first commit

This commit is contained in:
jerryjzhang
2023-06-12 18:44:01 +08:00
commit dc4fc69b57
879 changed files with 573090 additions and 0 deletions

29
webapp/.gitignore vendored Normal file
View File

@@ -0,0 +1,29 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
/dist
package-lock.json
yarn.lock
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-error.log*

3
webapp/README_CN.md Normal file
View File

@@ -0,0 +1,3 @@
开发模式下执行命令sh ./start-fe-dev.sh
等任务启动完成后在浏览器输入localhost:9000查看页面

6
webapp/lerna.json Normal file
View File

@@ -0,0 +1,6 @@
{
"packages": [
"packages/*"
],
"version": "independent"
}

7
webapp/package.json Normal file
View File

@@ -0,0 +1,7 @@
{
"name": "root",
"private": true,
"devDependencies": {
"lerna": "^4.0.0"
}
}

28
webapp/packages/chat-sdk/.gitignore vendored Normal file
View File

@@ -0,0 +1,28 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
/dist
package-lock.json
yarn.lock
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@@ -0,0 +1,24 @@
module.exports = {
"printWidth": 100, // 超过最大值换行
"overrides": [
{
"files": ".prettierrc",
"options": { "parser": "json" }
}
],
"tabWidth": 2, // 缩进字节数
"useTabs": false, // 缩进不使用tab使用空格
"semi": true, // 句尾添加分号
"singleQuote": true, // 使用单引号代替双引号
"proseWrap": "preserve", // 默认值。因为使用了一些折行敏感型的渲染器如GitHub comment而按照markdown文本样式进行折行
"arrowParens": "avoid", // (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid省略括号
"bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
"endOfLine": "auto", // 结尾是 \n \r \n\r auto
"eslintIntegration": false, //不让prettier使用eslint的代码格式进行校验
"htmlWhitespaceSensitivity": "ignore",
"ignorePath": ".prettierignore", // 不使用prettier格式化的文件填写在项目的.prettierignore文件中
"jsxBracketSameLine": false, // 在jsx中把'>' 是否单独放一行
"jsxSingleQuote": false, // 在jsx中使用单引号代替双引号 "prettier.parser": "babylon", // 格式化的解析器默认是babylon
"requireConfig": false, // Require a 'prettierconfig' to format prettier
"trailingComma": "es5", // 在对象或数组最后一个元素后面是否加逗号在ES5中加尾逗号
}

View File

@@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

View File

@@ -0,0 +1,104 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
`${paths.dotenv}.${NODE_ENV}`,
paths.dotenv,
].filter(Boolean);
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
})
);
}
});
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebook/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of webpack shims.
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in webpack configuration.
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether were running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
// We support configuring the sockjs pathname during development.
// These settings let a developer run multiple simultaneous projects.
// They are used as the connection `hostname`, `pathname` and `port`
// in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
// and `sockPort` options in webpack-dev-server.
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
// Whether or not react-refresh is enabled.
// It is defined here so it is available in the webpackHotDevClient.
FAST_REFRESH: process.env.FAST_REFRESH !== 'false',
}
);
// Stringify all values so we can feed into webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;

View File

@@ -0,0 +1,66 @@
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const chalk = require('react-dev-utils/chalk');
const paths = require('./paths');
// Ensure the certificate and key provided are valid and if not
// throw an easy to debug error
function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
let encrypted;
try {
// publicEncrypt will throw an error with an invalid cert
encrypted = crypto.publicEncrypt(cert, Buffer.from('test'));
} catch (err) {
throw new Error(
`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
);
}
try {
// privateDecrypt will throw an error with an invalid key
crypto.privateDecrypt(key, encrypted);
} catch (err) {
throw new Error(
`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
err.message
}`
);
}
}
// Read file and throw an error if it doesn't exist
function readEnvFile(file, type) {
if (!fs.existsSync(file)) {
throw new Error(
`You specified ${chalk.cyan(
type
)} in your env, but the file "${chalk.yellow(file)}" can't be found.`
);
}
return fs.readFileSync(file);
}
// Get the https config
// Return cert files if provided in env, otherwise just true or false
function getHttpsConfig() {
const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env;
const isHttps = HTTPS === 'true';
if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE);
const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE);
const config = {
cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
};
validateKeyAndCerts({ ...config, keyFile, crtFile });
return config;
}
return isHttps;
}
module.exports = getHttpsConfig;

View File

@@ -0,0 +1,29 @@
'use strict';
const babelJest = require('babel-jest').default;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
babelrc: false,
configFile: false,
});

View File

@@ -0,0 +1,14 @@
'use strict';
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
},
};

View File

@@ -0,0 +1,40 @@
'use strict';
const path = require('path');
const camelcase = require('camelcase');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
if (filename.match(/\.svg$/)) {
// Based on how SVGR generates a component name:
// https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
const pascalCaseFilename = camelcase(path.parse(filename).name, {
pascalCase: true,
});
const componentName = `Svg${pascalCaseFilename}`;
return `const React = require('react');
module.exports = {
__esModule: true,
default: ${assetFilename},
ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
return {
$$typeof: Symbol.for('react.element'),
type: 'svg',
ref: ref,
key: null,
props: Object.assign({}, props, {
children: ${assetFilename}
})
};
}),
};`;
}
return `module.exports = ${assetFilename};`;
},
};

View File

@@ -0,0 +1,134 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const chalk = require('react-dev-utils/chalk');
const resolve = require('resolve');
/**
* Get additional module paths based on the baseUrl of a compilerOptions object.
*
* @param {Object} options
*/
function getAdditionalModulePaths(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return '';
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
// the default behavior.
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
return null;
}
// Allow the user set the `baseUrl` to `appSrc`.
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
return [paths.appSrc];
}
// If the path is equal to the root directory we ignore it here.
// We don't want to allow importing from the root directly as source files are
// not transpiled outside of `src`. We do allow importing them with the
// absolute path (e.g. `src/Components/Button.js`) but we set that up with
// an alias.
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return null;
}
// Otherwise, throw an error.
throw new Error(
chalk.red.bold(
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
' Create React App does not support other values at this time.'
)
);
}
/**
* Get webpack aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getWebpackAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
src: paths.appSrc,
};
}
}
/**
* Get jest aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getJestAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
'^src/(.*)$': '<rootDir>/src/$1',
};
}
}
function getModules() {
// Check if TypeScript is setup
const hasTsConfig = fs.existsSync(paths.appTsConfig);
const hasJsConfig = fs.existsSync(paths.appJsConfig);
if (hasTsConfig && hasJsConfig) {
throw new Error(
'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
);
}
let config;
// If there's a tsconfig.json we assume it's a
// TypeScript project and set up the config
// based on tsconfig.json
if (hasTsConfig) {
const ts = require(resolve.sync('typescript', {
basedir: paths.appNodeModules,
}));
config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}
config = config || {};
const options = config.compilerOptions || {};
const additionalModulePaths = getAdditionalModulePaths(options);
return {
additionalModulePaths: additionalModulePaths,
webpackAliases: getWebpackAliases(options),
jestAliases: getJestAliases(options),
hasTsConfig,
};
}
module.exports = getModules();

View File

@@ -0,0 +1,77 @@
'use strict';
const path = require('path');
const fs = require('fs');
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const publicUrlOrPath = getPublicUrlOrPath(
process.env.NODE_ENV === 'development',
require(resolveApp('package.json')).homepage,
process.env.PUBLIC_URL
);
const buildPath = process.env.BUILD_PATH || 'build';
const moduleFileExtensions = [
'web.mjs',
'mjs',
'web.js',
'js',
'web.ts',
'ts',
'web.tsx',
'tsx',
'json',
'web.jsx',
'jsx',
];
// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find(extension =>
fs.existsSync(resolveFn(`${filePath}.${extension}`))
);
if (extension) {
return resolveFn(`${filePath}.${extension}`);
}
return resolveFn(`${filePath}.js`);
};
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp(buildPath),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
appJsConfig: resolveApp('jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
appWebpackCache: resolveApp('node_modules/.cache'),
appTsBuildInfoFile: resolveApp('node_modules/.cache/tsconfig.tsbuildinfo'),
swSrc: resolveModule(resolveApp, 'src/service-worker'),
publicUrlOrPath,
};
module.exports.moduleFileExtensions = moduleFileExtensions;

View File

@@ -0,0 +1,785 @@
'use strict';
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const ESLintPlugin = require('eslint-webpack-plugin');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin =
process.env.TSC_COMPILE_ON_ERROR === 'true'
? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
: require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash');
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime');
const reactRefreshWebpackPluginRuntimeEntry = require.resolve(
'@pmmmwh/react-refresh-webpack-plugin'
);
const babelRuntimeEntry = require.resolve('babel-preset-react-app');
const babelRuntimeEntryHelpers = require.resolve(
'@babel/runtime/helpers/esm/assertThisInitialized',
{ paths: [babelRuntimeEntry] }
);
const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', {
paths: [babelRuntimeEntry],
});
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// Check if Tailwind config exists
const useTailwind = fs.existsSync(
path.join(paths.appPath, 'tailwind.config.js')
);
// Get the path to the uncompiled service worker (if it exists).
const swSrc = paths.swSrc;
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function (webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// Variable used for enabling profiling in Production
// passed into alias object. Uses a flag if passed into the build command
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
// We will provide `paths.publicUrlOrPath` to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
// Get environment variables to inject into our app.
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const shouldUseReactRefresh = env.raw.FAST_REFRESH;
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
// css is located in `static/css`, use '../../' to locate index.html folder
// in production `paths.publicUrlOrPath` can be a relative path
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
config: false,
plugins: !useTailwind
? [
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
},
],
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
'postcss-normalize',
]
: [
'tailwindcss',
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
},
],
],
},
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
root: paths.appSrc,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
return {
target: ['browserslist'],
// Webpack noise constrained to errors and warnings
stats: 'errors-warnings',
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: paths.appIndexJs,
output: {
// The build folder.
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
assetModuleFilename: 'static/media/[name].[hash][ext]',
// webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: paths.publicUrlOrPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
},
cache: {
type: 'filesystem',
version: createEnvironmentHash(env.raw),
cacheDirectory: paths.appWebpackCache,
store: 'pack',
buildDependencies: {
defaultWebpack: ['webpack/lib/'],
config: [__filename],
tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f =>
fs.existsSync(f)
),
},
},
infrastructureLogging: {
level: 'none',
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending further investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
}),
// This is only used in production mode
new CssMinimizerPlugin(),
],
},
resolve: {
// This allows you to set a fallback for where webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [
paths.appPackageJson,
reactRefreshRuntimeEntry,
reactRefreshWebpackPluginRuntimeEntry,
babelRuntimeEntry,
babelRuntimeEntryHelpers,
babelRuntimeRegenerator,
]),
],
},
module: {
strictExportPresence: true,
rules: [
// Handle node_modules packages that contain sourcemaps
shouldUseSourceMap && {
enforce: 'pre',
exclude: /@babel(?:\/|\\{1,2})runtime/,
test: /\.(js|mjs|jsx|ts|tsx|css)$/,
loader: require.resolve('source-map-loader'),
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// TODO: Merge this config once `image/avif` is in the mime-db
// https://github.com/jshttp/mime-db
{
test: [/\.avif$/],
type: 'asset',
mimetype: 'image/avif',
parser: {
dataUrlCondition: {
maxSize: imageInlineSizeLimit,
},
},
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: imageInlineSizeLimit,
},
},
},
{
test: /\.svg$/,
use: [
{
loader: require.resolve('@svgr/webpack'),
options: {
prettier: false,
svgo: false,
svgoConfig: {
plugins: [{ removeViewBox: false }],
},
titleProp: true,
ref: true,
},
},
{
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash].[ext]',
},
},
],
issuer: {
and: [/\.(ts|tsx|js|jsx|md|mdx)$/],
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
plugins: [
isEnvDevelopment &&
shouldUseReactRefresh &&
require.resolve('react-refresh/babel'),
].filter(Boolean),
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// Babel sourcemaps are needed for debugging into node_modules
// code. Without the options below, debuggers like VSCode
// show incorrect code and set breakpoints on the wrong lines.
sourceMaps: shouldUseSourceMap,
inputSourceMap: shouldUseSourceMap,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'less-loader'
),
sideEffects: true,
},
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
},
'less-loader'
)
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
type: 'asset/resource',
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
].filter(Boolean),
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
// Inlines the webpack runtime script. This script is too small to warrant
// a network request.
// https://github.com/facebook/create-react-app/issues/5358
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// It will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Experimental hot reloading for React .
// https://github.com/facebook/react/tree/main/packages/react-refresh
isEnvDevelopment &&
shouldUseReactRefresh &&
new ReactRefreshWebpackPlugin({
overlay: false,
}),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse
// `index.html`
// - "entrypoints" key: Array of files which are included in `index.html`,
// can be used to reconstruct the HTML if necessary
new WebpackManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the webpack build.
isEnvProduction &&
fs.existsSync(swSrc) &&
new WorkboxWebpackPlugin.InjectManifest({
swSrc,
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
// Bump up the default maximum size (2mb) that's precached,
// to make lazy-loading failure scenarios less likely.
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}),
// TypeScript type checking
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
async: isEnvDevelopment,
typescript: {
typescriptPath: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
configOverwrite: {
compilerOptions: {
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
skipLibCheck: true,
inlineSourceMap: false,
declarationMap: false,
noEmit: true,
incremental: true,
tsBuildInfoFile: paths.appTsBuildInfoFile,
},
},
context: paths.appPath,
diagnosticOptions: {
syntactic: true,
},
mode: 'write-references',
// profile: true,
},
issue: {
// This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
include: [
{ file: '../**/src/**/*.{ts,tsx}' },
{ file: '**/src/**/*.{ts,tsx}' },
],
exclude: [
{ file: '**/src/**/__tests__/**' },
{ file: '**/src/**/?(*.){spec|test}.*' },
{ file: '**/src/setupProxy.*' },
{ file: '**/src/setupTests.*' },
],
},
logger: {
infrastructure: 'silent',
},
}),
!disableESLintPlugin &&
new ESLintPlugin({
// Plugin options
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
context: paths.appSrc,
cache: true,
cacheLocation: path.resolve(
paths.appNodeModules,
'.cache/.eslintcache'
),
// ESLint class options
cwd: paths.appPath,
resolvePluginsRelativeTo: __dirname,
baseConfig: {
extends: [require.resolve('eslint-config-react-app/base')],
rules: {
...(!hasJsxRuntime && {
'react/react-in-jsx-scope': 'error',
}),
},
},
}),
].filter(Boolean),
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
};

View File

@@ -0,0 +1,9 @@
'use strict';
const { createHash } = require('crypto');
module.exports = env => {
const hash = createHash('md5');
hash.update(JSON.stringify(env));
return hash.digest('hex');
};

View File

@@ -0,0 +1,127 @@
'use strict';
const fs = require('fs');
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware');
const paths = require('./paths');
const getHttpsConfig = require('./getHttpsConfig');
const host = process.env.HOST || '0.0.0.0';
const sockHost = process.env.WDS_SOCKET_HOST;
const sockPath = process.env.WDS_SOCKET_PATH; // default: '/ws'
const sockPort = process.env.WDS_SOCKET_PORT;
module.exports = function (proxy, allowedHost) {
const disableFirewall =
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true';
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebook/create-react-app/issues/2271
// https://github.com/facebook/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
// Note: ["localhost", ".localhost"] will support subdomains - but we might
// want to allow setting the allowedHosts manually for more complex setups
allowedHosts: disableFirewall ? 'all' : [allowedHost],
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
},
// Enable gzip compression of generated files.
compress: true,
static: {
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
directory: paths.appPublic,
publicPath: [paths.publicUrlOrPath],
// By default files from `contentBase` will not trigger a page reload.
watch: {
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebook/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebook/create-react-app/issues/1065
ignored: ignoredFiles(paths.appSrc),
},
},
client: {
webSocketURL: {
// Enable custom sockjs pathname for websocket connection to hot reloading server.
// Enable custom sockjs hostname, pathname and port for websocket connection
// to hot reloading server.
hostname: sockHost,
pathname: sockPath,
port: sockPort,
},
overlay: {
errors: true,
warnings: false,
},
},
devMiddleware: {
// It is important to tell WebpackDevServer to use the same "publicPath" path as
// we specified in the webpack config. When homepage is '.', default to serving
// from the root.
// remove last slash so user can land on `/test` instead of `/test/`
publicPath: paths.publicUrlOrPath.slice(0, -1),
},
https: getHttpsConfig(),
host,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
index: paths.publicUrlOrPath,
},
// `proxy` is run between `before` and `after` `webpack-dev-server` hooks
proxy,
onBeforeSetupMiddleware(devServer) {
// Keep `evalSourceMapMiddleware`
// middlewares before `redirectServedPath` otherwise will not have any effect
// This lets us fetch source contents from webpack for the error overlay
devServer.app.use(evalSourceMapMiddleware(devServer));
if (fs.existsSync(paths.proxySetup)) {
// This registers user provided middleware for proxy reasons
require(paths.proxySetup)(devServer.app);
}
},
onAfterSetupMiddleware(devServer) {
// Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match
devServer.app.use(redirectServedPath(paths.publicUrlOrPath));
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
devServer.app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath));
},
};
};

View File

@@ -0,0 +1,194 @@
{
"name": "supersonic-chat-sdk",
"version": "0.1.6",
"main": "dist/index.es.js",
"module": "dist/index.es.js",
"unpkg": "dist/index.umd.js",
"types": "dist/index.d.ts",
"dependencies": {
"antd": "^5.5.0",
"axios": "^1.4.0",
"classnames": "^2.3.2",
"echarts": "^5.4.2",
"moment": "^2.29.4",
"react-spinners": "^0.13.8",
"tslib": "^2.5.2"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"scripts": {
"start": "npm run build-es",
"start:dev": "node scripts/start.js",
"clean": "rimraf ./dist",
"build": "npm run clean && npm run build-es",
"test": "node scripts/test.js",
"build-ts": "tsc -p tsconfig.build.json",
"build-css": "lessc ./src/styles/index.less ./dist/index.css",
"build-es": "rollup --config rollup/rollup.esm.config.mjs",
"build-umd": "rollup --config rollup/rollup.umd.config.mjs"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
],
"rules": {
"react-hooks/exhaustive-deps": 0
}
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all",
"defaults",
"not ie < 8",
"last 2 versions",
"> 1%",
"iOS 7",
"last 3 iOS versions"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
"@rollup/plugin-commonjs": "^25.0.0",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^15.0.2",
"@rollup/plugin-replace": "^5.0.2",
"@svgr/webpack": "^5.5.0",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.31",
"@types/react": "^18.2.6",
"@types/react-dom": "^18.2.4",
"autoprefixer": "^10.4.14",
"babel-jest": "^27.4.2",
"babel-loader": "^8.2.3",
"babel-plugin-named-asset-import": "^0.3.8",
"babel-preset-react-app": "^10.0.1",
"bfj": "^7.0.2",
"browserslist": "^4.18.1",
"camelcase": "^6.2.1",
"case-sensitive-paths-webpack-plugin": "^2.4.0",
"css-loader": "^6.5.1",
"css-minimizer-webpack-plugin": "^3.2.0",
"cssnano": "^6.0.1",
"dotenv": "^10.0.0",
"dotenv-expand": "^5.1.0",
"eslint": "^8.3.0",
"eslint-config-react-app": "^7.0.1",
"eslint-webpack-plugin": "^3.1.1",
"file-loader": "^6.2.0",
"fs-extra": "^10.0.0",
"html-webpack-plugin": "^5.5.0",
"http-proxy-middleware": "^2.0.6",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.4.3",
"jest-resolve": "^27.4.2",
"jest-watch-typeahead": "^1.0.0",
"less": "^4.1.3",
"less-loader": "^11.1.0",
"mini-css-extract-plugin": "^2.4.5",
"postcss": "^8.4.4",
"postcss-flexbugs-fixes": "^5.0.2",
"postcss-loader": "^6.2.1",
"postcss-modules": "^6.0.0",
"postcss-normalize": "^10.0.1",
"postcss-preset-env": "^7.0.1",
"prompts": "^2.4.2",
"react": "^18.2.0",
"react-app-polyfill": "^3.0.0",
"react-dev-utils": "^12.0.1",
"react-dom": "^18.2.0",
"react-refresh": "^0.11.0",
"resolve": "^1.20.0",
"resolve-url-loader": "^4.0.0",
"rollup": "^3.22.1",
"rollup-plugin-exclude-dependencies-from-bundle": "^1.1.23",
"rollup-plugin-less": "^1.1.3",
"rollup-plugin-postcss": "^4.0.2",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript2": "^0.34.1",
"sass-loader": "^12.3.0",
"semver": "^7.3.5",
"source-map-loader": "^3.0.0",
"style-loader": "^3.3.1",
"tailwindcss": "^3.0.2",
"terser-webpack-plugin": "^5.2.5",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4",
"webpack": "^5.64.4",
"webpack-dev-server": "^4.6.0",
"webpack-manifest-plugin": "^4.0.2",
"workbox-webpack-plugin": "^6.4.1"
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.ts"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jsdom",
"transform": {
"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/config/jest/babelTransform.js",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
"^.+\\.module\\.(css|sass|scss)$"
],
"modulePaths": [],
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
"node"
],
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
],
"resetMocks": true
},
"babel": {
"presets": [
"react-app"
]
},
"engines": {
"node": ">=14.18.0"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 551 B

View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Supersonic chat</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@@ -0,0 +1,31 @@
import typescript from 'rollup-plugin-typescript2'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import less from 'rollup-plugin-less'
import postcss from 'rollup-plugin-postcss'
import cssnano from 'cssnano'
const overrides = {
compilerOptions: { declaration: true },
exclude: ["src/**/*.test.tsx", "src/**/*.stories.tsx", "src/**/*.stories.mdx", "src/setupTests.ts"]
}
const config = {
input: 'src/index.tsx',
plugins: [
nodeResolve(),
commonjs(),
json(),
typescript({ tsconfigOverride: overrides }),
less({ output: 'dist/index.css' }),
// postcss({
// plugins: [
// cssnano()
// ]
// })
],
}
export default config

View File

@@ -0,0 +1,23 @@
import basicConfig from './rollup.config.mjs'
// import { terser } from "rollup-plugin-terser"
import excludeDependenciesFromBundle from "rollup-plugin-exclude-dependencies-from-bundle"
const config = {
...basicConfig,
output: [
{
file: 'dist/index.es.js',
format: 'es',
// plugins: [
// terser()
// ],
},
],
plugins: [
...basicConfig.plugins,
excludeDependenciesFromBundle(),
]
}
export default config

View File

@@ -0,0 +1,32 @@
import basicConfig from './rollup.config.mjs'
import { terser } from "rollup-plugin-terser"
import replace from '@rollup/plugin-replace'
const config = {
...basicConfig,
output: [
{
name: 'chat-sdk',
file: 'dist/index.umd.js',
format: 'umd',
exports: 'named',
globals: {
'react': 'React',
'react-dom': 'ReactDOM',
'axios': 'Axios'
},
plugins: [
terser()
],
},
],
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
...basicConfig.plugins
],
external: ['react', 'react-dom', 'axios']
}
export default config

View File

@@ -0,0 +1,217 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('react-dev-utils/chalk');
const fs = require('fs-extra');
const bfj = require('bfj');
const webpack = require('webpack');
const configFactory = require('../config/webpack.config');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
const argv = process.argv.slice(2);
const writeStatsJson = argv.indexOf('--stats') !== -1;
// Generate configuration
const config = configFactory('production');
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
return measureFileSizesBeforeBuild(paths.appBuild);
})
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrlOrPath;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
if (tscCompileOnError) {
console.log(
chalk.yellow(
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
)
);
printBuildError(err);
} else {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
}
)
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
const compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
let messages;
if (err) {
if (!err.message) {
return reject(err);
}
let errMessage = err.message;
// Add additional information for postcss errors
if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
errMessage +=
'\nCompileError: Begins at CSS selector ' +
err['postcssNode'].selector;
}
messages = formatWebpackMessages({
errors: [errMessage],
warnings: [],
});
} else {
messages = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true })
);
}
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
// Ignore sourcemap warnings in CI builds. See #8227 for more info.
const filteredWarnings = messages.warnings.filter(
w => !/Failed to parse source map/.test(w)
);
if (filteredWarnings.length) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(filteredWarnings.join('\n\n')));
}
}
const resolveArgs = {
stats,
previousFileSizes,
warnings: messages.warnings,
};
if (writeStatsJson) {
return bfj
.write(paths.appBuild + '/bundle-stats.json', stats.toJson())
.then(() => resolve(resolveArgs))
.catch(error => reject(new Error(error)));
}
return resolve(resolveArgs);
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}

View File

@@ -0,0 +1,154 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const semver = require('semver');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
const getClientEnvironment = require('../config/env');
const react = require(require.resolve('react', { paths: [paths.appPath] }));
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(
`Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}`
);
console.log();
}
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
return choosePort(HOST, DEFAULT_PORT);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const config = configFactory('development');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const useTypeScript = fs.existsSync(paths.appTsConfig);
const urls = prepareUrls(
protocol,
HOST,
port,
paths.publicUrlOrPath.slice(0, -1)
);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler({
appName,
config,
urls,
useYarn,
useTypeScript,
webpack,
});
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(
proxySetting,
paths.appPublic,
paths.publicUrlOrPath
);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = {
...createDevServerConfig(proxyConfig, urls.lanUrlForConfig),
host: HOST,
port,
};
const devServer = new WebpackDevServer(serverConfig, compiler);
// Launch WebpackDevServer.
devServer.startCallback(() => {
if (isInteractive) {
clearConsole();
}
if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) {
console.log(
chalk.yellow(
`Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.`
)
);
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function (sig) {
process.on(sig, function () {
devServer.close();
process.exit();
});
});
if (process.env.CI !== 'true') {
// Gracefully exit when stdin ends
process.stdin.on('end', function () {
devServer.close();
process.exit();
});
}
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});

View File

@@ -0,0 +1,52 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const jest = require('jest');
const execSync = require('child_process').execSync;
let argv = process.argv.slice(2);
function isInGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function isInMercurialRepository() {
try {
execSync('hg --cwd . root', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
// Watch unless on CI or explicitly running all tests
if (
!process.env.CI &&
argv.indexOf('--watchAll') === -1 &&
argv.indexOf('--watchAll=false') === -1
) {
// https://github.com/facebook/create-react-app/issues/5210
const hasSourceControl = isInGitRepository() || isInMercurialRepository();
argv.push(hasSourceControl ? '--watch' : '--watchAll');
}
jest.run(argv);

View File

@@ -0,0 +1,50 @@
import { MsgValidTypeEnum } from './type';
export enum NumericUnit {
None = '无',
TenThousand = '万',
EnTenThousand = 'w',
OneHundredMillion = '亿',
Thousand = 'k',
Million = 'M',
Giga = 'G',
}
export const PRIMARY_COLOR = '#f87653';
export const CHART_BLUE_COLOR = '#446dff';
export const CHAT_BLUE = '#1b4aef';
export const CHART_SECONDARY_COLOR = 'rgba(153, 153, 153, 0.3)';
export const CLS_PREFIX = 'ss-chat';
export const DATE_TYPES = {
DAY: [{ label: '近7天', value: 7 }, { label: '近30天', value: 30 }, { label: '近60天', value: 60 }, { label: '近90天', value: 90 }],
WEEK: [{ label: '近4周', value: 4 }, { label: '近12周', value: 12 }, { label: '近24周', value: 24 }, { label: '近52周', value: 52 }],
MONTH: [{ label: '近3个月', value: 3 }, { label: '近6个月', value: 6 }, { label: '近12个月', value: 12 }, { label: '近24个月', value: 24 }],
};
export const THEME_COLOR_LIST = [
'#3369FF',
'#36D2B8',
'#DB8D76',
'#47B359',
'#8545E6',
'#E0B18B',
'#7258F3',
'#0095FF',
'#52CC8F',
'#6675FF',
'#CC516E',
'#5CA9E6',
];
export const PARSE_ERROR_TIP = '小Q不太懂您说什么呐回去一定补充知识';
export const MSG_VALID_TIP = {
[MsgValidTypeEnum.SEARCH_EXCEPTION]: '数据查询异常',
[MsgValidTypeEnum.INVALID]: '小Q不太懂您说什么呐回去一定补充知识',
};
export const PREFIX_CLS = 'ss-chat';

View File

@@ -0,0 +1,148 @@
export type SearchRecommendItem = {
complete: boolean;
domainId: number;
domainName: string;
recommend: string;
subRecommend: string;
schemaElementType: string;
};
export type FieldType = {
bizName: string;
id: number;
name: string;
status: number;
value: string;
};
export type DomainInfoType = {
bizName: string;
itemId: number;
name: string;
primaryEntityBizName: string;
value: string;
words: string[];
};
export type EntityInfoType = {
domainInfo: DomainInfoType;
dimensions: FieldType[];
metrics: FieldType[];
entityId: number;
};
export type DateInfoType = {
dateList: any[];
dateMode: number;
period: string;
startDate: string;
endDate: string;
text: string;
unit: number;
};
export type FilterItemType = {
elementID: number;
name: string;
operator: string;
type: string;
value: string;
};
export type ChatContextType = {
aggType: string;
domainId: number;
domainName: string;
dateInfo: DateInfoType;
dimensions: FieldType[];
metrics: FieldType[];
entity: number;
filters: FilterItemType[];
};
export enum MsgValidTypeEnum {
NORMAL = 0,
SEARCH_EXCEPTION = 1,
EMPTY = 2,
INVALID = 3,
};
export type MsgDataType = {
id: number;
question: string;
aggregateType: string;
appletResponse: string;
chatContext: ChatContextType;
entityInfo: EntityInfoType;
queryAuthorization: any;
queryColumns: ColumnType[];
queryResults: any[];
queryId: number;
queryMode: string;
queryState: MsgValidTypeEnum;
};
export type QueryDataType = {
queryColumns: ColumnType[];
queryResults: any[];
};
export type ColumnType = {
authorized: boolean;
name: string;
nameEn: string;
showType: string;
type: string;
dataFormatType: string;
dataFormat: {
decimalPlaces: number;
needmultiply100: boolean;
};
};
export enum SemanticTypeEnum {
DOMAIN = 'DOMAIN',
DIMENSION = 'DIMENSION',
METRIC = 'METRIC',
VALUE = 'VALUE',
};
export const SEMANTIC_TYPE_MAP = {
[SemanticTypeEnum.DOMAIN]: '主题域',
[SemanticTypeEnum.DIMENSION]: '维度',
[SemanticTypeEnum.METRIC]: '指标',
[SemanticTypeEnum.VALUE]: '维度值',
};
export type SuggestionItemType = {
domain: number;
name: string;
bizName: string
};
export type SuggestionType = {
dimensions: SuggestionItemType[];
metrics: SuggestionItemType[];
};
export type SuggestionDataType = {
currentAggregateType: string,
columns: ColumnType[],
mainEntity: EntityInfoType,
suggestions: SuggestionType,
};
export type HistoryMsgItemType = {
questionId: number;
queryText: string;
queryResponse: MsgDataType;
chatId: number;
createTime: string;
feedback: string;
score: number;
};
export type HistoryType = {
hasNextPage: boolean;
list: HistoryMsgItemType[];
};

View File

@@ -0,0 +1,17 @@
import Message from '../ChatMsg/Message';
import { PREFIX_CLS } from '../../common/constants';
type Props = {
data: any;
};
const Text: React.FC<Props> = ({ data }) => {
const prefixCls = `${PREFIX_CLS}-item`;
return (
<Message position="left" bubbleClassName={`${prefixCls}-text-bubble`} noWaterMark>
<div className={`${prefixCls}-text`}>{data}</div>
</Message>
);
};
export default Text;

View File

@@ -0,0 +1,19 @@
import { CHAT_BLUE, PREFIX_CLS } from '../../common/constants';
import { Spin } from 'antd';
import BeatLoader from 'react-spinners/BeatLoader';
import Message from '../ChatMsg/Message';
const Typing = () => {
const prefixCls = `${PREFIX_CLS}-item`;
return (
<Message position="left" bubbleClassName={`${prefixCls}-typing-bubble`}>
<Spin
spinning={true}
indicator={<BeatLoader color={CHAT_BLUE} size={10} />}
className={`${prefixCls}-typing`}
/>
</Message>
);
};
export default Typing;

View File

@@ -0,0 +1,154 @@
import { MsgDataType, MsgValidTypeEnum, SuggestionDataType } from '../../common/type';
import { useEffect, useState } from 'react';
import Typing from './Typing';
import ChatMsg from '../ChatMsg';
import { querySuggestionInfo, chatQuery } from '../../service';
import { MSG_VALID_TIP, PARSE_ERROR_TIP, PREFIX_CLS } from '../../common/constants';
import Text from './Text';
import Suggestion from '../Suggestion';
import Tools from '../Tools';
import SemanticDetail from '../SemanticDetail';
type Props = {
msg: string;
conversationId?: number;
classId?: number;
isLastMessage?: boolean;
suggestionEnable?: boolean;
msgData?: MsgDataType;
onLastMsgDataLoaded?: (data: MsgDataType) => void;
onSelectSuggestion?: (value: string) => void;
onUpdateMessageScroll?: () => void;
};
const ChatItem: React.FC<Props> = ({
msg,
conversationId,
classId,
isLastMessage,
suggestionEnable,
msgData,
onLastMsgDataLoaded,
onSelectSuggestion,
onUpdateMessageScroll,
}) => {
const [data, setData] = useState<MsgDataType>();
const [suggestionData, setSuggestionData] = useState<SuggestionDataType>();
const [loading, setLoading] = useState(false);
const [metricInfoList, setMetricInfoList] = useState<any[]>([]);
const [tip, setTip] = useState('');
const setMsgData = (value: MsgDataType) => {
setData(value);
};
const updateData = (res: Result<MsgDataType>) => {
if (res.code === 401) {
setTip(res.msg);
return false;
}
if (res.code !== 200) {
setTip(PARSE_ERROR_TIP);
return false;
}
const { queryColumns, queryResults, queryState } = res.data || {};
if (queryState !== MsgValidTypeEnum.NORMAL && queryState !== MsgValidTypeEnum.EMPTY) {
setTip(MSG_VALID_TIP[queryState || MsgValidTypeEnum.INVALID]);
return false;
}
if (queryColumns && queryColumns.length > 0 && queryResults) {
setMsgData(res.data);
setTip('');
return true;
}
setTip(PARSE_ERROR_TIP);
return false;
};
const updateSuggestionData = (semanticRes: MsgDataType, suggestionRes: any) => {
const { aggregateType, queryColumns, entityInfo } = semanticRes;
setSuggestionData({
currentAggregateType: aggregateType,
columns: queryColumns || [],
mainEntity: entityInfo,
suggestions: suggestionRes,
});
};
const getSuggestions = async (domainId: number, semanticResData: MsgDataType) => {
if (!domainId) {
return;
}
const res = await querySuggestionInfo(domainId);
updateSuggestionData(semanticResData, res.data.data);
};
const onSendMsg = async () => {
setLoading(true);
const semanticRes = await chatQuery(msg, conversationId, classId);
const semanticValid = updateData(semanticRes.data);
if (suggestionEnable && semanticValid) {
const semanticResData = semanticRes.data.data;
await getSuggestions(semanticResData.entityInfo?.domainInfo?.itemId, semanticRes.data.data);
} else {
setSuggestionData(undefined);
}
if (onLastMsgDataLoaded) {
onLastMsgDataLoaded(semanticRes.data.data);
}
setLoading(false);
};
useEffect(() => {
if (msgData) {
updateData({ code: 200, data: msgData, msg: 'success' });
} else if (msg) {
onSendMsg();
}
}, [msg, msgData]);
if (loading) {
return <Typing />;
}
if (tip) {
return <Text data={tip} />;
}
if (!data) {
return null;
}
const onCheckMetricInfo = (data: any) => {
setMetricInfoList([...metricInfoList, data]);
if (onUpdateMessageScroll) {
onUpdateMessageScroll();
}
};
const prefixCls = `${PREFIX_CLS}-item`;
return (
<div>
<ChatMsg data={data} onCheckMetricInfo={onCheckMetricInfo} />
<Tools isLastMessage={isLastMessage} />
{suggestionEnable && suggestionData && isLastMessage && (
<Suggestion {...suggestionData} onSelect={onSelectSuggestion} />
)}
<div className={`${prefixCls}-metric-info-list`}>
{metricInfoList.map(item => (
<SemanticDetail
dataSource={item}
onDimensionSelect={(value: string) => {
if (onSelectSuggestion) {
onSelectSuggestion(value);
}
}}
/>
))}
</div>
</div>
);
};
export default ChatItem;

View File

@@ -0,0 +1,38 @@
@import '../../styles/index.less';
@chat-item-prefix-cls: ~'@{supersonic-chat-prefix}-item';
.@{chat-item-prefix-cls} {
&-metric-info-list {
margin-top: 30px;
display: flex;
flex-direction: column;
row-gap: 30px;
}
&-typing {
width: 100%;
padding: 0 5px;
.ant-spin-dot {
width: 100% !important;
height: 100% !important;
}
}
&-typing-bubble {
width: fit-content;
padding: 16px !important;
}
&-text-bubble {
width: fit-content;
}
&-text {
line-height: 1.5;
white-space: pre-wrap;
overflow-wrap: break-word;
user-select: text;
}
}

View File

@@ -0,0 +1,30 @@
import { PREFIX_CLS } from '../../../common/constants';
type Props = {
domain: string;
onApplyAuth?: (domain: string) => void;
};
const ApplyAuth: React.FC<Props> = ({ domain, onApplyAuth }) => {
const prefixCls = `${PREFIX_CLS}-apply-auth`;
return (
<div className={prefixCls}>
{onApplyAuth ? (
<span
className={`${prefixCls}-apply`}
onClick={() => {
onApplyAuth(domain);
}}
>
</span>
) : (
'请联系管理员申请权限'
)}
</div>
);
};
export default ApplyAuth;

View File

@@ -0,0 +1,13 @@
@import '../../../styles/index.less';
@apply-auth-cls: ~'@{supersonic-chat-prefix}-apply-auth';
.@{apply-auth-cls} {
font-size: 14px;
color: var(--text-color);
&-apply {
color: var(--chat-blue);
cursor: pointer;
}
}

View File

@@ -0,0 +1,149 @@
import { CHART_BLUE_COLOR, CHART_SECONDARY_COLOR, PREFIX_CLS } from '../../../common/constants';
import { MsgDataType } from '../../../common/type';
import { getChartLightenColor, getFormattedValue } from '../../../utils/utils';
import type { ECharts } from 'echarts';
import * as echarts from 'echarts';
import React, { useEffect, useRef, useState } from 'react';
import NoPermissionChart from '../NoPermissionChart';
type Props = {
data: MsgDataType;
onApplyAuth?: (domain: string) => void;
};
const BarChart: React.FC<Props> = ({ data, onApplyAuth }) => {
const chartRef = useRef<any>();
const [instance, setInstance] = useState<ECharts>();
const { queryColumns, queryResults, entityInfo } = data;
const categoryColumnName =
queryColumns?.find(column => column.showType === 'CATEGORY')?.nameEn || '';
const metricColumn = queryColumns?.find(column => column.showType === 'NUMBER');
const metricColumnName = metricColumn?.nameEn || '';
const renderChart = () => {
let instanceObj: any;
if (!instance) {
instanceObj = echarts.init(chartRef.current);
setInstance(instanceObj);
} else {
instanceObj = instance;
}
const data = (queryResults || []).sort(
(a: any, b: any) => b[metricColumnName] - a[metricColumnName]
);
const xData = data.map(item => item[categoryColumnName]);
instanceObj.setOption({
legend: {
left: 0,
top: 0,
icon: 'rect',
itemWidth: 15,
itemHeight: 5,
},
xAxis: {
type: 'category',
axisTick: {
show: false,
},
axisLine: {
lineStyle: {
color: CHART_SECONDARY_COLOR,
},
},
axisLabel: {
width: 200,
overflow: 'truncate',
showMaxLabel: true,
hideOverlap: false,
interval: 0,
color: '#333',
rotate: 30,
},
data: xData,
},
yAxis: {
type: 'value',
splitLine: {
lineStyle: {
opacity: 0.3,
},
},
axisLabel: {
formatter: function (value: any) {
return value === 0 ? 0 : getFormattedValue(value);
},
},
},
tooltip: {
trigger: 'axis',
formatter: function (params: any[]) {
const param = params[0];
const valueLabels = params
.map(
(item: any) =>
`<div style="margin-top: 3px;">${
item.marker
} <span style="display: inline-block; width: 70px; margin-right: 12px;">${
item.seriesName
}</span><span style="display: inline-block; width: 90px; text-align: right; font-weight: 500;">${getFormattedValue(
item.value
)}</span></div>`
)
.join('');
return `${param.name}<br />${valueLabels}`;
},
},
grid: {
left: '2%',
right: '1%',
bottom: '3%',
top: 50,
containLabel: true,
},
series: {
type: 'bar',
name: metricColumn?.name,
barWidth: 20,
itemStyle: {
borderRadius: [10, 10, 0, 0],
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: CHART_BLUE_COLOR },
{ offset: 1, color: getChartLightenColor(CHART_BLUE_COLOR) },
]),
},
label: {
show: true,
position: 'top',
formatter: function ({ value }: any) {
return getFormattedValue(value);
},
},
data: data.map(item => {
return item[metricColumn?.nameEn || ''];
}),
},
});
instanceObj.resize();
};
useEffect(() => {
if (queryResults && queryResults.length > 0 && metricColumn?.authorized) {
renderChart();
}
}, [queryResults]);
if (!metricColumn?.authorized) {
return (
<NoPermissionChart
domain={entityInfo?.domainInfo.name || ''}
chartType="barChart"
onApplyAuth={onApplyAuth}
/>
);
}
return <div className={`${PREFIX_CLS}-bar`} ref={chartRef} />;
};
export default BarChart;

View File

@@ -0,0 +1,8 @@
@import '../../../styles/index.less';
@bar-cls: ~'@{supersonic-chat-prefix}-bar';
.@{bar-cls} {
height: 300px;
margin-top: 20px;
}

View File

@@ -0,0 +1,124 @@
import { EntityInfoType, ChatContextType } from '../../../common/type';
import moment from 'moment';
import { PREFIX_CLS } from '../../../common/constants';
type Props = {
position: 'left' | 'right';
width?: number | string;
height?: number | string;
bubbleClassName?: string;
noWaterMark?: boolean;
chatContext?: ChatContextType;
entityInfo?: EntityInfoType;
tip?: string;
aggregator?: string;
noTime?: boolean;
children?: React.ReactNode;
};
const Message: React.FC<Props> = ({
position,
width,
height,
children,
bubbleClassName,
chatContext,
entityInfo,
aggregator,
noTime,
}) => {
const { aggType, dateInfo, filters, metrics, domainName } = chatContext || {};
const prefixCls = `${PREFIX_CLS}-message`;
const timeSection =
!noTime && dateInfo?.text ? (
dateInfo.text
) : (
<div>{`${moment(dateInfo?.endDate).diff(dateInfo?.startDate, 'days') + 1}`}</div>
);
const metricSection =
metrics &&
metrics.map((metric, index) => {
let metricNode = <span className={`${PREFIX_CLS}-metric`}>{metric.name}</span>;
return (
<>
{metricNode}
{index < metrics.length - 1 && <span></span>}
</>
);
});
const aggregatorSection = aggregator !== 'tag' && aggType !== 'NONE' && aggType;
const hasFilterSection = filters && filters.length > 0;
const filterSection = hasFilterSection && (
<div className={`${prefixCls}-filter-section`}>
<div className={`${prefixCls}-field-name`}></div>
<div className={`${prefixCls}-filter-values`}>
{filters.map(filterItem => {
return (
<div className={`${prefixCls}-filter-item`} key={filterItem.name}>
{filterItem.name}{filterItem.value}
</div>
);
})}
</div>
</div>
);
const entityInfoList =
entityInfo?.dimensions?.filter(dimension => !dimension.bizName.includes('photo')) || [];
const hasEntityInfoSection =
entityInfoList.length > 0 && chatContext && chatContext.dimensions?.length > 0;
return (
<div className={prefixCls}>
<div className={`${prefixCls}-content`}>
<div className={`${prefixCls}-body`}>
<div
className={`${prefixCls}-bubble${bubbleClassName ? ` ${bubbleClassName}` : ''}`}
style={{ width, height }}
onClick={e => {
e.stopPropagation();
}}
>
{position === 'left' && chatContext && (
<div className={`${prefixCls}-top-bar`}>
{domainName}
{/* {dimensionSection} */}
{timeSection}
{metricSection}
{aggregatorSection}
{/* {tipSection} */}
</div>
)}
{(hasEntityInfoSection || hasFilterSection) && (
<div className={`${prefixCls}-info-bar`}>
{hasEntityInfoSection && (
<div className={`${prefixCls}-main-entity-info`}>
{entityInfoList.slice(0, 3).map(dimension => {
return (
<div className={`${prefixCls}-info-item`} key={dimension.bizName}>
<div className={`${prefixCls}-info-name`}>{dimension.name}</div>
<div className={`${prefixCls}-info-value`}>{dimension.value}</div>
</div>
);
})}
</div>
)}
{filterSection}
</div>
)}
<div className={`${prefixCls}-children`}>{children}</div>
</div>
</div>
</div>
</div>
);
};
export default Message;

View File

@@ -0,0 +1,89 @@
@import '../../../styles/index.less';
@msg-prefix-cls: ~'@{supersonic-chat-prefix}-message';
.@{msg-prefix-cls} {
&-content {
display: flex;
align-items: flex-start;
}
&-body {
width: 100%;
}
&-bubble {
box-sizing: border-box;
min-width: 1px;
max-width: 100%;
padding: 8px 16px 10px;
background: rgba(255, 255, 255, 0.8);
border: 1px solid transparent;
border-radius: 12px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.14), 0 0 2px rgba(0, 0, 0, 0.12);
}
&-top-bar {
display: flex;
align-items: center;
max-width: 100%;
padding: 4px 0 8px;
overflow-x: auto;
color: var(--text-color);
font-weight: 500;
font-size: 14px;
white-space: nowrap;
border-bottom: 1px solid rgba(0, 0, 0, 0.03);
}
&-filter-section {
display: flex;
align-items: center;
color: var(--text-color-secondary);
font-weight: normal;
font-size: 13px;
}
&-filter-item {
padding: 2px 12px;
color: var(--text-color-secondary);
background-color: #edf2f2;
border-radius: 13px;
}
&-tip {
margin-left: 6px;
color: var(--text-color-third);
}
&-info-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
margin-top: 20px;
column-gap: 20px;
}
&-main-entity-info {
display: flex;
flex-wrap: wrap;
align-items: center;
font-size: 13px;
column-gap: 20px;
}
&-info-item {
display: flex;
align-items: center;
}
&-info-Name {
color: var(--text-color-fourth);
}
&-info-value {
color: var(--text-color-secondary);
}
}

View File

@@ -0,0 +1,38 @@
import { PREFIX_CLS } from '../../../common/constants';
import { getFormattedValue } from '../../../utils/utils';
import ApplyAuth from '../ApplyAuth';
import { MsgDataType } from '../../../common/type';
type Props = {
data: MsgDataType;
onApplyAuth?: (domain: string) => void;
};
const MetricCard: React.FC<Props> = ({ data, onApplyAuth }) => {
const { queryColumns, queryResults, entityInfo } = data;
const indicatorColumn = queryColumns?.find(column => column.showType === 'NUMBER');
const indicatorColumnName = indicatorColumn?.nameEn || '';
const prefixCls = `${PREFIX_CLS}-metric-card`;
return (
<div className={prefixCls}>
<div className={`${prefixCls}-indicator`}>
{/* <div className={`${prefixCls}-date-range`}>
{startTime === endTime ? startTime : `${startTime} ~ ${endTime}`}
</div> */}
{!indicatorColumn?.authorized ? (
<ApplyAuth domain={entityInfo?.domainInfo.name || ''} onApplyAuth={onApplyAuth} />
) : (
<div className={`${prefixCls}-indicator-value`}>
{getFormattedValue(queryResults?.[0]?.[indicatorColumnName])}
</div>
)}
{/* <div className={`${prefixCls}-indicator-name`}>{query}</div> */}
</div>
</div>
);
};
export default MetricCard;

View File

@@ -0,0 +1,36 @@
@import '../../../styles/index.less';
@metric-card-prefix-cls: ~'@{supersonic-chat-prefix}-metric-card';
.@{metric-card-prefix-cls} {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 150px;
row-gap: 4px;
&-indicator {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
}
&-date-range {
color: var(--text-color-fourth);
font-size: 14px;
}
&-indicator-value {
color: var(--text-color);
font-weight: 600;
font-size: 30px;
}
&-indicator-name {
color: var(--text-color-fourth);
font-size: 14px;
}
}

View File

@@ -0,0 +1,197 @@
import { CHART_SECONDARY_COLOR, CLS_PREFIX, THEME_COLOR_LIST } from '../../../common/constants';
import {
formatByDecimalPlaces,
getFormattedValue,
getMinMaxDate,
groupByColumn,
normalizeTrendData,
} from '../../../utils/utils';
import type { ECharts } from 'echarts';
import * as echarts from 'echarts';
import React, { useEffect, useRef, useState } from 'react';
import moment from 'moment';
import { ColumnType } from '../../../common/type';
import NoPermissionChart from '../NoPermissionChart';
type Props = {
domain?: string;
dateColumnName: string;
categoryColumnName: string;
metricField: ColumnType;
resultList: any[];
onApplyAuth?: (domain: string) => void;
};
const MetricTrendChart: React.FC<Props> = ({
domain,
dateColumnName,
categoryColumnName,
metricField,
resultList,
onApplyAuth,
}) => {
const chartRef = useRef<any>();
const [instance, setInstance] = useState<ECharts>();
const renderChart = () => {
let instanceObj: any;
if (!instance) {
instanceObj = echarts.init(chartRef.current);
setInstance(instanceObj);
} else {
instanceObj = instance;
}
const valueColumnName = metricField.nameEn;
const groupDataValue = groupByColumn(resultList, categoryColumnName);
const [startDate, endDate] = getMinMaxDate(resultList, dateColumnName);
const groupData = Object.keys(groupDataValue).reduce((result: any, key) => {
result[key] =
startDate &&
endDate &&
(dateColumnName.includes('date') || dateColumnName.includes('month'))
? normalizeTrendData(
groupDataValue[key],
dateColumnName,
valueColumnName,
startDate,
endDate,
dateColumnName.includes('month') ? 'months' : 'days'
)
: groupDataValue[key].reverse();
return result;
}, {});
const sortedGroupKeys = Object.keys(groupData).sort((a, b) => {
return (
groupData[b][groupData[b].length - 1][valueColumnName] -
groupData[a][groupData[a].length - 1][valueColumnName]
);
});
const xData = groupData[sortedGroupKeys[0]]?.map((item: any) => {
const date = `${item[dateColumnName]}`;
return date.length === 10 ? moment(date).format('MM-DD') : date;
});
instanceObj.setOption({
legend: categoryColumnName && {
left: 0,
top: 0,
icon: 'rect',
itemWidth: 15,
itemHeight: 5,
type: 'scroll',
},
xAxis: {
type: 'category',
axisTick: {
alignWithLabel: true,
lineStyle: {
color: CHART_SECONDARY_COLOR,
},
},
axisLine: {
lineStyle: {
color: CHART_SECONDARY_COLOR,
},
},
axisLabel: {
showMaxLabel: true,
color: '#999',
},
data: xData,
},
yAxis: {
type: 'value',
splitLine: {
lineStyle: {
opacity: 0.3,
},
},
axisLabel: {
formatter: function (value: any) {
return value === 0
? 0
: metricField.dataFormatType === 'percent'
? `${formatByDecimalPlaces(value, metricField.dataFormat?.decimalPlaces || 2)}%`
: getFormattedValue(value);
},
},
},
tooltip: {
trigger: 'axis',
formatter: function (params: any[]) {
const param = params[0];
const valueLabels = params
.sort((a, b) => b.value - a.value)
.map(
(item: any) =>
`<div style="margin-top: 3px;">${
item.marker
} <span style="display: inline-block; width: 70px; margin-right: 12px;">${
item.seriesName
}</span><span style="display: inline-block; width: 90px; text-align: right; font-weight: 500;">${
item.value === ''
? '-'
: metricField.dataFormatType === 'percent'
? `${formatByDecimalPlaces(
item.value,
metricField.dataFormat?.decimalPlaces || 2
)}%`
: getFormattedValue(item.value)
}</span></div>`
)
.join('');
return `${param.name}<br />${valueLabels}`;
},
},
grid: {
left: '1%',
right: '4%',
bottom: '3%',
top: categoryColumnName ? 45 : 20,
containLabel: true,
},
series: sortedGroupKeys.slice(0, 20).map((category, index) => {
const data = groupData[category];
return {
type: 'line',
name: categoryColumnName ? category : metricField.name,
symbol: 'circle',
showSymbol: data.length === 1,
smooth: true,
data: data.map((item: any) => {
const value = item[valueColumnName];
return metricField.dataFormatType === 'percent' &&
metricField.dataFormat?.needmultiply100
? value * 100
: value;
}),
color: THEME_COLOR_LIST[index],
};
}),
});
instanceObj.resize();
};
useEffect(() => {
if (metricField.authorized) {
renderChart();
}
}, [resultList, metricField]);
const prefixCls = `${CLS_PREFIX}-metric-trend`;
return (
<div>
{!metricField.authorized ? (
<NoPermissionChart domain={domain || ''} onApplyAuth={onApplyAuth} />
) : (
<div className={`${prefixCls}-flow-trend-chart`} ref={chartRef} />
)}
</div>
);
};
export default MetricTrendChart;

View File

@@ -0,0 +1,205 @@
import { useEffect, useState } from 'react';
import { CLS_PREFIX, DATE_TYPES } from '../../../common/constants';
import { ColumnType, MsgDataType } from '../../../common/type';
import { groupByColumn, isMobile } from '../../../utils/utils';
import { queryData } from '../../../service';
import MetricTrendChart from './MetricTrendChart';
import classNames from 'classnames';
import { Spin } from 'antd';
import Table from '../Table';
import SemanticInfoPopover from '../SemanticInfoPopover';
type Props = {
data: MsgDataType;
onApplyAuth?: (domain: string) => void;
onCheckMetricInfo?: (data: any) => void;
};
const MetricTrend: React.FC<Props> = ({ data, onApplyAuth, onCheckMetricInfo }) => {
const { queryColumns, queryResults, entityInfo, chatContext } = data;
const [columns, setColumns] = useState<ColumnType[]>(queryColumns);
const metricFields = columns.filter((column: any) => column.showType === 'NUMBER') || [];
const [currentMetricField, setCurrentMetricField] = useState<ColumnType>(metricFields[0]);
const [onlyOneDate, setOnlyOneDate] = useState(false);
const [trendData, setTrendData] = useState(data);
const [dataSource, setDataSource] = useState<any[]>(queryResults);
const [mergeMetric, setMergeMetric] = useState(false);
const [currentDateOption, setCurrentDateOption] = useState<number>();
const [loading, setLoading] = useState(false);
const dateField: any = columns.find(
(column: any) => column.showType === 'DATE' || column.type === 'DATE'
);
const dateColumnName = dateField?.nameEn || '';
const categoryColumnName =
columns.find((column: any) => column.showType === 'CATEGORY')?.nameEn || '';
const getColumns = () => {
const categoryFieldData = groupByColumn(dataSource, categoryColumnName);
const result = [dateField];
const columnsValue = Object.keys(categoryFieldData).map(item => ({
authorized: currentMetricField.authorized,
name: item !== 'undefined' ? item : currentMetricField.name,
nameEn: `${item}${currentMetricField.name}`,
showType: 'NUMBER',
type: 'NUMBER',
}));
return result.concat(columnsValue);
};
const getResultList = () => {
return [
{
[dateField.nameEn]: dataSource[0][dateField.nameEn],
...dataSource.reduce((result, item) => {
result[`${item[categoryColumnName]}${currentMetricField.name}`] =
item[currentMetricField.nameEn];
return result;
}, {}),
},
];
};
useEffect(() => {
setDataSource(queryResults);
}, [queryResults]);
useEffect(() => {
let onlyOneDateValue = false;
let dataValue = trendData;
if (dateColumnName && dataSource.length > 0) {
const dateFieldData = groupByColumn(dataSource, dateColumnName);
onlyOneDateValue =
Object.keys(dateFieldData).length === 1 && Object.keys(dateFieldData)[0] !== undefined;
if (onlyOneDateValue) {
if (categoryColumnName !== '') {
dataValue = {
...trendData,
queryColumns: getColumns(),
queryResults: getResultList(),
};
} else {
setMergeMetric(true);
}
}
}
setOnlyOneDate(onlyOneDateValue);
setTrendData(dataValue);
}, [currentMetricField]);
const dateOptions = DATE_TYPES[chatContext.dateInfo?.period] || DATE_TYPES[0];
const onLoadData = async (value: number) => {
setLoading(true);
const { data } = await queryData({
...chatContext,
dateInfo: { ...chatContext.dateInfo, unit: value },
});
setLoading(false);
if (data.code === 200) {
setColumns(data.data?.queryColumns || []);
setDataSource(data.data?.queryResults || []);
}
};
const selectDateOption = (dateOption: number) => {
setCurrentDateOption(dateOption);
// const { domainName, dimensions, metrics, aggType, filters } = chatContext || {};
// const dimensionSection = dimensions?.join('、') || '';
// const metricSection = metrics?.join('、') || '';
// const aggregatorSection = aggType || '';
// const filterSection = filters
// .reduce((result, dimensionName) => {
// result = result.concat(dimensionName);
// return result;
// }, [])
// .join('、');
onLoadData(dateOption);
};
if (metricFields.length === 0) {
return null;
}
const prefixCls = `${CLS_PREFIX}-metric-trend`;
return (
<div className={prefixCls}>
<div className={`${prefixCls}-charts`}>
{!onlyOneDate && (
<div className={`${prefixCls}-date-options`}>
{dateOptions.map((dateOption: { label: string; value: number }, index: number) => {
const dateOptionClass = classNames(`${prefixCls}-date-option`, {
[`${prefixCls}-date-active`]: dateOption.value === currentDateOption,
[`${prefixCls}-date-mobile`]: isMobile,
});
return (
<>
<div
key={dateOption.value}
className={dateOptionClass}
onClick={() => {
selectDateOption(dateOption.value);
}}
>
{dateOption.label}
{dateOption.value === currentDateOption && (
<div className={`${prefixCls}-active-identifier`} />
)}
</div>
{index !== dateOptions.length - 1 && (
<div className={`${prefixCls}-date-option-divider`} />
)}
</>
);
})}
</div>
)}
{metricFields.length > 1 && !mergeMetric && (
<div className={`${prefixCls}-metric-fields`}>
{metricFields.map((metricField: ColumnType) => {
const metricFieldClass = classNames(`${prefixCls}-metric-field`, {
[`${prefixCls}-metric-field-active`]:
currentMetricField?.nameEn === metricField.nameEn,
});
return (
<div
className={metricFieldClass}
key={metricField.nameEn}
onClick={() => {
setCurrentMetricField(metricField);
}}
>
<SemanticInfoPopover
classId={chatContext.domainId}
uniqueId={metricField.nameEn}
onDetailBtnClick={onCheckMetricInfo}
>
{metricField.name}
</SemanticInfoPopover>
</div>
);
})}
</div>
)}
{onlyOneDate ? (
<Table data={trendData} onApplyAuth={onApplyAuth} />
) : (
<Spin spinning={loading}>
<MetricTrendChart
domain={entityInfo?.domainInfo.name}
dateColumnName={dateColumnName}
categoryColumnName={categoryColumnName}
metricField={currentMetricField}
resultList={dataSource}
onApplyAuth={onApplyAuth}
/>
</Spin>
)}
</div>
</div>
);
};
export default MetricTrend;

View File

@@ -0,0 +1,124 @@
@import '../../../styles/index.less';
@metric-trend-prefix-cls: ~'@{supersonic-chat-prefix}-metric-trend';
.@{metric-trend-prefix-cls} {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-top: 20px;
width: 100%;
row-gap: 4px;
&-indicator {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
}
&-date-range {
color: var(--text-color-fourth);
font-size: 14px;
}
&-indicator-value {
color: var(--text-color);
font-weight: 600;
font-size: 30px;
}
&-indicator-name {
color: var(--text-color-fourth);
font-size: 14px;
}
&-flow-trend-chart {
height: 300px;
}
&-charts {
display: flex;
flex-direction: column;
width: 100%;
row-gap: 20px;
}
&-metric-fields {
display: flex;
flex-wrap: wrap;
align-items: center;
row-gap: 12px;
}
&-metric-field {
display: inline-block;
box-sizing: border-box;
height: auto;
margin: 0;
margin-right: 8px;
padding: 1px 8px;
color: var(--text-color-third);
font-variant: tabular-nums;
line-height: 20px;
white-space: nowrap;
list-style: none;
border-color: transparent;
border-radius: 2px;
cursor: pointer;
opacity: 1;
transition: all 0.3s;
font-feature-settings: 'tnum', 'tnum';
&:hover {
color: var(--chat-blue);
}
}
&-metric-field-active {
color: #fff !important;
background-color: var(--chat-blue);
}
&-date-options {
display: flex;
align-items: center;
column-gap: 20px;
font-size: 14px;
}
&-date-option {
position: relative;
color: var(--text-color-secondary);
cursor: pointer;
&:hover {
color: var(--chat-blue);
}
}
&-date-option-active {
color: var(--chat-blue);
}
&-date-option-mobile {
font-size: 12px;
}
&-active-identifier {
position: absolute;
bottom: -6px;
width: 100%;
height: 4px;
background-color: var(--chat-blue);
border-radius: 4px 4px 0 0;
}
&-date-option-divider {
width: 1px;
height: 16px;
background-color: var(--text-color-fifth);
}
}

View File

@@ -0,0 +1,28 @@
import classNames from 'classnames';
import { CLS_PREFIX } from '../../../common/constants';
import ApplyAuth from '../ApplyAuth';
type Props = {
domain: string;
chartType?: string;
onApplyAuth?: (domain: string) => void;
};
const NoPermissionChart: React.FC<Props> = ({ domain, chartType, onApplyAuth }) => {
const prefixCls = `${CLS_PREFIX}-no-permission-chart`;
const chartHolderClass = classNames(`${prefixCls}-holder`, {
[`${prefixCls}-bar-chart-holder`]: chartType === 'barChart',
});
return (
<div className={prefixCls}>
<div className={chartHolderClass} />
<div className={`${prefixCls}-no-permission`}>
<ApplyAuth domain={domain} onApplyAuth={onApplyAuth} />
</div>
</div>
);
};
export default NoPermissionChart;

View File

@@ -0,0 +1,30 @@
@import '../../../styles/index.less';
@no-permission-chart-prefix-cls: ~'@{supersonic-chat-prefix}-no-permission-chart';
.@{no-permission-chart-prefix-cls} {
position: relative;
width: 100%;
height: 300px;
&-holder {
width: 100%;
height: 300px;
// background-image: url(~./images/line_chart_holder.png);
// background-repeat: no-repeat;
// background-size: 100% 300px;
}
&-bar-chart-holder {
margin-top: 20px;
// background-image: url(~./images/bar_chart_holder.png);
}
&-no-permission {
position: absolute;
top: 50%;
left: 50%;
padding: 4px 12px;
transform: translate(-50%, -50%);
}
}

View File

@@ -0,0 +1,25 @@
import { Tag } from 'antd';
import React from 'react';
import { SemanticTypeEnum, SEMANTIC_TYPE_MAP } from '../../../common/type';
type Props = {
infoType?: SemanticTypeEnum;
};
const SemanticTypeTag: React.FC<Props> = ({ infoType = SemanticTypeEnum.METRIC }) => {
return (
<Tag
color={
infoType === SemanticTypeEnum.DIMENSION || infoType === SemanticTypeEnum.DOMAIN
? 'blue'
: infoType === SemanticTypeEnum.VALUE
? 'geekblue'
: 'orange'
}
>
{SEMANTIC_TYPE_MAP[infoType]}
</Tag>
);
};
export default SemanticTypeTag;

View File

@@ -0,0 +1,104 @@
import { Popover, message, Row, Col, Button, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import { SemanticTypeEnum } from '../../../common/type';
import { queryMetricInfo } from '../../../service';
import SemanticTypeTag from './SemanticTypeTag';
import { isMobile } from '../../../utils/utils';
import { CLS_PREFIX } from '../../../common/constants';
type Props = {
children: React.ReactNode;
classId?: number;
infoType?: SemanticTypeEnum;
uniqueId: string | number;
onDetailBtnClick?: (data: any) => void;
};
const SemanticInfoPopover: React.FC<Props> = ({
classId,
infoType,
uniqueId,
children,
onDetailBtnClick,
}) => {
const [semanticInfo, setSemanticInfo] = useState<any>(undefined);
const [popoverVisible, setPopoverVisible] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const prefixCls = `${CLS_PREFIX}-semantic-info-popover`;
const text = (
<Row>
<Col flex="1">
<SemanticTypeTag infoType={infoType} />
</Col>
{onDetailBtnClick && (
<Col flex="0 1 40px">
{semanticInfo && (
<Button
type="link"
size="small"
onClick={() => {
onDetailBtnClick(semanticInfo);
}}
>
</Button>
)}
</Col>
)}
</Row>
);
const content = loading ? (
<div className={`${prefixCls}-spin-box`}>
<Spin />
</div>
) : (
<div>
<span>{semanticInfo?.description || '暂无数据'}</span>
</div>
);
const getMetricInfo = async () => {
setLoading(true);
const { data: resData } = await queryMetricInfo({
classId,
uniqueId,
});
const { code, data, msg } = resData;
setLoading(false);
if (code === '0') {
setSemanticInfo({
...data,
semanticInfoType: SemanticTypeEnum.METRIC,
});
} else {
message.error(msg);
}
};
useEffect(() => {
if (popoverVisible && !semanticInfo) {
getMetricInfo();
}
}, [popoverVisible]);
return (
<Popover
placement="top"
title={text}
content={content}
trigger="hover"
open={classId && !isMobile ? undefined : false}
onOpenChange={visible => {
setPopoverVisible(visible);
}}
overlayClassName={prefixCls}
>
{children}
</Popover>
);
};
export default SemanticInfoPopover;

View File

@@ -0,0 +1,18 @@
@import '../../../styles/index.less';
@semantic-info-popover-cls: ~'@{supersonic-chat-prefix}-semantic-info-popover';
.semantic-info-popover-cls {
max-width: 300px;
&-spin-box {
text-align: center;
padding-top: 10px;
}
.ant-popover-title{
padding: 5px 8px 4px;
}
.ant-popover-inner-content {
min-height: 60px;
min-width: 185px;
}
}

View File

@@ -0,0 +1,72 @@
import { formatByDecimalPlaces, getFormattedValue } from '../../../utils/utils';
import { Table as AntTable } from 'antd';
import { MsgDataType } from '../../../common/type';
import { CLS_PREFIX } from '../../../common/constants';
import ApplyAuth from '../ApplyAuth';
type Props = {
data: MsgDataType;
onApplyAuth?: (domain: string) => void;
};
const Table: React.FC<Props> = ({ data, onApplyAuth }) => {
const { entityInfo, queryColumns, queryResults } = data;
const prefixCls = `${CLS_PREFIX}-table`;
const tableColumns: any[] = queryColumns.map(
({ name, nameEn, showType, dataFormatType, dataFormat, authorized }) => {
return {
dataIndex: nameEn,
key: nameEn,
title: name,
render: (value: string | number) => {
if (!authorized) {
return (
<ApplyAuth domain={entityInfo?.domainInfo.name || ''} onApplyAuth={onApplyAuth} />
);
}
if (dataFormatType === 'percent') {
return (
<div className={`${prefixCls}-formatted-value`}>
{`${formatByDecimalPlaces(
dataFormat?.needmultiply100 ? +value * 100 : value,
dataFormat?.decimalPlaces || 2
)}%`}
</div>
);
}
if (showType === 'NUMBER') {
return (
<div className={`${prefixCls}-formatted-value`}>
{getFormattedValue(value as number)}
</div>
);
}
if (nameEn.includes('photo')) {
return (
<div className={`${prefixCls}-photo`}>
<img width={40} height={40} src={value as string} alt="" />
</div>
);
}
return value;
},
};
}
);
return (
<div className={prefixCls}>
<AntTable
pagination={queryResults.length <= 10 ? false : undefined}
size={queryResults.length === 1 ? 'middle' : 'small'}
columns={tableColumns}
dataSource={queryResults}
style={{ width: '100%' }}
/>
</div>
);
};
export default Table;

View File

@@ -0,0 +1,72 @@
@import '../../../styles/index.less';
@table-prefix-cls: ~'@{supersonic-chat-prefix}-table';
.@{table-prefix-cls} {
margin-top: 20px;
margin-bottom: 20px;
&-photo {
display: flex;
align-items: center;
justify-content: center;
}
table {
width: 100%;
}
.ant-table-container table > thead > tr:first-child th:first-child {
border-top-left-radius: 12px !important;
border-bottom-left-radius: 12px !important;
}
.ant-table-container table > thead > tr:first-child th:last-child {
border-top-right-radius: 12px !important;
border-bottom-right-radius: 12px !important;
}
.ant-table-tbody > tr.ant-table-row:hover > td {
background-color: #fafafa !important;
}
.ant-table-cell {
text-align: center !important;
}
.ant-table-thead {
.ant-table-cell {
padding-top: 10px;
padding-bottom: 10px;
color: #666;
font-size: 13px;
background: #f0f2f5;
&::before {
display: none;
}
}
}
.@{table-prefix-cls}-formatted-value {
font-weight: 500;
font-size: 16px;
}
.ant-table-thead .ant-table-cell {
padding-top: 8.5px;
padding-bottom: 8.5px;
color: #737b7b;
font-weight: 500;
font-size: 14px;
background-color: #edf2f2;
}
.ant-table-tbody {
.ant-table-cell {
padding: 15px 0;
color: #333;
font-size: 14px;
}
}
}

View File

@@ -0,0 +1,62 @@
import { isMobile } from '../../utils/utils';
import Bar from './Bar';
import Message from './Message';
import MetricCard from './MetricCard';
import MetricTrend from './MetricTrend';
import Table from './Table';
import { MsgDataType } from '../../common/type';
type Props = {
data: MsgDataType;
onCheckMetricInfo?: (data: any) => void;
};
const ChatMsg: React.FC<Props> = ({ data, onCheckMetricInfo }) => {
const { aggregateType, queryColumns, queryResults, chatContext, entityInfo } = data;
if (!queryColumns || !queryResults) {
return null;
}
const singleData = queryResults.length === 1;
const dateField = queryColumns.find(item => item.showType === 'DATE' || item.type === 'DATE');
const categoryField = queryColumns.filter(item => item.showType === 'CATEGORY');
const metricFields = queryColumns.filter(item => item.showType === 'NUMBER');
const getMsgContent = () => {
if (categoryField.length > 1 || aggregateType === 'tag') {
return <Table data={data} />;
}
if (dateField && metricFields.length > 0) {
return <MetricTrend data={data} onCheckMetricInfo={onCheckMetricInfo} />;
}
if (singleData) {
return <MetricCard data={data} />;
}
return <Bar data={data} />;
};
let width = '100%';
if ((categoryField.length > 1 || aggregateType === 'tag') && !isMobile) {
if (queryColumns.length === 1) {
width = '600px';
} else if (queryColumns.length === 2) {
width = '1000px';
}
}
return (
<Message
position="left"
chatContext={chatContext}
entityInfo={entityInfo}
aggregator={aggregateType}
tip={''}
width={width}
>
{getMsgContent()}
</Message>
);
};
export default ChatMsg;

View File

@@ -0,0 +1,42 @@
import { CLS_PREFIX } from '../../common/constants';
import { Row, Col } from 'antd';
type Props = {
description: string;
basicInfoList: any[];
};
const BasicInfoSection: React.FC<Props> = ({ description = '', basicInfoList }) => {
const prefixCls = `${CLS_PREFIX}-semantic-detail`;
return (
<>
<div className={`${prefixCls}-info-bar`}>
<div className={`${prefixCls}-main-entity-info`}>
{basicInfoList.map(item => {
return (
<div className={`${prefixCls}-info-item`}>
<div className={`${prefixCls}-info-name`}>{item.name}</div>
<div className={`${prefixCls}-info-value`}>{item.value}</div>
</div>
);
})}
</div>
</div>
{description && (
<>
<Row>
<Col flex="0 0 52px">
<div className={`${prefixCls}-description`}> : </div>
</Col>
<Col flex="1 1 auto">
<div className={`${prefixCls}-description`}>{description}</div>
</Col>
</Row>
</>
)}
</>
);
};
export default BasicInfoSection;

View File

@@ -0,0 +1,97 @@
import { message, Row, Col } from 'antd';
import { isMobile } from '../../utils/utils';
import { ReloadOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import { getRelatedDimensionFromStatInfo } from '../../service';
import { CLS_PREFIX } from '../../common/constants';
type Props = {
classId?: number;
uniqueId: string | number;
onSelect?: (value: string) => void;
};
const PAGE_SIZE = isMobile ? 3 : 10;
const DimensionSection: React.FC<Props> = ({ classId, uniqueId, onSelect }) => {
const [dimensions, setDimensions] = useState<string[]>([]);
const [dimensionIndex, setDimensionIndex] = useState(0);
const prefixCls = `${CLS_PREFIX}-semantic-detail`;
const queryDimensionList = async () => {
const { data: resData } = await getRelatedDimensionFromStatInfo({
classId,
uniqueId,
});
const { code, data, msg } = resData;
if (code === '0') {
setDimensions(
data.map(item => {
return item.name;
})
);
} else {
message.error(msg);
}
};
useEffect(() => {
queryDimensionList();
}, []);
const reloadDimensionCmds = () => {
const dimensionPageCount = Math.ceil(dimensions.length / PAGE_SIZE);
setDimensionIndex((dimensionIndex + 1) % dimensionPageCount);
};
const dimensionList = dimensions.slice(
dimensionIndex * PAGE_SIZE,
(dimensionIndex + 1) * PAGE_SIZE
);
return (
<>
{dimensionList.length > 0 && (
<div className={`${prefixCls}-content-section`}>
<Row>
<Col flex="0 0 80px">
<div className={`${prefixCls}-label`}> </div>
</Col>
<Col flex="1 1" className={`${prefixCls}-content-col`}>
<div className={`${prefixCls}-content-col-box`}>
{dimensionList.map((dimension, index) => {
return (
<>
<span
className={`${prefixCls}-section-item`}
onClick={() => {
onSelect?.(dimension);
}}
>
{dimension}
</span>
{index < dimensionList.length - 1 && '、'}
</>
);
})}
</div>
</Col>
<Col flex="0 1 50px">
<div
className={`${prefixCls}-reload`}
onClick={() => {
reloadDimensionCmds();
}}
>
<ReloadOutlined className={`${prefixCls}-reload-icon`} />
{!isMobile && <div className={`${prefixCls}-reload-label`}></div>}
</div>
</Col>
</Row>
</div>
)}
</>
);
};
export default DimensionSection;

View File

@@ -0,0 +1,112 @@
import { useEffect, useState } from 'react';
import { getMetricQueryInfo } from '../../service';
import { message, Row, Col } from 'antd';
import { CLS_PREFIX } from '../../common/constants';
type Props = {
classId: number;
metricName: string;
onSelect?: (value: string) => void;
};
const RecommendQuestions: React.FC<Props> = ({ classId, metricName, onSelect }) => {
const [moreMode, setMoreMode] = useState<boolean>(false);
const [questionData, setQuestionData] = useState<any[]>([]);
const prefixCls = `${CLS_PREFIX}-semantic-detail`;
const queryMetricQueryInfo = async () => {
const { data: resData } = await getMetricQueryInfo({
classId,
metricName,
});
const { code, data, msg } = resData;
if (code === '0') {
setQuestionData(data);
} else {
message.error(msg);
}
};
useEffect(() => {
queryMetricQueryInfo();
}, []);
return (
<div className={`${prefixCls}-recommend-questions`}>
<div className={`${prefixCls}-header`}>
<Row>
<Col flex="0 0 85px">
<div className={`${prefixCls}-label`}> : </div>
</Col>
<Col flex="1 1" className={`${prefixCls}-content-col`}>
{!moreMode && (
<div className={`${prefixCls}-content-col-box`}>
{questionData.slice(0, 5).map((item, index) => {
const { question } = item;
return (
<>
{index !== 0 && '、'}
<span
key={question}
className={`${prefixCls}-question`}
onClick={() => {
onSelect?.(question);
}}
>
<span dangerouslySetInnerHTML={{ __html: question }} />
</span>
</>
);
})}
</div>
)}
</Col>
<Col flex="0 1 30px">
{!moreMode ? (
<span
onClick={() => {
setMoreMode(true);
}}
className={`${prefixCls}-more`}
>
</span>
) : (
<span
className={`${prefixCls}-more`}
onClick={() => {
setMoreMode(false);
}}
>
</span>
)}
</Col>
</Row>
</div>
{moreMode && (
<div className={`${prefixCls}-recommend-questions-content`}>
<div className={`${prefixCls}-questions`}>
{questionData.map(item => {
const { question } = item;
return (
<div
key={question}
className={`${prefixCls}-question`}
onClick={() => {
onSelect?.(question);
}}
>
<span dangerouslySetInnerHTML={{ __html: question }} />
</div>
);
})}
</div>
</div>
)}
</div>
);
};
export default RecommendQuestions;

View File

@@ -0,0 +1,53 @@
import Message from '../ChatMsg/Message';
import { Space, Row, Col, Divider } from 'antd';
import BasicInfoSection from './BasicInfoSection';
import DimensionSection from './DimensionSection';
import RecommendSection from './RecommendSection';
import SemanticTypeTag from '../ChatMsg/SemanticInfoPopover/SemanticTypeTag';
import { CLS_PREFIX } from '../../common/constants';
type Props = {
dataSource?: any;
onDimensionSelect?: (value: any) => void;
};
const SemanticDetail: React.FC<Props> = ({ dataSource, onDimensionSelect }) => {
const { name, nameEn, createdBy, description, className, classId, semanticInfoType } = dataSource;
const semanticDetailCls = `${CLS_PREFIX}-semantic-detail`;
return (
<Message position="left" width="100%" noTime>
<div>
<div>
<Row>
<Col flex="1">
<Space size={20}>
<span className={`${semanticDetailCls}-title`}>{`指标详情: ${name}`}</span>
</Space>
</Col>
<Col flex="0 1 40px">
<SemanticTypeTag infoType={semanticInfoType} />
</Col>
</Row>
</div>
<BasicInfoSection
description={description}
basicInfoList={[
{
name: '主题域',
value: className,
},
{ name: '创建人', value: createdBy },
]}
/>
<Divider style={{ margin: '12px 0 16px 0px' }} />
<DimensionSection classId={classId} uniqueId={nameEn} onSelect={onDimensionSelect} />
<Divider style={{ margin: '6px 0 12px 0px' }} />
<RecommendSection classId={classId} metricName={name} onSelect={onDimensionSelect} />
</div>
</Message>
);
};
export default SemanticDetail;

View File

@@ -0,0 +1,129 @@
@import '../../styles/variables.less';
@semantic-detail-cls: ~'@{supersonic-chat-prefix}-semantic-detail';
.@{semantic-detail-cls} {
&-info-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
margin: 20px 0;
column-gap: 20px;
}
&-description {
font-size: 13px;
color: var(--text-color-fourth);
}
&-main-entity-info {
display: flex;
flex-wrap: wrap;
align-items: center;
font-size: 13px;
column-gap: 20px;
}
&-info-item {
display: flex;
align-items: center;
}
&-info-name {
color: var(--text-color-fourth);
}
&-info-value {
color: var(--text-color-secondary);
}
&-title {
font-size: 16px;
margin-left: 15px;
line-height: 30px;
&::before {
display: block;
position: absolute;
content: "";
left: 0;
top: 6px;
height: 15px;
width: 3px;
font-size: 0;
background: #0e73ff;
border-radius: 2px;
border: 1px solid #0e73ff;
}
}
&-label {
font-size: 14px;
color: var(--text-color-fourth);
}
&-section-item {
cursor: pointer;
&:hover {
color: var(--chat-blue);
}
}
&-reload {
display: flex;
align-items: center;
color: var(--text-color-fourth);
font-size: 12px;
column-gap: 4px;
cursor: pointer;
position: relative;
top: 3px;
&:hover {
color: var(--chat-blue);
}
}
&-reload-icon {
font-size: 10px;
position: relative;
}
&-header {
font-size: 14px;
color: var(--text-color-fourth);
margin-bottom: 5px;
}
&-more {
cursor: pointer;
font-size: 12px;
&:hover {
color: var(--chat-blue);
}
}
&-recommend-questions-content {
height: 300px;
overflow: auto;
}
&-question {
cursor: pointer;
color: rgba(0, 0, 0, 0.87);
&:hover {
color: var(--chat-blue);
}
}
&-content-col {
min-width: 300px;
overflow-y: hidden;
height: 32px;
overflow-x: scroll;
}
&-content-col-box{
width: max-content;
}
}

View File

@@ -0,0 +1,162 @@
import { isMobile } from '../../utils/utils';
import { ReloadOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { EntityInfoType } from '../../common/type';
import Message from '../ChatMsg/Message';
import { CLS_PREFIX } from '../../common/constants';
type Props = {
currentMsgAggregator?: string;
columns: any[];
mainEntity: EntityInfoType;
suggestions: any;
onSelect?: (value: string) => void;
};
const PAGE_SIZE = isMobile ? 3 : 5;
const Suggestion: React.FC<Props> = ({
currentMsgAggregator,
columns,
mainEntity,
suggestions,
onSelect,
}) => {
const [dimensions, setDimensions] = useState<string[]>([]);
const [metrics, setMetrics] = useState<string[]>([]);
const [dimensionIndex, setDimensionIndex] = useState(0);
const [metricIndex, setMetricIndex] = useState(0);
const fields = columns
.filter(column => currentMsgAggregator !== 'tag' || column.showType !== 'NUMBER')
.concat(isMobile ? [] : mainEntity?.dimensions || [])
.map(item => item.name);
useEffect(() => {
setDimensions(
suggestions.dimensions
.filter((dimension: any) => !fields.some(field => field === dimension.name))
.map((item: any) => item.name)
);
setMetrics(
suggestions.metrics
.filter((metric: any) => !fields.some(field => field === metric.name))
.map((item: any) => item.name)
);
}, []);
const reloadDimensionCmds = () => {
const dimensionPageCount = Math.ceil(dimensions.length / PAGE_SIZE);
setDimensionIndex((dimensionIndex + 1) % dimensionPageCount);
};
const reloadMetricCmds = () => {
const metricPageCount = Math.ceil(metrics.length / PAGE_SIZE);
setMetricIndex((metricIndex + 1) % metricPageCount);
};
const dimensionList = dimensions.slice(
dimensionIndex * PAGE_SIZE,
(dimensionIndex + 1) * PAGE_SIZE
);
const metricList = metrics.slice(metricIndex * PAGE_SIZE, (metricIndex + 1) * PAGE_SIZE);
if (!dimensionList.length && !metricList.length) {
return null;
}
const prefixCls = `${CLS_PREFIX}-suggestion`;
const suggestionClass = classNames(prefixCls, {
[`${prefixCls}-mobile`]: isMobile,
});
const sectionItemClass = classNames({
[`${prefixCls}-section-item-selectable`]: onSelect !== undefined,
});
return (
<div className={suggestionClass}>
<Message position="left" width="fit-content" noWaterMark>
<div className={`${prefixCls}-tip`}></div>
{metricList.length > 0 && (
<div className={`${prefixCls}-content-section`}>
<div className={`${prefixCls}-title`}></div>
<div className={`${prefixCls}-section-items`}>
{metricList.map((metric, index) => {
let metricNode = (
<div
className={sectionItemClass}
onClick={() => {
if (onSelect) {
onSelect(metric);
}
}}
>
{metric}
</div>
);
return (
<>
{metricNode}
{index < metricList.length - 1 && '、'}
</>
);
})}
</div>
{metrics.length > PAGE_SIZE && (
<div
className={`${prefixCls}-reload`}
onClick={() => {
reloadMetricCmds();
}}
>
<ReloadOutlined className={`${prefixCls}-reload-icon`} />
{!isMobile && <div className={`${prefixCls}-reload-label`}></div>}
</div>
)}
</div>
)}
{dimensionList.length > 0 && (
<div className={`${prefixCls}-content-section`}>
<div className={`${prefixCls}-title`}></div>
<div className={`${prefixCls}-section-items`}>
{dimensionList.map((dimension, index) => {
return (
<>
<div
className={sectionItemClass}
onClick={() => {
if (onSelect) {
onSelect(dimension);
}
}}
>
{dimension}
</div>
{index < dimensionList.length - 1 && '、'}
</>
);
})}
</div>
{dimensions.length > PAGE_SIZE && (
<div
className={`${prefixCls}-reload`}
onClick={() => {
reloadDimensionCmds();
}}
>
<ReloadOutlined className={`${prefixCls}-reload-icon`} />
{!isMobile && <div className={`${prefixCls}-reload-label`}></div>}
</div>
)}
</div>
)}
</Message>
</div>
);
};
export default Suggestion;

View File

@@ -0,0 +1,59 @@
@import '../../styles/index.less';
@suggestion-prefix-cls: ~'@{supersonic-chat-prefix}-suggestion';
.@{suggestion-prefix-cls} {
margin-top: 30px;
.@{suggestion-prefix-cls}-mobile {
margin-top: 12px;
font-size: 13px;
}
&-tip {
margin-bottom: 12px;
}
&-content-section {
display: flex;
align-items: center;
margin-bottom: 10px;
row-gap: 12px;
}
&-title {
color: var(--text-color-fourth);
}
&-section-items {
display: flex;
flex-wrap: wrap;
align-items: center;
}
&-section-item-selectable {
cursor: pointer;
&:hover {
color: var(--chat-blue);
}
}
&-reload {
display: flex;
align-items: center;
margin-right: 14px;
margin-left: 20px;
color: var(--text-color-fourth);
font-size: 12px;
column-gap: 4px;
cursor: pointer;
&:hover {
color: var(--chat-blue);
}
}
&-reload-icon {
font-size: 10px;
}
}

View File

@@ -0,0 +1,70 @@
import { isMobile } from '../../utils/utils';
import { DislikeOutlined, LikeOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import { CLS_PREFIX } from '../../common/constants';
type Props = {
isLastMessage?: boolean;
};
const Tools: React.FC<Props> = ({ isLastMessage }) => {
const prefixCls = `${CLS_PREFIX}-tools`;
const changeChart = () => {
message.info('正在开发中,敬请期待');
};
const addToDashboard = () => {
message.info('正在开发中,敬请期待');
};
const lockDomain = () => {
message.info('正在开发中,敬请期待');
};
const like = () => {
message.info('正在开发中,敬请期待');
};
const dislike = () => {
message.info('正在开发中,敬请期待');
};
const lockDomainSection = isLastMessage && (
<Button shape="round" onClick={lockDomain}>
</Button>
);
const feedbackSection = isLastMessage && (
<div className={`${prefixCls}-feedback`}>
<div></div>
<LikeOutlined className={`${prefixCls}-like`} onClick={like} />
<DislikeOutlined className={`${prefixCls}-dislike`} onClick={dislike} />
</div>
);
if (isMobile) {
return (
<div className={`${prefixCls}-mobile-tools`}>
{isLastMessage && <div className={`${prefixCls}-tools`}>{lockDomainSection}</div>}
{feedbackSection}
</div>
);
}
return (
<div className={prefixCls}>
<Button shape="round" onClick={changeChart}>
</Button>
<Button shape="round" onClick={addToDashboard}>
</Button>
{lockDomainSection}
{feedbackSection}
</div>
);
};
export default Tools;

View File

@@ -0,0 +1,37 @@
@import '../../styles/index.less';
@tools-cls: ~'@{supersonic-chat-prefix}-tools';
.@{tools-cls} {
display: flex;
align-items: center;
margin-top: 12px;
column-gap: 6px;
&-feedback {
display: flex;
align-items: center;
margin-left: 4px;
color: var(--text-color-third);
column-gap: 6px;
}
&-like {
margin-right: 4px;
}
&-mobile-tools {
display: flex;
flex-direction: column;
margin-top: 12px;
row-gap: 10px;
}
&-tools {
margin-top: 0;
}
&-feedback {
margin-left: 2px;
}
}

View File

@@ -0,0 +1,41 @@
import { Input } from 'antd';
import styles from './style.module.less';
import { useState } from 'react';
import ChatItem from '../components/ChatItem';
import { queryContext, searchRecommend } from '../service';
const { Search } = Input;
const Chat = () => {
const [inputMsg, setInputMsg] = useState('');
const [msg, setMsg] = useState('');
const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { value } = e.target;
setInputMsg(value);
searchRecommend(value);
};
const onSearch = () => {
setMsg(inputMsg);
queryContext(inputMsg);
};
return (
<div className={styles.page}>
<div className={styles.inputMsg}>
<Search
placeholder="请输入问题"
value={inputMsg}
onChange={onInputChange}
onSearch={onSearch}
/>
</div>
<div className={styles.chatItem}>
<ChatItem msg={msg} suggestionEnable isLastMessage />
</div>
</div>
);
};
export default Chat;

View File

@@ -0,0 +1,11 @@
.page {
display: flex;
flex-direction: column;
row-gap: 20px;
padding: 30px;
background:
linear-gradient(180deg,rgba(23,74,228,0) 29.44%,rgba(23,74,228,.06)),linear-gradient(90deg,#f3f3f7,#f3f3f7 20%,#ebf0f9 60%,#f3f3f7 80%,#f3f3f7);
height: 100vh;
overflow: auto;
box-sizing: border-box;
}

View File

@@ -0,0 +1,39 @@
import './styles/index.less';
// import React from 'react';
// import ReactDOM from 'react-dom/client';
// import Chat from './demo/Chat';
// const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
// root.render(
// <React.StrictMode>
// <Chat />
// </React.StrictMode>
// );
export { default as ChatMsg } from './components/ChatMsg';
export { default as ChatItem } from './components/ChatItem';
export type {
SearchRecommendItem,
FieldType,
DomainInfoType,
EntityInfoType,
DateInfoType,
ChatContextType,
MsgValidTypeEnum,
MsgDataType,
ColumnType,
SuggestionItemType,
SuggestionType,
SuggestionDataType,
FilterItemType,
HistoryType,
HistoryMsgItemType,
} from './common/type';
export { getHistoryMsg, searchRecommend, queryContext } from './service';
export { setToken } from './utils/utils';

View File

@@ -0,0 +1,51 @@
// 引入axios库
import axios, { AxiosInstance } from 'axios';
import { getToken } from '../utils/utils';
// 创建axios实例
const axiosInstance: AxiosInstance = axios.create({
// 设置基本URL所有请求都会使用这个URL作为前缀
baseURL: '',
// 设置请求超时时间(毫秒)
timeout: 30000,
// 设置请求头
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器
axiosInstance.interceptors.request.use(
(config: any) => {
const token = getToken();
if (token && config?.headers) {
config.headers.auth = `Bearer ${token}`;
}
return config;
},
(error) => {
// 请求错误时的处理
return Promise.reject(error);
}
);
// 响应拦截器
axiosInstance.interceptors.response.use(
(response: any) => {
if (Number(response.data.code) === 403) {
window.location.href = '/#/login';
return response;
}
return response;
},
(error) => {
// 对响应错误进行处理
if (error.response && error.response.status === 401) {
// 如果响应状态码为401表示未授权可以在这里处理重新登录等操作
console.log('Unauthorized, please log in again.');
}
return Promise.reject(error);
}
);
export default axiosInstance;

View File

@@ -0,0 +1,70 @@
import axios from './axiosInstance';
import { ChatContextType, HistoryType, MsgDataType, SearchRecommendItem } from '../common/type';
import { QueryDataType } from '../common/type';
const DEFAULT_CHAT_ID = 0;
const prefix = '/api';
export function searchRecommend(queryText: string, chatId?: number, domainId?: number) {
return axios.post<Result<SearchRecommendItem[]>>(`${prefix}/chat/query/search`, {
queryText,
chatId: chatId || DEFAULT_CHAT_ID,
domainId,
});
}
export function chatQuery(queryText: string, chatId?: number, domainId?: number, isSaveQuestionAnswer?: boolean) {
return axios.post<Result<MsgDataType>>(`${prefix}/chat/query/query`, {
queryText,
chatId: chatId || DEFAULT_CHAT_ID,
domainId,
isSaveQuestionAnswer
});
}
export function queryData(chatContext: ChatContextType) {
return axios.post<Result<QueryDataType>>(`${prefix}/chat/query/queryData`, chatContext);
}
export function queryContext(queryText: string, chatId?: number) {
return axios.post<Result<ChatContextType>>(`${prefix}/chat/query/queryContext`, {
queryText,
chatId: chatId || DEFAULT_CHAT_ID,
});
}
export function querySuggestionInfo(domainId: number) {
return axios.get<Result<any>>(`${prefix}/chat/recommend/${domainId}`);
}
export function getHistoryMsg(current: number, chatId: number = DEFAULT_CHAT_ID, pageSize: number = 10) {
return axios.post<Result<HistoryType>>(`${prefix}/chat/manage/pageQueryInfo?chatId=${chatId}`, {
current,
pageSize,
});
}
export function queryMetricInfo(data: any) {
return axios.get(`/semantic/metric/getMetric/${data.classId}/${data.uniqueId}`);
}
export function getRelatedDimensionFromStatInfo(data: any) {
return axios.get(
`/semantic/metric/getRelatedDimensionFromStatInfo/${data.classId}/${data.uniqueId}`,
);
}
export function getMetricQueryInfo(data: any) {
return axios.get<any>(
`getMetricQueryInfo/${data.classId}/${data.metricName}`
);
}
export function saveConversation(chatName: string) {
return axios.post<Result<any>>(`${prefix}/chat/manage/save?chatName=${chatName}`);
}
export function getAllConversations() {
return axios.get<Result<any>>(`${prefix}/chat/manage/getAll`);
}

View File

@@ -0,0 +1,19 @@
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
// app.use(
// '/api',
// createProxyMiddleware({
// target: 'http://10.91.206.71:9079',
// changeOrigin: true,
// })
// );
app.use(
'/api',
// '/api',
createProxyMiddleware({
target: 'http://supersonic.test.tmeoa.com',
changeOrigin: true,
})
);
};

View File

@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@@ -0,0 +1,50 @@
@import './index.less';
@prefix-cls: ~'@{supersonic-chat-prefix}';
.@{prefix-cls} {
&-dimension,
&-metric {
position: relative;
&::after {
position: absolute;
right: 0.5px;
bottom: -2px;
left: 0.5px;
height: 2px;
margin: 0 1px;
content: '';
}
}
&-dimension {
&::after {
background: var(--chat-blue);
}
}
&-metric {
&::after {
background: #31c462;
}
}
&-table-row {
cursor: pointer;
}
&-even-row {
background-color: #fbfbfb;
}
&-no-border-table {
.ant-table-cell {
border: none !important;
}
.ant-table-tbody > tr.ant-table-row:hover > td {
background-color: #efefef !important;
}
}
}

View File

@@ -0,0 +1,29 @@
@import './reboot.less';
@import './variables.less';
@import './global.less';
@import '../components/ChatMsg/Bar/style.less';
@import '../components/ChatMsg/Table/style.less';
@import '../components/ChatMsg/Message/style.less';
@import '../components/ChatMsg/MetricCard/style.less';
@import "../components/ChatMsg/MetricTrend/style.less";
@import "../components/ChatMsg/ApplyAuth/style.less";
@import "../components/ChatMsg/NoPermissionChart/style.less";
@import "../components/ChatMsg/SemanticInfoPopover/style.less";
@import "../components/SemanticDetail/style.less";
@import '../components/ChatItem/style.less';
@import "../components/Tools/style.less";
@import "../components/Suggestion/style.less";

View File

@@ -0,0 +1,14 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-size: 14px;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@@ -0,0 +1,79 @@
@supersonic-chat-prefix: ~'ss-chat';
:root:root {
--primary: 180deg 4%;
--primary-color: #f87653;
--blue: #296df3;
--deep-blue: #446dff;
--chat-blue: #1b4aef;
--wy-color: #c20c0c;
--detail-width: 1300px;
--primary-1: #fff0f0;
--primary-2: #ffc7c7;
--primary-3: #ff9ea1;
--primary-4: #ff757e;
--primary-5: #ff4d5e;
--primary-6: #ff2441;
--primary-7: #d91434;
--primary-8: rgba(255, 36, 66, 0.1);
--body-background: #f7fafa;
--deep-background: #f0f0f0;
--light-background: #f5f5f5;
--component-background: #fff;
--header-color: #edf2f2;
--text-color: #181a1a;
--text-color-secondary: #3d4242;
--text-color-third: #626a6a;
--text-color-fourth: #889191;
--text-color-fifth: #afb6b6;
--text-color-six: #a3a4a6;
--text-color-fifth-4: hsla(180, 5%, 70%, 0.4);
--tooltip-max-width: 350px;
--info-color: #ff2442;
--success-color: #52c41a;
--processing-color: #ff2442;
--error-color: #ff4d4f;
--highlight-color: #ff4d4f;
--newrank-color: #ff7800;
--warning-color: #faad14;
--normal-color: #d9d9d9;
--white: #fff;
--white-30: hsla(0, 0%, 100%, 0.3);
--black: #000;
--disabled-color: #afb6b6;
--disabled-bg: #eceeee;
--border-color-base: #e1e6e6;
--chat-border-color-base: #d5d7db;
--light-blue-background: rgba(58, 100, 255, 0.1);
--link-color: #3a64ff;
--link-hover-color: #638aff;
--link-active-color: #2748d9;
--link-bg-color: rgba(58, 100, 255, 0.1);
--text-accent-color: #3a64ff;
--primary-green: #00b354;
--link-hover-bg-color: rgba(58, 100, 255, 0.06);
--success-2: rgba(82, 196, 26, 0.2);
--success-pink: #ff8193;
--disabled-bg-3: hsla(180, 6%, 93%, 0.3);
--tooltip-bg: #fff;
--record-btn: #00b354;
--record-btn-bg: rgba(0, 179, 84, 0.1);
--record-btn-bg-3: rgba(0, 179, 84, 0.3);
--border-color-base-bg-5: hsla(180, 9%, 89%, 0.5);
--user-gao-color: #fcad36;
--user-hao-color: #ec6f6f;
--user-all-color: #252526;
--nr-menu-highlight-color: #ff2442;
--nr-menu-icon-hover-color: #ff2442;
--nr-sider-background: #fff;
--nr-menu-bg: #fff;
--nr-sider-fixed-zindex: 12;
--nr-header-fixed-zindex: 11;
--newrank-color-bg: rgba(255, 120, 0, 0.1);
--newrank-color-bg-3: rgba(255, 120, 0, 0.3);
--warning-05: rgba(250, 173, 20, 0.05);
--bridge-account-color: #ff2442;
--bridge-agency-color: #3a64ff;
--bridge-free-color: #ff7800;
--bridge-medium-color: #00b354;
}

View File

@@ -0,0 +1,167 @@
declare module 'slash2';
declare module '*.css';
declare module '*.less';
declare module '*.scss';
declare module '*.sass';
declare module '*.svg';
declare module '*.png';
declare module '*.jpg';
declare module '*.jpeg';
declare module '*.gif';
declare module '*.bmp';
declare module '*.tiff';
declare module 'omit.js';
declare module 'numeral';
declare module '@antv/data-set';
declare module 'mockjs';
declare module 'react-fittext';
declare module 'bizcharts-plugin-slider';
declare module 'react-split-pane/lib/Pane';
// preview.pro.ant.design only do not use in your production ;
// preview.pro.ant.design Dedicated environment variable, please do not use it in your project.
declare let ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION: 'site' | undefined;
declare const REACT_APP_ENV: 'test' | 'dev' | 'pre' | false;
type Result<T> = {
code: number;
data: T;
msg: string;
};
type DavinciResponseHeader = {
code: number;
msg: string;
token: string;
};
type DavinciResponse<T> = {
header: DavinciResponseHeader;
payload: T;
};
// 达芬奇接口返回的参数格式
type DavinciResult<T> = {
payload: T;
header: {
msg: string;
code: number;
token: string;
};
};
// 新请求器下的超音数分页接口声明泛型
type TPaginationResponse<T> = {
content: T[];
current: number;
pageSize: number;
total: number;
};
type DavinciPaginationResponse<T> = DavinciResult<{
resultList: T[];
pageNo: number;
pageSize: number;
totalCount: number;
[key: string]: any;
}>;
type BDResponse<T> = {
code: string;
data: T;
msg: string;
traceId: string;
};
type TopNConfig = {
computeType: 'field' | 'dimension';
column: string;
direction: 'asc' | 'desc';
limit: number;
};
type ColumnType = {
name: string;
type: string;
};
type DataType = {
columns: ColumnType[];
pageNo: number;
pageSize: number;
totalCount: number;
resultList: any[];
sqlToExec: string;
timeUsed: number;
};
type QueryVariable = { name: string; value: string | number }[];
type GetDataParams = {
groups: string[];
aggregators: { column: string; func: string }[];
filters: any[];
params?: QueryVariable;
orders?: { column: string; direction?: string; sortList?: string[] }[];
limit: number;
cache: boolean;
expired: number;
flush: boolean;
pageNo?: number;
pageSize?: number;
nativeQuery: boolean;
topN?: TopNConfig;
classId?: number;
};
type ReportEventParams = {
event: string;
dt_pgid?: string;
page_title: string;
page_path?: string;
entity_id?: string | number;
singer_id?: number;
producer?: string;
ip?: string;
song_id?: number;
album_id?: number;
brand_id?: number;
company_id?: number;
song_ids?: string;
compare_Ids?: string;
element_name?: string;
entrance_name?: string;
category_id?: string;
category_type?: string;
conversation_name?: string;
msg?: string;
msg_type?: string;
search_value?: string;
[key: string]: string | number;
};
type RowSpanMapIndexItem = number[];
type RowSpanMap = Record<string, RowSpanMapIndexItem>;
type Pagination = {
current?: number;
pageSize?: number;
sort?: string;
orderCondition?: string;
};
type PromiseSettledItem = {
status: string;
value?: any;
reason?: any;
};
type PromiseSettledList = PromiseSettledItem[];
type PaginationResponse<T> = Result<{
content: T[];
current: number;
pageSize: number;
total: number;
}>;

View File

@@ -0,0 +1,176 @@
import moment, { Moment } from 'moment';
import { NumericUnit } from '../common/constants';
export function formatByDecimalPlaces(value: number | string, decimalPlaces: number) {
if (isNaN(+value) || decimalPlaces < 0 || decimalPlaces > 100) {
return value;
}
let strValue = (+value).toFixed(decimalPlaces);
if (!/^[0-9.]+$/g.test(strValue)) {
return '0';
}
while (strValue.includes('.') && (strValue.endsWith('.') || strValue.endsWith('0'))) {
strValue = strValue.slice(0, -1);
}
return strValue;
}
export function formatByThousandSeperator(value: number | string) {
if (isNaN(+value)) {
return value;
}
const partValues = value.toString().split('.');
partValues[0] = partValues[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return partValues.join('.');
}
export function formatByUnit(value: number | string, unit: NumericUnit) {
const numericValue = +value;
if (isNaN(numericValue) || unit === NumericUnit.None) {
return value;
}
let exponentValue = 0;
switch (unit) {
case NumericUnit.TenThousand:
case NumericUnit.EnTenThousand:
exponentValue = 4;
break;
case NumericUnit.OneHundredMillion:
exponentValue = 8;
break;
case NumericUnit.Thousand:
exponentValue = 3;
break;
case NumericUnit.Million:
exponentValue = 6;
break;
case NumericUnit.Giga:
exponentValue = 9;
break;
}
return numericValue / Math.pow(10, exponentValue);
}
export const getFormattedValue = (value: number | string, remainZero?: boolean) => {
if (remainZero && (value === undefined || +value === 0)) {
return 0;
}
if (value === undefined) {
return '-';
}
if (!isFinite(+value)) {
return value;
}
const unit =
+value >= 100000000
? NumericUnit.OneHundredMillion
: +value >= 10000
? NumericUnit.EnTenThousand
: NumericUnit.None;
let formattedValue = formatByUnit(value, unit);
formattedValue = formatByDecimalPlaces(
formattedValue,
unit === NumericUnit.OneHundredMillion ? 2 : +value < 1 ? 3 : 1,
);
formattedValue = formatByThousandSeperator(formattedValue);
if ((typeof formattedValue === 'number' && isNaN(formattedValue)) || +formattedValue === 0) {
return '-';
}
return `${formattedValue}${unit === NumericUnit.None ? '' : unit}`;
};
export const groupByColumn = (data: any[], column: string) => {
return data.reduce((result, item) => {
const resultData = { ...result };
const key = item[column];
if (!resultData[key]) {
resultData[key] = [];
}
resultData[key].push(item);
return resultData;
}, {});
};
// 获取任意两个日期中的所有日期
export function enumerateDaysBetweenDates(startDate: Moment, endDate: Moment, dateType?: any) {
let daysList: any[] = [];
const day = endDate.diff(startDate, dateType || 'days');
const format = dateType === 'months' ? 'YYYY-MM' : 'YYYY-MM-DD';
daysList.push(startDate.format(format));
for (let i = 1; i <= day; i++) {
daysList.push(startDate.add(1, dateType || 'days').format(format));
}
return daysList;
}
export const normalizeTrendData = (
resultList: any[],
dateColumnName: string,
valueColumnName: string,
startDate: string,
endDate: string,
dateType?: string,
) => {
const dateList = enumerateDaysBetweenDates(moment(startDate), moment(endDate), dateType);
const result = dateList.map((date) => {
const item = resultList.find((result) => result[dateColumnName] === date);
return {
...(item || {}),
[dateColumnName]: date,
[valueColumnName]: item ? item[valueColumnName] : 0,
};
});
return result;
};
export const getMinMaxDate = (resultList: any[], dateColumnName: string) => {
const dateList = resultList.map((item) => moment(item[dateColumnName]));
return [moment.min(dateList).format('YYYY-MM-DD'), moment.max(dateList).format('YYYY-MM-DD')];
};
export function hexToRgbObj(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
}
export function getLightenDarkenColor(col, amt) {
let result;
if (col?.includes('rgb')) {
const [r, g, b, a] = col.match(/\d+/g).map(Number);
result = { r, g, b, a };
} else {
result = hexToRgbObj(col) || {};
}
return `rgba(${result.r + amt},${result.g + amt},${result.b + amt}${
result.a ? `,${result.a}` : ''
})`;
}
export function getChartLightenColor(col) {
return getLightenDarkenColor(col, 80);
}
export const isMobile = window.navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i);
export function isProd() {
return (
window.location.origin.includes('tmeoa.com') ||
window.location.hostname === 's2.tencentmusic.com'
);
}
export function setToken(token: string) {
localStorage.setItem('SUPERSONIC_CHAT_TOKEN', token);
}
export function getToken() {
return localStorage.getItem('SUPERSONIC_CHAT_TOKEN');
}

View File

@@ -0,0 +1,20 @@
{
"compilerOptions": {
"outDir": "dist",
"module": "esnext",
"target": "es5",
"declaration": true,
"jsx": "react-jsx",
"moduleResolution":"Node",
"allowSyntheticDefaultImports": true,
"importHelpers": true,
},
"include": [
"src"
],
"exclude": [
"src/**/*.test.tsx",
"src/**/*.stories.tsx",
"src/setupTests.ts",
]
}

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noImplicitAny": false,
},
"include": [
"src"
]
}

View File

@@ -0,0 +1,16 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[Makefile]
indent_style = tab

View File

@@ -0,0 +1,8 @@
/lambda/
/scripts
/config
.history
public
dist
.umi
mock

View File

@@ -0,0 +1,38 @@
module.exports = {
extends: [require.resolve('@umijs/fabric/dist/eslint')],
// globals: {
// ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION: true,
// page: true,
// REACT_APP_ENV: true,
// },
rules: {
'spaced-comment': 'off',
'@typescript-eslint/no-parameter-properties': 'off',
'@typescript-eslint/no-redeclare': 'off',
'@typescript-eslint/no-namespace': 'off',
'no-param-reassign': 'off',
'no-underscore-dangle': 'off',
'no-restricted-syntax': 'off',
'@typescript-eslint/no-loop-func': 'off',
'consistent-type-definitions': 'off',
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/consistent-type-imports": "off",
"no-shadow": "off",
"@typescript-eslint/no-shadow": "off",
'no-useless-return': 'off',
'max-classes-per-file': 'off',
'no-return-assign': 'off',
'no-continue': 'off',
'no-bitwise': 'off',
'no-await-in-loop': 'off',
'@typescript-eslint/no-unused-expressions': 'off',
'global-require': 'off',
'no-plusplus': 'off',
'import/export': 'off',
'react-hooks/exhaustive-deps': 'off',
'import/no-extraneous-dependencies': 0,
'react-hooks/exhaustive-deps': 0,
'no-console': 0,
},
};

View File

@@ -0,0 +1,44 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
**/node_modules
# roadhog-api-doc ignore
/src/utils/request-temp.js
_roadhog-api-doc
# production
/dist
/supersonic-webapp
/.vscode
# misc
.DS_Store
npm-debug.log*
yarn-error.log
/coverage
.idea
package-lock.json
yarn.lock
*bak
.vscode
# visual studio code
.history
*.log
functions/*
.temp/**
# umi
.umi
.umi-production
# screenshot
screenshot
.firebase
.eslintcache
build
/public/version.js

View File

@@ -0,0 +1,23 @@
**/*.svg
package.json
.umi
.umi-production
/dist
.dockerignore
.DS_Store
.eslintignore
*.png
*.toml
docker
.editorconfig
Dockerfile*
.gitignore
.prettierignore
LICENSE
.eslintcache
*.lock
yarn-error.log
.history
CNAME
/build
/public

View File

@@ -0,0 +1,5 @@
const fabric = require('@umijs/fabric');
module.exports = {
...fabric.prettier,
};

View File

@@ -0,0 +1,5 @@
const fabric = require('@umijs/fabric');
module.exports = {
...fabric.stylelint,
};

View File

@@ -0,0 +1,15 @@
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const commitId = execSync('git rev-parse HEAD').toString().trim();
const file = path.resolve(__dirname, './public/version.js');
const data = {
commitId: commitId,
updateTime: new Date().toString(),
};
const feVersion = JSON.stringify(data, null, 4);
// 异步写入数据到文件
fs.writeFile(file, `feVersion=${feVersion}`, { encoding: 'utf8' }, (err) => {});
console.log(`成功写入版本文件,版本信息为${feVersion}`);

View File

@@ -0,0 +1,61 @@
# Ant Design Pro
This project is initialized with [Ant Design Pro](https://pro.ant.design). Follow is the quick guide for how to use.
## Environment Prepare
Install `node_modules`:
```bash
npm install
```
or
```bash
yarn
```
## Provided Scripts
Ant Design Pro provides some useful script to help you quick start and build with web project, code style check and test.
Scripts provided in `package.json`. It's safe to modify or add additional script:
### Start project
```bash
npm start
```
### Build project
```bash
npm run build
```
### Check code style
```bash
npm run lint
```
You can also use script to auto fix some lint error:
```bash
npm run lint:fix
```
### Test code
```bash
npm test
```
## More
You can view full document on our [official website](https://pro.ant.design). And welcome any feedback in our [github](https://github.com/ant-design/ant-design-pro).
#### 踩坑
1.antd `Select`组件如果默认不选中时默认值不是`undefeated`,则不显示 placeholder

View File

@@ -0,0 +1,19 @@
#!/bin/bash
npm i
if [ $? -ne 0 ]; then
echo "npm i failed"
exit 1
fi
npm run build
if [ $? -ne 0 ]; then
echo "build failed"
exit 1
fi
rm -rf dist.zip
zip -r dist.zip ./dist/
mkdir -p bin
mv dist.zip bin/
tar czf dist.tar.gz bin/dist.zip

View File

@@ -0,0 +1,19 @@
#!/bin/bash
npm i
if [ $? -ne 0 ]; then
echo "npm i failed"
exit 1
fi
npm run build:inner
if [ $? -ne 0 ]; then
echo "build failed"
exit 1
fi
rm -rf dist.zip
zip -r dist.zip ./dist/
mkdir -p bin
mv dist.zip bin/
tar czf dist.tar.gz bin/dist.zip

View File

@@ -0,0 +1,83 @@
// https://umijs.org/config/
import { defineConfig } from 'umi';
import defaultSettings from './defaultSettings';
import themeSettings from './themeSettings';
import proxy from './proxy';
import routes from './routes';
import moment from 'moment';
const { REACT_APP_ENV, RUN_TYPE } = process.env;
const publicPath = '/webapp/';
export default defineConfig({
define: {
// 添加这个自定义的环境变量
// 'process.env.REACT_APP_ENV': process.env.REACT_APP_ENV, // * REACT_APP_ENV 本地开发环境dev测试服test正式服prod
'process.env': {
...process.env,
API_BASE_URL: '/api/semantic/', // 直接在define中挂载裸露的全局变量还需要配置eslintts相关配置才能导致在使用中不会飘红冗余较高这里挂在进程环境下
CHAT_API_BASE_URL: '/api/chat/',
AUTH_API_BASE_URL: '/api/auth/',
},
},
metas: [
{
name: 'app_version',
content: moment().format('YYYY-MM-DD HH:mm:ss'),
},
],
devServer: { port: 8002 },
hash: true,
// history: { type: 'hash' },
antd: {},
dva: {
hmr: true,
},
layout: {
name: '',
locale: true,
siderWidth: 208,
...defaultSettings,
},
locale: {
// default zh-CN
default: 'zh-CN',
antd: true,
// default true, when it is true, will use `navigator.language` overwrite default
baseNavigator: false,
},
// dynamicImport: {
// loading: '@ant-design/pro-layout/es/PageLoading',
// },
targets: {
ie: 11,
},
// umi routes: https://umijs.org/docs/routing
routes,
// Theme for antd: https://ant.design/docs/react/customize-theme-cn
theme: {
...themeSettings,
},
esbuild: {},
title: false,
ignoreMomentLocale: true,
proxy: proxy[REACT_APP_ENV || 'dev'],
manifest: {
basePath: '/',
},
base: publicPath,
publicPath,
outputPath: RUN_TYPE === 'local' ? 'supersonic-webapp' : 'dist',
// https://github.com/zthxxx/react-dev-inspector
plugins: ['react-dev-inspector/plugins/umi/react-inspector'],
inspectorConfig: {
// loader options type and docs see below
exclude: [],
babelPlugins: [],
babelOptions: {},
},
resolve: {
includes: ['src/components'],
},
});

View File

@@ -0,0 +1,26 @@
import { Settings as LayoutSettings } from '@ant-design/pro-layout';
const Settings: LayoutSettings & {
pwa?: boolean;
logo?: string;
} = {
navTheme: 'light',
primaryColor: '#296DF3',
layout: 'mix',
contentWidth: 'Fluid',
fixedHeader: false,
fixSiderbar: true,
colorWeak: false,
title: '',
pwa: false,
// logo: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
iconfontUrl: '//at.alicdn.com/t/c/font_3201979_rncj6jun6k.js',
splitMenus: true,
menu: {
defaultOpenAll: true,
autoClose: false,
ignoreFlatMenu: true,
},
};
export default Settings;

View File

@@ -0,0 +1,16 @@
export default {
dev: {
'/api/chat/': {
target: 'http://localhost:9080',
changeOrigin: true,
},
'/api/semantic/': {
target: 'http://localhost:9081',
changeOrigin: true,
},
'/api/': {
target: 'http://localhost:9080',
changeOrigin: true,
},
},
};

View File

@@ -0,0 +1,43 @@
export const ROUTE_AUTH_CODES = {
CHAT: 'chat',
CHAT_SETTING: 'chatSetting',
SEMANTIC: 'semantic',
};
const ROUTES = [
{
path: '/chat',
name: 'chat',
component: './Chat',
access: ROUTE_AUTH_CODES.CHAT,
},
{
path: '/chatSetting',
name: 'chatSetting',
component: './SemanticModel/ChatSetting',
access: ROUTE_AUTH_CODES.CHAT_SETTING,
},
{
path: '/semanticModel',
name: 'semanticModel',
component: './SemanticModel/ProjectManager',
access: ROUTE_AUTH_CODES.SEMANTIC,
},
{
path: '/login',
name: 'login',
layout: false,
hideInMenu: true,
component: './Login',
},
{
path: '/',
redirect: '/chat',
},
{
path: '/401',
component: './401',
},
];
export default ROUTES;

View File

@@ -0,0 +1,52 @@
// import defaultSettings from './defaultSettings';
const constants = {
black85: 'rgba(0,10,36,0.85)',
black65: 'rgba(0,10,36,0.65)',
black45: 'rgba(0,10,36,0.45)',
black25: 'rgba(0,10,36,0.25)',
};
const settings = {
// 'primary-color': defaultSettings.primaryColor,
// Colors
'blue-6': '#296DF3',
'primary-color': '#296DF3',
'green-6': '#26C992',
'success-color': '#26C992',
'red-5': '#EF4872',
'error-color': '#EF4872',
'gold-6': '#FFB924',
'warning-color': '#FFB924',
// Color used by default to control hover and active backgrounds and for
// alert info backgrounds.
'primary-1': '#E3ECFD',
'primary-2': '#BED2FB',
'primary-3': '#86ACF8',
'primary-4': '#6193F6',
'primary-5': '#4E86F5',
'primary-6': '#296DF3',
'primary-7': '#0D57E8',
'primary-8': '#0B49C3',
'primary-9': '#093B9D',
'primary-10': '#062666',
// Base Scaffolding Variables
'heading-color': constants.black85,
'text-color': constants.black85,
'text-color-secondary': constants.black65,
'border-radius-base': '4px',
// Buttons
'btn-padding-horizontal-sm': '8px',
'btn-padding-horizontal-base': '16px',
'btn-padding-horizontal-lg': '16px',
'btn-default-color': constants.black65,
'btn-default-border': 'rgba(0,0,0,0.15)',
'btn-disable-color': constants.black25,
'btn-disable-border': 'rgba(0,10,36,0.15)',
'btn-disable-bg': 'rgba(0,10,36,0.04)',
};
export default settings;

View File

@@ -0,0 +1,10 @@
module.exports = {
testURL: 'http://localhost:8000',
testEnvironment: './tests/PuppeteerEnvironment',
verbose: false,
extraSetupFiles: ['./tests/setupTests.js'],
globals: {
ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION: false,
localStorage: null,
},
};

View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}

View File

@@ -0,0 +1,146 @@
{
"name": "supersonic-fe",
"version": "0.1.0",
"private": true,
"description": "data chat",
"scripts": {
"analyze": "cross-env ANALYZE=1 umi build",
"build": "npm run build:os",
"build:os": "node .writeVersion.js && cross-env REACT_APP_ENV=prod APP_TARGET=opensource umi build",
"build:os-local": "node .writeVersion.js && cross-env REACT_APP_ENV=prod APP_TARGET=opensource RUN_TYPE=local umi build",
"build:inner": "node .writeVersion.js && cross-env REACT_APP_ENV=prod APP_TARGET=inner umi build",
"build:test": "node .writeVersion.js && cross-env REACT_APP_ENV=test umi build",
"deploy": "npm run site && npm run gh-pages",
"dev": "npm run start:osdev",
"dev:os": "npm run start:osdev",
"dev:inner": "npm run start:dev",
"gh-pages": "gh-pages -d dist",
"i18n-remove": "pro i18n-remove --locale=zh-CN --write",
"postinstall": "umi g tmp",
"lint": "umi g tmp && npm run lint:js && npm run lint:style && npm run lint:prettier",
"lint-staged": "lint-staged",
"lint-staged:js": "eslint --ext .js,.jsx,.ts,.tsx ",
"lint:fix": "eslint --fix --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src && npm run lint:style",
"lint:js": "eslint --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src",
"lint:prettier": "prettier --check \"src/**/*\" --end-of-line auto",
"lint:style": "stylelint --fix \"src/**/*.less\" --syntax less",
"precommit": "lint-staged",
"prettier": "prettier -c --write \"src/**/*\"",
"start": "npm run start:osdev",
"start:dev": "cross-env REACT_APP_ENV=dev MOCK=none APP_TARGET=inner umi dev",
"start:osdev": "cross-env REACT_APP_ENV=dev PORT=9000 MOCK=none APP_TARGET=opensource umi dev",
"start:no-mock": "cross-env MOCK=none umi dev",
"start:no-ui": "cross-env UMI_UI=none umi dev",
"start:pre": "cross-env REACT_APP_ENV=pre umi dev",
"start:test": "cross-env REACT_APP_ENV=test MOCK=none umi dev",
"pretest": "node ./tests/beforeTest",
"test": "umi test",
"test:all": "node ./tests/run-tests.js",
"test:component": "umi test ./src/components",
"tsc": "tsc --noEmit"
},
"lint-staged": {
"**/*.less": "stylelint --syntax less",
"**/*.{js,jsx,ts,tsx}": "npm run lint-staged:js",
"**/*.{js,jsx,tsx,ts,less,md,json}": [
"prettier --write"
]
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 10"
],
"dependencies": {
"@ant-design/charts": "^1.3.3",
"@ant-design/icons": "^4.7.0",
"@ant-design/pro-card": "^1.11.13",
"@ant-design/pro-components": "^2.4.4",
"@ant-design/pro-descriptions": "^1.0.19",
"@ant-design/pro-form": "^1.23.0",
"@ant-design/pro-layout": "^6.38.22",
"@ant-design/pro-table": "^2.80.6",
"@antv/g6": "^4.8.14",
"@antv/layout": "^0.3.20",
"@antv/xflow": "^1.0.55",
"@babel/runtime": "^7.22.5",
"supersonic-chat-sdk": "^0.1.6",
"@types/numeral": "^2.0.2",
"@types/react-draft-wysiwyg": "^1.13.2",
"@types/react-syntax-highlighter": "^13.5.0",
"@umijs/route-utils": "^1.0.33",
"ace-builds": "^1.4.12",
"ahooks": "^3.7.7",
"antd": "^4.24.8",
"classnames": "^2.2.6",
"copy-to-clipboard": "^3.3.1",
"cross-env": "^7.0.0",
"crypto-js": "^4.0.0",
"echarts": "^5.0.2",
"echarts-for-react": "^3.0.1",
"eslint-config-tencent": "^1.0.4",
"jsencrypt": "^3.0.1",
"lodash": "^4.17.11",
"moment": "^2.29.1",
"numeral": "^2.0.6",
"omit.js": "^2.0.2",
"path-to-regexp": "^2.4.0",
"qs": "^6.9.0",
"react": "^17.0.0",
"react-ace": "^9.4.1",
"react-dev-inspector": "^1.8.4",
"react-dom": "^17.0.2",
"react-helmet-async": "^1.0.4",
"react-spinners": "^0.10.6",
"react-split-pane": "^2.0.3",
"react-syntax-highlighter": "^15.4.3",
"sql-formatter": "^2.3.3",
"umi": "^3.2.14",
"umi-request": "^1.0.8"
},
"devDependencies": {
"@ant-design/pro-cli": "^2.0.2",
"@types/classnames": "^2.2.7",
"@types/crypto-js": "^4.0.1",
"@types/draftjs-to-html": "^0.8.0",
"@types/echarts": "^4.9.4",
"@types/express": "^4.17.0",
"@types/history": "^4.7.2",
"@types/jest": "^26.0.0",
"@types/lodash": "^4.14.144",
"@types/pinyin": "^2.8.3",
"@types/qs": "^6.5.3",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@types/react-helmet": "^6.1.0",
"@umijs/fabric": "^2.4.0",
"@umijs/plugin-blocks": "^2.0.5",
"@umijs/plugin-esbuild": "^1.0.1",
"@umijs/preset-ant-design-pro": "^1.2.0",
"@umijs/preset-dumi": "^1.1.0-rc.6",
"@umijs/preset-react": "^1.7.4",
"@umijs/yorkie": "^2.0.3",
"carlo": "^0.9.46",
"cross-port-killer": "^1.1.1",
"detect-installer": "^1.0.1",
"eslint": "^7.1.0",
"eslint-plugin-chalk": "^1.0.0",
"eslint-plugin-import": "^2.27.5",
"express": "^4.17.1",
"gh-pages": "^3.0.0",
"jsdom-global": "^3.0.2",
"lint-staged": "^10.0.0",
"prettier": "^2.3.1",
"pro-download": "1.0.1",
"puppeteer-core": "^5.0.0",
"stylelint": "^13.0.0",
"typescript": "^4.0.3"
},
"engines": {
"node": ">=10.0.0"
},
"resolutions": {
"@types/react": "17.0.0"
},
"__npminstall_done": false
}

View File

@@ -0,0 +1 @@
preview.pro.ant.design

Binary file not shown.

After

Width:  |  Height:  |  Size: 551 B

Some files were not shown because too many files have changed in this diff Show More