chore: monorepoify

This commit is contained in:
12f23eddde 2023-02-05 23:39:00 +08:00
parent 7ed0761650
commit b282fd2a31
75 changed files with 4 additions and 32778 deletions

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "frontend"]
path = frontend
url = git@github.com:osslab-pku/gfi-frontend.git

1
frontend Submodule

@ -0,0 +1 @@
Subproject commit d9737d9eb298f8d44645be161f96ba6d24c47eba

View File

@ -1,2 +0,0 @@
node_modules/
build/

View File

@ -1,2 +0,0 @@
REACT_APP_ENV = 'development'
REACT_APP_BASE_URL = 'https://gfibot.io'

View File

@ -1,2 +0,0 @@
REACT_APP_ENV = 'development'
REACT_APP_BASE_URL = 'http://localhost:5000'

View File

@ -1,2 +0,0 @@
REACT_APP_ENV = 'production'
REACT_APP_BASE_URL = 'https://gfibot.io'

View File

@ -1,47 +0,0 @@
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"plugin:react/recommended",
"plugin:react-svg/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/eslint-recommended",
"prettier"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly",
"React": true
},
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2021,
"sourceType": "module"
},
"plugins": ["prettier", "react", "@typescript-eslint"],
"settings": {
"react": {
"version": "detect"
}
},
"ignorePatterns": ["build", "node_modules"],
"rules": {
"react/jsx-filename-extension": [ 2, { "extensions": [".js", ".jsx", ".ts", ".tsx"] }],
"prettier/prettier": "warn",
"react/jsx-indent": ["warn", 2, { "indentLogicalExpressions": true }],
"react/prop-types": "off",
"react/jsx-no-target-blank": "off",
"prefer-const": "warn",
"@typescript-eslint/ban-ts-comment": "off",
"no-empty-function": "warn",
"@typescript-eslint/no-empty-function": "warn",
"no-unused-expressions": "warn",
"no-unused-vars": "warn",
"@typescript-eslint/no-empty-interface": "warn"
}
}

25
frontend/.gitignore vendored
View File

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

View File

@ -1,7 +0,0 @@
{
"singleQuote": true,
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"endOfLine": "auto"
}

View File

@ -1,79 +0,0 @@
# GFI-Bot Frontend
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Environmental Variables For Running
You should create `.env.development` and `.env.production` in root directory of the frontend part of GFI-Bot (current directory) to set environmental variables (request urls etc.) before building.
```
REACT_APP_ENV = 'development' or 'production'
REACT_APP_BASE_URL ?= 'YOUR_SERVER_URL' # can be undifined
```
## 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 your browser.
The page will reload when you make changes.\
You may 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:prod` or `npm run build:dev`
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 can't go back!**
If you aren't 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 you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't 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/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

View File

@ -1,3 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-github" viewBox="0 0 16 16">
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8z"/>
</svg>

Before

Width:  |  Height:  |  Size: 717 B

2
frontend/index.d.ts vendored
View File

@ -1,2 +0,0 @@
declare module '*.png';
declare module '*.jpg';

View File

@ -1,44 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon-gfi.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="ML-powered 🤖 for finding and labeling good first issues in your GitHub project!"
/>
<link rel="apple-touch-icon" href="/apple-touch-icon.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="/manifest.json" />
<!--
Notice the use of 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-gfi.ico" or "favicon-gfi.ico", "/favicon-gfi.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>GFI Bot</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.jsx"></script>
<!--
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>

View File

@ -1,26 +0,0 @@
[build.environment]
# bypass npm auto install
NPM_FLAGS = "--version"
NODE_VERSION = "16"
[build]
publish = "build"
# command = "npx pnpm i --store=node_modules/.pnpm-store && npx pnpm run build"
[[redirects]]
from = "/api/*"
to = "http://gfibot.io:5000/api/:splat"
status = 200
force = true
[redirects.headers]
X-From = "Netlify"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[headers]]
for = "/manifest.webmanifest"
[headers.values]
Content-Type = "application/manifest+json"

24638
frontend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,165 +0,0 @@
{
"name": "gfi-bot-web",
"version": "0.1.0",
"private": true,
"dependencies": {
"@ant-design/icons": "^4.7.0",
"@stahl.luke/react-reveal": "^1.2.3",
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"@types/react-router-bootstrap": "^0.24.5",
"@visx/curve": "^2.1.0",
"@visx/gradient": "^2.10.0",
"@visx/group": "^2.10.0",
"@visx/responsive": "^2.10.0",
"@visx/scale": "^2.2.2",
"@visx/shape": "^2.10.0",
"axios": "^0.26.1",
"babel-preset-react-app": "^10.0.1",
"bfj": "^7.0.2",
"bootstrap": "^5.1.3",
"bootstrap-icons": "^1.7.2",
"camelcase": "^6.2.1",
"cross-env": "^7.0.3",
"css-loader": "^6.5.1",
"dotenv": "^10.0.0",
"dotenv-expand": "^5.1.0",
"echarts": "^5.2.2",
"echarts-for-react": "^3.0.2",
"fs-extra": "^10.0.0",
"gsap": "^3.9.1",
"jest": "^27.4.3",
"jest-watch-typeahead": "^1.0.0",
"prop-types": "^15.8.1",
"react": "^17.0.2",
"react-activation": "^0.10.2",
"react-app-polyfill": "^3.0.0",
"react-bootstrap": "^2.4.0",
"react-dev-utils": "^12.0.0",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-helmet-async": "^1.2.3",
"react-markdown": "^8.0.0",
"react-redux": "^7.2.6",
"react-refresh": "^0.11.0",
"react-router": "^6.2.1",
"react-router-bootstrap": "^0.25.0",
"react-router-cache-route": "^1.12.7",
"react-router-dom": "^5.3.0",
"react-syntax-highlighter": "^15.4.5",
"react-transition-group": "^4.4.2",
"redux": "^4.1.2",
"redux-persist": "^6.0.0",
"remark-gemoji": "^7.0.1",
"remark-gfm": "^3.0.1",
"remark-github": "^11.2.2",
"resolve": "^1.20.0",
"resolve-url-loader": "^4.0.0",
"semver": "^7.3.5",
"source-map-loader": "^3.0.0",
"style-loader": "^3.3.1",
"web-vitals": "^2.1.2"
},
"scripts": {
"start": "vite --mode production",
"dev": "vite --mode development",
"dev:local": "vite --mode devlocal",
"build": "vite build",
"serve": "vite preview",
"lint": "eslint --fix --ext .js,.jsx,.ts,.tsx src"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.js"
],
"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"
]
},
"devDependencies": {
"@types/react": "^18.0.5",
"@types/react-dom": "^18.0.1",
"@types/react-router-dom": "^5.3.3",
"@typescript-eslint/eslint-plugin": "^5.23.0",
"@typescript-eslint/parser": "^5.23.0",
"@vitejs/plugin-react": "^1.3.2",
"eslint": "^8.15.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-only-warn": "^1.0.3",
"eslint-plugin-react": "^7.29.4",
"eslint-plugin-react-hooks": "^4.5.0",
"typescript": "^4.6.3",
"vite": "^3.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-config-react-app": "^7.0.0",
"eslint-plugin-prettier": "^4.0.0",
"prettier": "^2.6.2"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 601 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

View File

@ -1,44 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon-gfi.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="/apple-touch-icon.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="/manifest.json" />
<!--
Notice the use of 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-gfi.ico" or "favicon-gfi.ico", "/favicon-gfi.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>GFI Bot</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.jsx"></script>
<!--
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.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -1,25 +0,0 @@
{
"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

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

View File

@ -1,217 +0,0 @@
'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

@ -1,154 +0,0 @@
'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

@ -1,51 +0,0 @@
'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

@ -1,244 +0,0 @@
import { requestGFI, getBaseURL } from './query';
import { userInfo } from '../storage';
import type {
RepoSort,
RepoBrief,
RepoDetail,
RepoGFIConfig,
SearchedRepo,
RepoUpdateConfig,
UserQueryHistory,
GFIInfo,
GFITrainingSummary,
GFIResponse,
GFIFailure,
} from '../model/api';
export const getRepoNum = async (lang?: string) => {
return await requestGFI<number>({
url: '/api/repos/num',
params: { lang },
});
};
export const getPagedRepoDetailedInfo = async (
start: string | number,
length: string | number,
lang?: string,
filter?: RepoSort
) => {
return await requestGFI<RepoDetail[]>({
url: '/api/repos/info/',
params: { start, length, lang, filter },
baseURL: getBaseURL(),
});
};
export const getPagedRepoBrief = async (
start: number,
length: number,
lang?: string,
filter?: RepoSort
) =>
await requestGFI<RepoBrief[]>({
url: '/api/repos/info/paged',
params: { start, length, lang, filter },
});
export const getRepoDetailedInfo = async (name: string, owner: string) => {
return await requestGFI<RepoDetail>({
url: '/api/repos/info/detail',
params: { name, owner },
});
};
export const getRepoInfo = async (name: string, owner: string) => {
return await requestGFI<RepoBrief>({
url: '/api/repos/info',
params: { name, owner },
});
};
export const searchRepoInfoByNameOrURL = async (
repoName?: string,
repoURL?: string
) => {
const { githubLogin } = userInfo();
return await requestGFI<[RepoBrief]>({
url: '/api/repos/info/search',
params: {
repo: repoName,
url: repoURL,
user: githubLogin,
},
});
};
export const getGFIByRepoName = async (
name: string,
owner: string,
start?: number,
length?: number
) =>
await requestGFI<GFIInfo[]>({
url: '/api/issue/gfi',
params: { owner, repo: name, start, length },
});
export const getGFINum = async (repoName?: string, repoOwner?: string) => {
return await requestGFI<number | undefined>({
url: '/api/issue/gfi/num',
params: {
name: repoName,
owner: repoOwner,
},
});
};
export const getLanguageTags = async () => {
return await requestGFI<string[]>({
url: '/api/repos/language',
});
};
export const addRepoToGFIBot = async (repoName: string, repoOwner: string) => {
const { githubLogin } = userInfo();
return await requestGFI<any>({
method: 'POST',
url: '/api/repos/add',
headers: {
'Content-Type': 'application/json',
},
data: {
user: githubLogin,
repo: repoName,
owner: repoOwner,
},
});
};
export const getAddRepoHistory = async (filter?: RepoSort) => {
const { githubLogin } = userInfo();
return await requestGFI<UserQueryHistory>({
url: '/api/user/queries',
params: {
user: githubLogin,
filter: filter,
},
});
};
export const getTrainingSummary = async (name?: string, owner?: string) => {
return await requestGFI<GFITrainingSummary[]>({
url: '/api/model/training/result',
params: {
name,
owner,
},
});
};
export const getUserSearches = async () => {
const { githubLogin } = userInfo();
return await requestGFI<SearchedRepo[]>({
url: '/api/user/searches',
params: {
user: githubLogin,
},
});
};
export const deleteUserSearch = async (
name: string,
owner: string,
id: number
) => {
const { githubLogin } = userInfo();
return await requestGFI<SearchedRepo[]>({
method: 'DELETE',
url: '/api/user/searches',
params: {
user: githubLogin,
name,
owner,
id,
},
});
};
export const deleteRepoQuery = async (name: string, owner: string) => {
const { githubLogin } = userInfo();
return await requestGFI<{
nums?: number;
queries: RepoBrief[];
finished_queries?: RepoBrief[];
}>({
method: 'DELETE',
url: '/api/user/queries',
params: {
user: githubLogin,
name,
owner,
},
baseURL: getBaseURL(),
});
};
export const updateRepoInfo = async (name: string, owner: string) => {
const { githubLogin } = userInfo();
return await requestGFI<string>({
method: 'PUT',
url: '/api/repos/update/',
data: {
github_login: githubLogin,
name,
owner,
},
baseURL: getBaseURL(),
});
};
export const updateTags = async (name: string, owner: string) => {
const { githubLogin } = userInfo();
return await requestGFI<string>({
method: 'PUT',
url: '/api/repos/update/tags',
data: {
github_login: githubLogin,
name,
owner,
},
baseURL: getBaseURL(),
});
};
export const getRepoConfig = async (name: string, owner: string) => {
const { githubLogin } = userInfo();
return await requestGFI<RepoGFIConfig>({
url: '/api/user/queries/config',
params: {
user: githubLogin,
name,
owner,
},
});
};
export const updateRepoConfig = async (
name: string,
owner: string,
config: RepoGFIConfig
) => {
const { githubLogin } = userInfo();
return await requestGFI<string>({
method: 'PUT',
url: '/api/user/queries/config',
params: {
user: githubLogin,
name,
owner,
},
data: config,
});
};

View File

@ -1,82 +0,0 @@
import { requestGFI, asyncRequest, RequestParams } from './query';
import { userInfo } from '../storage';
import {
GitHubIssueResponse,
GitHubRepoPermissions,
GitHubHTTPResponse,
} from '../model/github';
export const requestGitHub = async <T>(params: RequestParams) => {
// if token exists, add token to headers
const { githubToken } = userInfo();
if (githubToken) params.headers = { Authorization: `token ${githubToken}` };
const res = await asyncRequest<GitHubHTTPResponse<T>>(params);
if (!res) return undefined;
if (res && !res.error) {
return res.data ? res.data : res;
} else if (typeof params.onError === 'function') {
// normally when an error occurs, status code != 200
// but in this case, we want to keep the compatibility
params.onError(new Error(String(res.error)));
}
return undefined;
};
/** redirect to gh oauth login */
const gitHubOAuthLogin = async () => {
return await requestGFI<string>({
url: '/api/user/github/login',
});
};
export const gitHubLogin = () => {
const { hasLogin, name } = userInfo();
if (hasLogin && name !== undefined) {
window.location.reload();
return;
}
gitHubOAuthLogin().then((url) => {
if (url) {
window.location.assign(url);
}
});
};
export const checkGithubLogin = async () => {
const { githubLogin, githubToken } = userInfo();
if (githubToken) {
const res = await requestGitHub<any>({
url: `https://api.github.com/users/${githubLogin}`,
});
if (res) return true;
}
return false;
};
/** User must have write access */
export const checkHasRepoPermissions = async (
repoName: string,
owner: string
) => {
const { hasLogin, githubToken } = userInfo();
if (!hasLogin) return false;
const res = await requestGitHub<{ permissions: GitHubRepoPermissions }>({
url: `https://api.github.com/repos/${owner}/${repoName}`,
});
if (!res || !res.permissions) return false;
return (
!!res.permissions.maintain ||
!!res.permissions.admin ||
!!res.permissions.push
);
};
export const getIssueByRepoInfo = async (
repoName: string,
owner?: string,
issueId?: string | number
) => {
// url such as https://api.github.com/repos/pallets/flask/issues/4333
const url = `https://api.github.com/repos/${owner}/${repoName}/issues/${issueId}`;
return await requestGitHub<Partial<GitHubIssueResponse>>({ url });
};

View File

@ -1,88 +0,0 @@
import axios, { AxiosError } from 'axios';
import { userInfo } from "../storage";
import { GFIResponse } from "../model/api";
type HTTPMethods = 'GET' | 'POST' | 'DELETE' | 'PATCH' | 'PUT';
type ErrorFunc = null | ((error: Error | AxiosError) => any);
type AnyObject = { [key: string]: any };
export type RequestParams = {
/** request method */
method?: HTTPMethods;
/** request data */
baseURL?: string;
/** request url */
url: string;
/** request params */
params?: AnyObject;
/** request headers */
headers?: AnyObject;
/** request payload */
data?: AnyObject;
/** error handler */
onError?: ErrorFunc;
};
export const URL_KEY = 'baseURL';
export const getBaseURL = () => {
if (import.meta.env.REACT_APP_ENV === 'production') {
return import.meta.env.REACT_APP_BASE_URL;
}
const url = localStorage.getItem(URL_KEY);
if (url && url.length) {
return url;
}
const baseURL = import.meta.env.REACT_APP_BASE_URL || '';
localStorage.setItem(URL_KEY, baseURL);
return baseURL;
};
/** wrapper for request data **/
export const requestGFI = async <T>(params: RequestParams) => {
// if token exists, add token to headers
const { githubToken } = userInfo();
if (githubToken) params.headers = { Authorization: `token ${githubToken}` };
const res = await asyncRequest<GFIResponse<T>>(params);
if (!res) return undefined;
if (200 <= res.code && res.code < 300 && res.result) {
return res.result;
} else if (typeof params.onError === 'function') {
// normally when an error occurs, status code != 200
// but in this case, we want to keep the compatibility
params.onError(new Error(String(res.result)));
}
return undefined;
};
/** request wrapper */
export const asyncRequest: <T>(
params: RequestParams
) => Promise<T | undefined> = async (params: RequestParams) => {
try {
const method = params.method || 'GET';
const baseURL = params.baseURL || getBaseURL();
const res = await axios({
method,
baseURL,
url: params.url,
params: params.params,
headers: params.headers,
data: params.data,
});
if (200 <= res.status && res.status < 300 && res.data) {
return res.data;
} else {
// use callback function to handle error
const msg = res.data || res.statusText;
throw new Error(msg);
}
} catch (error: any | AxiosError) {
// log
console.error('%s %s: %s', params.url, error.name, error.message);
if (typeof params.onError === 'function') {
params.onError(error);
}
return undefined;
}
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1017 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 396 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 314 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

View File

@ -1,17 +0,0 @@
html body {
height: 100%;
width: 100%;
}
root {
width: 100%;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
.main-container {
min-height: 100vh;
}

View File

@ -1,67 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { Helmet, HelmetProvider } from 'react-helmet-async';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { BrowserRouter, Route } from 'react-router-dom';
import { CacheRoute, CacheSwitch } from 'react-router-cache-route';
import { AliveScope } from 'react-activation';
import { Container } from 'react-bootstrap';
import { DescriptionPage } from './pages/descriptionPage';
import { GFIHeader } from './pages/GFIHeader';
import { Repositories } from './pages/repositories/repositories';
import { persistor, store } from './storage/configureStorage';
import reportWebVitals from './reportWebVitals';
import { MainPage } from './pages/main/mainPage';
import { LoginRedirect } from './pages/login/GFILoginComponents';
import {
GlobalRefProvider,
WindowContextProvider,
} from './pages/app/windowContext';
import { GFIPortal } from './pages/portal/GFIPortal';
import { GFICopyright } from './pages/GFIComponents';
ReactDOM.render(
<React.StrictMode>
<HelmetProvider>
<Helmet></Helmet>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<WindowContextProvider>
<GlobalRefProvider>
<BrowserRouter>
<AliveScope>
<Container
fluid
className="no-gutters mx-0 px-0 main-container"
>
<GFIHeader />
<CacheSwitch>
<CacheRoute exact path="/" component={MainPage} />
<CacheRoute path="/home" component={DescriptionPage} />
<CacheRoute path="/repos" component={Repositories} />
<CacheRoute path="/portal" component={GFIPortal} />
<Route path="/login/redirect" component={LoginRedirect} />
<CacheRoute path="*" component={MainPage} />
</CacheSwitch>
<GFICopyright />
</Container>
</AliveScope>
</BrowserRouter>
</GlobalRefProvider>
</WindowContextProvider>
</PersistGate>
</Provider>
</HelmetProvider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -1,107 +0,0 @@
export type GFIResponse<T> = {
code?: number;
result: T;
};
export type GFIFailure = {
detail: string | ValidationError[];
};
/** FastAPI Validation Error */
export type ValidationError = {
/** Location */
loc: (Partial<string> & Partial<number>)[];
/** Message */
msg: string;
/** Error Type */
type: string;
};
/** Repo Info */
export interface RepoBrief {
name: string;
owner: string;
description?: string;
language?: string;
topics: string[];
}
type MonthlyCount = {
/** ISO datestring */
month: string;
/** Number of * in the month */
count: number;
};
/** Repo Info (with monthly stats) */
export type RepoDetail = RepoBrief & {
monthly_stars: MonthlyCount[];
monthly_commits: MonthlyCount[];
monthly_issues: MonthlyCount[];
monthly_pulls: MonthlyCount[];
};
/** supported sort */
export type RepoSort =
| 'popularity'
| 'gfis'
| 'median_issue_resolve_time'
| 'newcomer_friendly';
export type UserQueryHistory = {
/** number of queries in total */
nums: number;
/** pending queries */
queries: RepoBrief[];
/** finished queries */
finished_queries: RepoBrief[];
};
export type GFIInfo = {
name: string;
owner: string;
probability: number;
number: number;
/** ISO datestring */
last_updated: string;
title?: string;
state?: 'closed' | 'open' | 'resolved';
};
export type GFITrainingSummary = {
name: string;
owner: string;
issues_train: number;
issues_test: number;
n_resolved_issues: number;
n_newcomer_resolved: number;
last_updated: string;
/** performance metrics are not available during training */
accuracy?: number;
auc?: number;
};
export type RepoGFIConfig = {
newcomer_threshold: number;
gfi_threshold: number;
need_comment: boolean;
issue_tag: string;
};
export type RepoUpdateConfig = {
task_id: string | null;
interval: number;
begin_time: string;
};
export type RepoConfig = {
update_config: RepoUpdateConfig;
repo_config: RepoGFIConfig;
};
export type SearchedRepo = {
name: string;
owner: string;
created_at: string;
increment: number;
};

View File

@ -1,24 +0,0 @@
type AnyObject = { [key: string]: any };
export type GitHubHTTPResponse<T extends AnyObject> = {
[key: string]: any;
status: number;
data?: T;
};
export type GitHubIssueResponse = {
number: number;
title: string;
state: string;
active_lock_reason: string;
body: string;
html_url: string;
};
export type GitHubRepoPermissions = {
admin: boolean;
maintain: boolean;
push: boolean;
triage: boolean;
pull: boolean;
};

View File

@ -1,9 +0,0 @@
import { RepoBrief } from './api';
export const MockedRepoInfo: RepoBrief = {
name: 'scikit-learn',
owner: 'scikit-learn',
language: 'Python',
description: 'scikit-learn: machine learning in Python',
topics: ['python', 'data-science', 'machine-learning'],
};

View File

@ -1,519 +0,0 @@
import { Container, Col, Row, Form, Pagination, Alert } from 'react-bootstrap';
import React, {
ChangeEvent,
createRef,
forwardRef,
MutableRefObject,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import { checkIsNumber, checkIsPercentage, defaultFontFamily } from '../utils';
import { gsap } from 'gsap';
import '../style/gfiStyle.css';
import { Variant as AlarmPanelVariants } from 'react-bootstrap/types';
export function GFICopyright() {
const copyright =
'Copyright © 2022 OSS Lab, Peking University. All rights reserved.';
return (
<Container
style={{
paddingTop: '20px',
paddingBottom: '10px',
fontFamily: defaultFontFamily,
fontSize: '15px',
fontWeight: '100',
position: 'sticky',
top: '100vh',
}}
>
<Row>
<Col style={{ textAlign: 'center' }}>{copyright}</Col>
</Row>
</Container>
);
}
export interface GFIPaginationProps {
maxPagingCount: number;
pageNums: number;
pageIdx: number;
onPageBtnClicked?: () => void;
toPage: (page: number) => void;
needInputArea?: boolean;
onFormInput?: (target: EventTarget) => void;
needPadding?: boolean;
className?: string;
}
export function GFIPagination(props: GFIPaginationProps) {
const { maxPagingCount, toPage, pageIdx, pageNums, needPadding, className } =
props;
const toFirstPage = useCallback(() => {
toPage(1);
}, [toPage]);
const toPrevPage = useCallback(() => {
if (pageIdx === 1) {
toFirstPage();
} else {
toPage(pageIdx - 1);
}
}, [pageIdx, toPage, toFirstPage]);
const toLastPage = () => {
toPage(pageNums);
};
const toNextPage = () => {
if (pageIdx === pageNums) {
return;
}
if (pageIdx === pageNums - 1) {
toLastPage();
} else {
toPage(pageIdx + 1);
}
};
const calRenderRange = (pageNum: number, selectedIdx: number) => {
const pageArray: number[] = [];
let idx = Math.max(selectedIdx - maxPagingCount + 2, 1);
for (let i = 0; i < maxPagingCount; i += 1, idx += 1) {
pageArray.push(idx);
if (idx + 1 > pageNum) {
break;
}
}
return pageArray;
};
const renderPagingItem = (pageNum: number, selectedIdx: number) => {
const pageArray = calRenderRange(pageNum, selectedIdx);
const renderedArray = pageArray.map((ele, idx) => {
return (
<Pagination.Item
key={ele}
active={ele === selectedIdx}
onClick={() => toPage(ele)}
>
{' '}
{ele}{' '}
</Pagination.Item>
);
});
if (!pageArray.includes(1)) {
const showDot = !pageArray.includes(2);
renderedArray.unshift(renderExpPagingItem(1, showDot));
}
if (!pageArray.includes(pageNums) && pageNums) {
const showDot = !pageArray.includes(pageNums - 1);
renderedArray.push(renderExpPagingItem(pageNums, showDot));
}
return renderedArray;
};
const renderExpPagingItem = (pageNum: number, shotDot: boolean) => {
let msg: string = pageNum.toString();
if (shotDot) {
msg = `.. ${pageNum}`;
}
return (
<Pagination.Item key={pageNum} onClick={() => toPage(pageNum)}>
{' '}
{msg}{' '}
</Pagination.Item>
);
};
return (
<Container
style={
needPadding
? { overflow: 'hidden' }
: { overflow: 'hidden', padding: '0' }
}
className={className}
>
<Row style={{ marginTop: '10px' }}>
<Form.Group>
<Col sm={8} style={{ float: 'left' }}>
<Pagination style={{ margin: '0 auto' }}>
<Pagination.Prev
onClick={() => {
toPrevPage();
}}
/>
{renderPagingItem(pageNums, pageIdx)}
<Pagination.Next
onClick={() => {
toNextPage();
}}
/>
</Pagination>
</Col>
{props.needInputArea && (
<Col sm={4} style={{ float: 'right' }}>
<Form.Label
style={{
maxWidth: '80px',
float: 'right',
}}
>
<Form.Control
placeholder={`${props.pageIdx}/${props.pageNums}`}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
props.onFormInput && props.onFormInput(e.target);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && props.onPageBtnClicked) {
e.preventDefault();
props.onPageBtnClicked();
}
}}
/>
</Form.Label>
</Col>
)}
</Form.Group>
</Row>
</Container>
);
}
export type GFIAlarmPanelVariants = AlarmPanelVariants;
export interface GFIAlarmProps {
onClose?: () => void;
title?: string;
variant?: AlarmPanelVariants;
className?: string;
children?: React.ReactNode;
}
export class GFIAlarm extends React.Component<GFIAlarmProps> {
private readonly selfRef: React.RefObject<any>;
constructor(props: GFIAlarmProps) {
super(props);
this.selfRef = createRef();
}
componentDidMount() {
const alarmTimeline = gsap.timeline();
alarmTimeline
.from(this.selfRef.current, {
duration: 0.4,
autoAlpha: 0,
y: -25,
})
.play();
}
alarmOnClose = () => {
const timeline = gsap.timeline();
timeline
.to(this.selfRef.current, {
duration: 0.4,
autoAlpha: 0,
y: -25,
})
.eventCallback('onComplete', () => {
if (this.props.onClose) {
this.props.onClose();
}
})
.play();
};
render() {
const { title } = this.props;
return (
<Alert
variant={this.props.variant ? this.props.variant : 'danger'}
dismissible
ref={this.selfRef}
onClick={this.alarmOnClose}
style={{
borderRadius: '5px',
}}
className={this.props?.className}
>
{title}
{this.props?.children}
</Alert>
);
}
}
export interface GFIProgressBarProps {
barWidth: string | number;
height: string;
onFinished: () => void;
}
interface GFIProgressBarStates {
barWidth: any;
}
export class GFIProgressBar extends React.Component<
GFIProgressBarProps,
GFIProgressBarStates
> {
private readonly barRef: React.RefObject<any>;
constructor(props: GFIProgressBarProps) {
super(props);
this.barRef = React.createRef();
this.state = {
barWidth: '0%',
};
}
checkValidWidth = (width: any) => {
return (
(checkIsNumber(width.slice(0, -1)) && width.slice(-1) === '%') ||
checkIsNumber(width)
);
};
componentDidUpdate(
prevProps: GFIProgressBarProps,
prevState: GFIProgressBarStates,
snapshot: any
) {
const { barWidth, onFinished } = this.props;
if (
this.checkValidWidth(barWidth) &&
this.checkValidWidth(prevProps.barWidth)
) {
if (barWidth === prevProps.barWidth) {
return;
}
gsap
.to(this.barRef.current, {
duration: 0.2,
width: barWidth,
paused: true,
})
.eventCallback('onComplete', () => {
this.setState({
barWidth,
});
})
.play();
if (barWidth === '100%' || barWidth === window.innerWidth) {
gsap
.to(this.barRef.current, {
duration: 0.2,
autoAlpha: 0,
})
.eventCallback('onComplete', () => {
if (onFinished) {
onFinished();
}
})
.play();
}
}
}
render() {
const { height } = this.props;
return (
<div
style={{
backgroundColor: '#85a5ff',
height,
width: this.state.barWidth,
borderRadius: '2px',
}}
ref={this.barRef}
/>
);
}
}
export interface GFIOverlay {
width?: string;
height?: string;
direction: 'left' | 'right' | 'top' | 'bottom';
children?: React.ReactNode;
hidden?: boolean;
id: string;
callback?: () => void;
animation?: boolean;
className?: string;
}
export const GFIOverlay = forwardRef<HTMLDivElement, GFIOverlay>(
(props: GFIOverlay, ref) => {
const selfRef = useRef<HTMLDivElement>(null);
const {
id,
width,
height,
direction,
children,
hidden,
callback,
animation,
className,
} = props;
const hide = hidden ? 'hidden' : '';
const resizeHandler = () => {
if (animation && selfRef.current && direction === 'right') {
selfRef.current.style.left = '';
}
};
useEffect(() => {
window.addEventListener('resize', resizeHandler);
return () => {
window.removeEventListener('resize', resizeHandler);
};
}, []);
useEffect(() => {
const currentRef = (ref as MutableRefObject<HTMLDivElement>).current;
if (currentRef && !hidden) {
document
.getElementsByTagName('html')[0]
.classList.add('scrollbar-hidden');
currentRef.style.display = 'block';
// animation
// currently only for direction = right & left
if (
animation &&
selfRef.current &&
direction === 'right' &&
width &&
checkIsPercentage(width)
) {
selfRef.current.style.left = '100%';
currentRef.style.overflowX = 'hidden';
gsap
.to(selfRef.current, {
duration: 0.4,
left: `${100 - parseFloat(width)}%`,
ease: 'power3.out',
})
.play();
} else if (
animation &&
selfRef.current &&
direction === 'left' &&
width &&
checkIsPercentage(width)
) {
selfRef.current.style.left = `${0 - parseFloat(width)}%`;
currentRef.style.overflowX = 'hidden';
gsap
.to(selfRef.current, {
duration: 0.4,
left: `0`,
ease: 'power3.out',
})
.play();
}
} else if (currentRef) {
currentRef.style.display = 'none';
}
}, [hidden]);
return (
<div
id={id}
className={`full-overlay ${hide}`}
ref={ref}
onClick={(e) => {
e.stopPropagation();
if (ref) {
document
.getElementsByTagName('html')[0]
.classList.remove('scrollbar-hidden');
const currentRef = (ref as MutableRefObject<HTMLDivElement>)
.current;
if (currentRef) {
currentRef.style.display = 'none';
}
if (callback) {
callback();
}
}
}}
>
<div
className={`full-overlay-${direction} ${className}`}
style={{
width: width || '100%',
height: height || '100%',
}}
onClick={(e) => e.stopPropagation()}
ref={selfRef}
>
{children}
</div>
</div>
);
}
);
GFIOverlay.displayName = 'GFIOverlay';
export function GFISimplePagination(props: {
nums: number;
onClick: (idx: number) => void;
title?: string[];
}) {
const { nums, onClick, title } = props;
const [selectedIdx, setSelectedIdx] = useState<number>(0);
let showTitle = '';
let shouldShowTitle = false;
if (title && title.length === nums) {
showTitle = '-title';
shouldShowTitle = true;
}
const render = () => {
const List = [];
for (let i = 0; i < nums; i++) {
List.push(i);
}
return List.map((i, idx) => {
const isSelected = idx === selectedIdx ? 'page-selected' : '';
const idRandom = Math.random() * 1000;
return (
<div
key={`simple-pagination-item-${title}-${idx}-${idRandom}`}
className={`simple-pagination-item${showTitle} ${isSelected} hoverable`}
onClick={() => {
if (idx !== selectedIdx) {
setSelectedIdx(idx);
onClick(idx);
}
}}
>
{shouldShowTitle && title && title[idx]}
</div>
);
});
};
return (
<div className="simple-pagination flex-row align-center justify-content-between">
{render()}
</div>
);
}

View File

@ -1,158 +0,0 @@
import React, { useCallback, useRef, useState } from 'react';
import { SettingOutlined, ReloadOutlined } from '@ant-design/icons';
import { GFIAlarm, GFIOverlay } from './GFIComponents';
import '../style/gfiStyle.css';
import { useIsMobile } from './app/windowContext';
import { Button, Form } from 'react-bootstrap';
import { getBaseURL, URL_KEY } from '../api/query';
import { checkIsValidUrl } from '../utils';
export function GFIDevController() {
const overlayRef = useRef<HTMLDivElement>(null);
const [hideOverlay, setHideOverlay] = useState(true);
const [showAlarmBanner, setShowAlarmBanner] = useState(false);
const [alarmBannerTitle, setAlarmBannerTitle] = useState('');
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
const [updateBannerTitle, setUpdateBannerTitle] = useState('');
const isMobile = useIsMobile();
const [shouldDisableURLBtn, setShouldDisableURLBtn] = useState(true);
const [showRefreshBtn, setShowRefreshBtn] = useState(false);
const baseURLRef = useRef<HTMLInputElement | null>(null);
const urlRef = useCallback((node: HTMLInputElement | null) => {
baseURLRef.current = node;
}, []);
const modifyBaseURL = useCallback(() => {
if (baseURLRef && baseURLRef.current) {
const nxtBaseURL = baseURLRef.current.value || '';
if (checkIsValidUrl(nxtBaseURL)) {
localStorage.setItem(URL_KEY, nxtBaseURL);
setShowUpdateBanner(true);
setShowRefreshBtn(true);
setUpdateBannerTitle('Base URL successfully modified!');
}
} else {
setShowAlarmBanner(true);
setAlarmBannerTitle('You should enter a correct URL!');
setShowRefreshBtn(false);
}
}, []);
return (
<div className="gfi-dev-controller flex-row">
<GFIOverlay
className="gfi-dev-controller-overlay"
id="gfi-dev-controller-overlay"
direction="right"
width={isMobile ? '80%' : '40%'}
hidden={hideOverlay}
ref={overlayRef}
callback={() => {
setHideOverlay(true);
}}
animation
>
<div className="gfi-repo-setting-item-title" id={'dev-setting-title'}>
GFI-Bot Dev Environment Settings
</div>
<div className="gfi-repo-setting-item-container" id={'dev-setting'}>
{showUpdateBanner && (
<GFIAlarm
variant="success"
title={updateBannerTitle}
onClose={() => setShowUpdateBanner(false)}
/>
)}
{showAlarmBanner && (
<GFIAlarm
variant="danger"
title={alarmBannerTitle}
onClose={() => setShowAlarmBanner(false)}
/>
)}
<Form className={'dev-setting-form'}>
<Form.Group controlId="base-url">
<Form.Label className="gfi-repo-setting-form-label">
Modify Base URL
</Form.Label>
<div className="flex-row">
<Form.Control
ref={urlRef}
placeholder={getBaseURL()}
style={{
borderBottomRightRadius: '0',
borderTopRightRadius: '0',
}}
onChange={(event) => {
if (event.target.value.length) {
setShouldDisableURLBtn(false);
} else {
setShouldDisableURLBtn(true);
}
}}
/>
<Button
variant="outline-success"
style={{
borderBottomLeftRadius: '0',
borderTopLeftRadius: '0',
}}
onClick={() => {
modifyBaseURL();
}}
disabled={shouldDisableURLBtn}
>
Change
</Button>
</div>
{showRefreshBtn && (
<button
className="flex-row dev-setting-refresh-btn flex-center"
onClick={() => {
window.location.reload();
}}
>
<ReloadOutlined
style={{
fontSize: '12px',
}}
/>
<div
style={{
textDecoration: 'underline',
marginLeft: '0.2rem',
fontSize: '0.9rem',
}}
>
{' '}
Refresh{' '}
</div>
</button>
)}
</Form.Group>
</Form>
</div>
</GFIOverlay>
<button
className="gfi-dev-controller-btn"
onClick={() => {
setHideOverlay(false);
}}
>
<SettingOutlined
style={{
fontSize: '17px',
color: 'darkgray',
}}
/>
<div className="gfi-dev-controller-title">Dev Environment Settings</div>
</button>
</div>
);
}

View File

@ -1,406 +0,0 @@
// TODO:MSKYurina
// Refactor using TypeScript
import React, { useEffect, useRef, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
Container,
Nav,
Navbar,
Button,
Popover,
OverlayTrigger,
ProgressBar,
} from 'react-bootstrap';
import { LinkContainer } from 'react-router-bootstrap';
import {
GithubFilled,
UserDeleteOutlined,
SettingOutlined,
} from '@ant-design/icons';
import 'bootstrap/dist/css/bootstrap.min.css';
import { gsap } from 'gsap';
import { useIsMobile } from './app/windowContext';
import { defaultFontFamily } from '../utils';
import { gitHubLogin } from '../api/githubApi';
import {
createAccountNavStateAction,
createLogoutAction,
} from '../storage/reducers';
import '../style/gfiStyle.css';
import navLogo from '../assets/favicon-thumbnail.png';
import { GFIPortalPageNav } from './portal/GFIPortal';
import { GFIDevController } from './GFIDevController';
export function GFIHeader() {
const dispatch = useDispatch();
const logout = () => {
dispatch(createLogoutAction());
window.location.reload();
};
const hasLogin = useSelector((state) => {
if ('loginReducer' in state && 'hasLogin' in state.loginReducer)
return state.loginReducer.hasLogin;
return undefined;
});
const userName = useSelector((state) => {
if ('loginReducer' in state && 'name' in state.loginReducer)
return state.loginReducer.name;
return undefined;
});
// Login / Logout related components
const [popOverToggled, setPopOverToggled] = useState(false);
const [showPopOver, setShowPopOver] = useState(false);
const popOverRef = useRef(null);
const loginBtnRef = useRef(null);
const checkIfClosePopOver = (e) => {
const ele = e.target;
if (
popOverRef.current &&
!popOverRef.current.contains(ele) &&
!loginBtnRef.current.contains(ele)
) {
e.preventDefault();
e.stopPropagation();
setShowPopOver(false);
}
};
useEffect(() => {
if (popOverToggled === true) {
window.addEventListener('mousedown', (e) => checkIfClosePopOver(e));
}
return () => {
window.removeEventListener('mousedown', (e) => checkIfClosePopOver(e));
};
}, [popOverToggled]);
// Popover menu, currently for user logout
const logoutPopover = (
<Popover id="popover-basic">
<Popover.Body>
<div ref={popOverRef}>
<p>
{' '}
<u> Hi, {userName} </u>{' '}
</p>
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
<UserDeleteOutlined
style={{
fontSize: '17px',
}}
/>
<Button
onClick={logout}
size="sm"
variant="outline-danger"
style={{ marginLeft: 'auto' }}
>
Logout
</Button>
</div>
</div>
</Popover.Body>
</Popover>
);
// Sign in component
const signInLink = () => {
const login = hasLogin === true && userName !== undefined;
if (!login) {
return (
<Button
onClick={gitHubLogin}
variant="outline-secondary"
size="sm"
style={{ marginRight: '15px' }}
className="sign-in"
>
Sign in via GitHub
</Button>
);
}
return (
<div ref={loginBtnRef}>
<OverlayTrigger
trigger="click"
placement="bottom"
overlay={logoutPopover}
onToggle={() => {
setShowPopOver(true);
setPopOverToggled(true);
}}
show={showPopOver}
>
<Button
variant="outline-secondary"
size="sm"
style={{
marginRight: '15px',
}}
onClick={() => {
if (showPopOver) {
setShowPopOver(false);
setPopOverToggled(false);
}
}}
>
{userName}
</Button>
</OverlayTrigger>
</div>
);
};
// Display responsively
const isMobile = useIsMobile();
const iconRef = useRef(null);
const hideAccountNav = () => {
dispatch(createAccountNavStateAction({ show: false }));
};
const showAccountNav = () => {
dispatch(createAccountNavStateAction({ show: true }));
};
const renderNavItem = () => {
const renderSignInItems = () => {
const hoverTimeline = gsap.timeline();
const hoveredColor = '#404040';
const normalColor = '#707070';
return (
<Container
style={{
padding: 0,
display: 'flex',
alignItems: 'center',
height: '40px',
marginRight: '0px',
}}
>
<div
style={{
display: 'inline-block',
width: '80%',
textAlign: isMobile ? '' : 'right',
}}
>
{signInLink()}
</div>
<div
style={{
display: 'inline-block',
width: '20%',
textAlign: 'right',
}}
>
<GithubFilled
style={{ fontSize: '30px', color: normalColor }}
onClick={() =>
window.open('https://github.com/osslab-pku/gfi-bot')
}
onMouseEnter={() => {
hoverTimeline
.pause()
.clear()
.to(iconRef.current, {
color: hoveredColor,
duration: 0.3,
})
.play();
}}
onMouseLeave={() => {
hoverTimeline
.pause()
.clear()
.to(iconRef.current, {
color: normalColor,
duration: 0.1,
})
.play();
}}
ref={iconRef}
/>
</div>
</Container>
);
};
const renderMobileSignIn = () => {
if (isMobile) {
return renderSignInItems();
}
return <></>;
};
const renderDesktopSignIn = () => {
if (!isMobile) {
return (
<Navbar.Collapse
className="justify-content-end"
style={{
fontFamily: defaultFontFamily,
maxWidth: '180px',
}}
>
{renderSignInItems()}
</Navbar.Collapse>
);
}
return <></>;
};
function MyPage() {
if (hasLogin) {
return (
<LinkContainer
to="/portal"
onClick={() => {
showAccountNav();
}}
>
<Nav.Link> Portal </Nav.Link>
</LinkContainer>
);
}
return <></>;
}
return (
<Container
style={{ marginRight: '5px', marginLeft: '5px', maxWidth: '100vw' }}
>
<LinkContainer
to="/"
onClick={() => {
hideAccountNav();
}}
>
<Navbar.Brand>
<img
alt=""
src={navLogo}
width="30"
height="30"
className="d-inline-block align-top"
/>{' '}
GFI-Bot
</Navbar.Brand>
</LinkContainer>
<Navbar.Toggle />
<Navbar.Collapse>
<Nav>
{MyPage()}
<LinkContainer
to="/home"
onClick={() => {
hideAccountNav();
}}
>
<Nav.Link> About Us </Nav.Link>
</LinkContainer>
{renderMobileSignIn()}
</Nav>
</Navbar.Collapse>
{renderDesktopSignIn()}
</Container>
);
};
// Explain:
// The 'expand' property of React-bootstrap Navbar turn out to be effective (equals to 'false') even when set to 'true' or ''
// so temporarily using two functions to render navbar responsively
const isDev = process.env.REACT_APP_ENV === 'development';
const renderDesktopNavbar = () => {
return (
<div className="flex-col sticky-top">
<Navbar bg="light" sticky="top">
{renderNavItem(false)}
</Navbar>
{isDev && <GFIDevController />}
<GFIGlobalProgressBar />
</div>
);
};
const renderMobileNavbar = () => {
return (
<>
<Navbar bg="light" sticky="top" expand="false">
{renderNavItem(true)}
</Navbar>
{isDev && <GFIDevController />}
<GFIGlobalProgressBar />
</>
);
};
const render = () => {
if (!isMobile) {
return renderDesktopNavbar();
}
return renderMobileNavbar();
};
const shouldShowAccountNav = useSelector((state) => {
if (
'accountNavStateReducer' in state &&
'show' in state.accountNavStateReducer
)
return state.accountNavStateReducer.show;
return false;
});
return (
<>
{render()}
{shouldShowAccountNav && <GFIPortalPageNav id="portal-page-nav" />}
</>
);
}
function GFIGlobalProgressBar() {
const ref = useRef(null);
const hidden = useSelector((state) => {
if (
'globalProgressBarReducer' in state &&
'hidden' in state.globalProgressBarReducer
) {
if (state.globalProgressBarReducer.hidden) {
return 'gfi-hidden-with-space';
}
}
return '';
});
return (
<ProgressBar
ref={ref}
className={`progress-bar-thin ${hidden} sticky-top transition-01`}
animated
now={100}
/>
);
}

View File

@ -1,38 +0,0 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@ -1,32 +0,0 @@
// import React, { createContext, useContext, useEffect, useState } from 'react';
// import webSocket from 'socket.io-client';
// import { WEBSOCKET_URL } from '../../api/api';
//
// const gfiQueryProcessContext = createContext({});
//
// export const GFIQueryProcessContextProvider: React.FC<{
// children: React.ReactNode;
// }> = ({ children }) => {
// const [ws, setWs] = useState(webSocket(WEBSOCKET_URL));
// const [succeedQueryList, setSucceedQueryList] = useState<any[]>([]);
// useEffect(() => {
// ws.on('socket_connected', (msg) => {
// console.log(msg);
// });
//
// ws.on('gfi_query_succeed', (msg: { data: any }) => {
// console.log(msg);
// setSucceedQueryList([...succeedQueryList, msg.data]);
// });
// }, []);
//
// return (
// <gfiQueryProcessContext.Provider value={succeedQueryList}>
// {children}
// </gfiQueryProcessContext.Provider>
// );
// };
//
// export const useSucceedQuery = () => {
// return useContext(gfiQueryProcessContext);
// };

View File

@ -1,70 +0,0 @@
import React, {
createContext,
RefObject,
useContext,
useEffect,
useRef,
useState,
} from 'react';
const windowContext = createContext<{ width: number; height: number }>(
{} as any
);
export const WindowContextProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [width, setWidth] = useState<number>(window.innerWidth);
const [height, setHeight] = useState<number>(window.innerHeight);
const resizeHandler = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
};
useEffect(() => {
window.addEventListener('resize', resizeHandler);
return () => {
window.removeEventListener('resize', resizeHandler);
};
}, []);
return (
<windowContext.Provider value={{ width, height }}>
{children}
</windowContext.Provider>
);
};
export const useWindowSize = () => {
const { width, height } = useContext(windowContext);
return { width, height };
};
export const mobileThreshold = 700;
export const useIsMobile = () => {
const { width } = useContext(windowContext);
return width <= mobileThreshold;
};
const GlobalRefContext = createContext<{ ref: RefObject<HTMLDivElement> }>(
{} as any
);
export const GlobalRefProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const ref = useRef<HTMLDivElement>(null);
return (
<GlobalRefContext.Provider value={{ ref }}>
<div ref={ref}>{children}</div>
</GlobalRefContext.Provider>
);
};
export const useGlobalRef = () => {
const { ref } = useContext(GlobalRefContext);
return ref;
};

View File

@ -1,98 +0,0 @@
import React from 'react';
import { Container, Row, Col, Button } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../style/gfiStyle.css';
import { defaultFontFamily } from '../utils';
import { Link } from 'react-router-dom';
// TODO: @MSKYurina
// Design and Animation
const SELF_INTRO =
'The introduction of the bot is submitted to FSE 2022 Demo --- GFI-Bot: Automated Good First Issue Recommendation on GitHub';
const GFIBOT_INTRO =
"The embedded ML approach is introduced in the following paper: W. Xiao, H. He, W. Xu, X. Tan, J. Dong, M. Zhou. Recommending Good First Issues in GitHub OSS Projects. Accepted at ICSE'2022.";
export const DescriptionPage: React.FC = () => {
const welcomeMsg = 'GFI-BOT WebApp';
const description =
'ML-powered 🤖 for finding and labeling Good First Issues in your GitHub project!';
return (
<div className="scrollbar-hidden">
<Container
className="flex-col flex-center"
style={{
marginTop: '9%',
}}
>
<Row style={{ height: '25%', flexDirection: 'column-reverse' }}>
<Col sm={12}>
<Row style={{ marginTop: 'auto' }}>
<Col
style={{
textAlign: 'center',
fontWeight: 'bolder',
fontSize: 'xx-large',
}}
>
{welcomeMsg}
</Col>
</Row>
</Col>
</Row>
<Row style={{ marginTop: '20px' }}>
<Col style={{ textAlign: 'center', maxWidth: '400px' }}>
{description}
</Col>
</Row>
<Row style={{ margin: '35px' }}>
<Col className="flex-col flex-center description-container">
<div style={{ maxWidth: '600px' }}>{SELF_INTRO}</div>
<div style={{ maxWidth: '600px' }}>{GFIBOT_INTRO}</div>
<Link to="/">
<Button variant="outline-primary" style={{ marginTop: '2rem' }}>
{' '}
Get Started{' '}
</Button>
</Link>
</Col>
</Row>
</Container>
</div>
);
};
interface DescriptionPageProps {
title?: string;
content?: string;
}
function Description(props: DescriptionPageProps) {
return (
<Container>
<Row
style={{
fontFamily: defaultFontFamily,
fontSize: '24px',
color: '#6d6d6d',
fontWeight: '300',
}}
>
<Col>{props.title}</Col>
</Row>
<Row
style={{
fontFamily: defaultFontFamily,
fontSize: '17px',
fontWeight: '400',
marginTop: '10px',
}}
>
<Col>{props.content}</Col>
</Row>
</Container>
);
}

View File

@ -1,107 +0,0 @@
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { Container, ToastContainer, Toast, Button } from 'react-bootstrap';
import '../../style/gfiStyle.css';
import { UserOutlined } from '@ant-design/icons';
import { defaultFontFamily } from '../../utils';
import { createLoginAction } from '../../storage/reducers';
export function LoginRedirect(props: any) {
const dispatch = useDispatch();
const history = useHistory();
useEffect(() => {
const params = new URLSearchParams(props.location.search);
const loginName = params.get('github_login');
const userName = params.get('github_name');
const userUrl = params.get('github_avatar_url');
const userId = params.get('github_id');
const userToken = params.get('github_token');
if (userId && loginName && userName && userToken && userUrl) {
dispatch(
createLoginAction(userId, loginName, userName, userToken, userUrl)
);
history.push('/', { justLogin: true });
}
}, []);
return (
<Container
style={{
textAlign: 'center',
fontFamily: defaultFontFamily,
}}
>
Redirecting...
</Container>
);
}
export interface GFINotiToastProps {
userName: string;
userAvatarUrl?: string;
onClose: () => void;
context?: string;
buttonContext?: string;
onClick?: () => void;
show: boolean;
}
export function GFINotiToast(props: GFINotiToastProps) {
const {
userName,
userAvatarUrl,
onClose,
show,
context,
buttonContext,
onClick,
} = props;
return (
<ToastContainer
position="top-end"
style={{
zIndex: '9999',
}}
>
<Toast show={show} animation onClose={() => onClose()}>
<Toast.Header>
{userAvatarUrl ? (
<img
src={userAvatarUrl}
alt=""
className="rounded me-2"
style={{ width: '30px' }}
/>
) : (
<UserOutlined style={{ fontSize: '30px' }} />
)}
<strong className="me-auto" style={{ marginLeft: '5px' }}>
{' '}
Hello, {userName}{' '}
</strong>
</Toast.Header>
<Toast.Body>{context || 'Welcome to GFI-Bot'}</Toast.Body>
{buttonContext ? (
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
paddingRight: '1rem',
paddingBottom: '0.5rem',
}}
>
<Button variant="outline-primary" size="sm" onClick={onClick}>
{buttonContext}
</Button>
</div>
) : (
<></>
)}
</Toast>
</ToastContainer>
);
}

View File

@ -1,17 +0,0 @@
import React, { forwardRef, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
export const GFIAlphaWarning = () => (
<div className="kanban wrapper">
<div
className="gfi-wrapper tags"
style={{ backgroundColor: 'rgba(255, 91, 91, 0.2)' }}
>
<div style={{ marginBottom: '0.3rem' }}>Warning</div>
<div className="tags wrapper" style={{ marginBottom: '0.1rem' }}>
GFI-Bot is undergoing rapid development and still highly unstable. It is
not recommended to use it in production.
</div>
</div>
</div>
);

View File

@ -1,756 +0,0 @@
import React, {
createContext,
ForwardedRef,
forwardRef,
MouseEventHandler,
ReactElement,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'react';
import { Row, Col } from 'react-bootstrap';
import { useDispatch, useSelector } from 'react-redux';
import remarkGfm from 'remark-gfm';
import remarkGemoji from 'remark-gemoji';
import ReactMarkdown from 'react-markdown';
import '../../style/gfiStyle.css';
import {
GFIOverlay,
GFIPagination,
GFISimplePagination,
} from '../GFIComponents';
import {
GFIInfo,
RepoBrief,
RepoDetail,
GFITrainingSummary,
} from '../../model/api';
import { getIssueByRepoInfo } from '../../api/githubApi';
import { GFIRootReducers } from '../../storage/configureStorage';
import { createPopoverAction } from '../../storage/reducers';
import {
getGFIByRepoName,
getGFINum,
getRepoDetailedInfo,
getTrainingSummary,
} from '../../api/api';
import { useIsMobile } from '../app/windowContext';
import { RepoGraphContainer } from '../repositories/repoDataDemonstrator';
import { checkHasUndefinedProperty, checkIsNumber } from '../../utils';
export interface RepoShouldDisplayPopoverState {
shouldDisplayPopover?: boolean;
popoverComponent?: ReactElement;
popoverID?: string;
}
export interface GFIRepoBasicProp {
repoInfo: RepoBrief;
}
export interface GFIRepoDisplayView extends GFIRepoBasicProp {
tags?: string[];
panels?: ReactElement[];
style?: any;
className?: string;
}
const RepoDisplayOverlayIDContext = createContext<string>({} as any);
const RepoDisplayOverlayIDProvider: React.FC<{
children: React.ReactNode;
id: string;
}> = ({ children, id }) => {
return (
<RepoDisplayOverlayIDContext.Provider value={id}>
{children}
</RepoDisplayOverlayIDContext.Provider>
);
};
const useOverlayID = () => {
return useContext(RepoDisplayOverlayIDContext);
};
export const GFIRepoDisplayView = forwardRef(
(props: GFIRepoDisplayView, ref: ForwardedRef<HTMLDivElement>) => {
const { repoInfo, tags, panels, style, className } = props;
const [selectedTag, setSelectedTag] = useState<number>(0);
const [selectedTagList, setSelectedTagList] = useState<boolean[]>();
// Not good, but 'position: fixed' in child components doesn't work here
// wondering why...
const overlayItem = useSelector<
GFIRootReducers,
RepoShouldDisplayPopoverState | undefined
>((state) => {
return state.mainPopoverReducer;
});
const overlayRef = useRef<HTMLDivElement>(null);
const dispatch = useDispatch();
const overlayID = `main-overlay-${repoInfo.name}-${repoInfo.owner}`;
const isMobile = useIsMobile();
useEffect(() => {
if (tags) {
setSelectedTagList(
tags.map((_, i) => {
return !i;
})
);
}
}, []);
function Info() {
if (panels && tags && panels.length === tags.length) {
return panels.map((node, i) => {
return (
<div
className="flex-col"
style={i === selectedTag ? {} : { display: 'none' }}
key={i}
>
<RepoDisplayOverlayIDProvider id={overlayID}>
{node}
</RepoDisplayOverlayIDProvider>
</div>
);
});
}
return <></>;
}
function Title() {
const ProjectTags = () => {
return repoInfo.topics?.map((item, i) => {
return (
<div className="repo-display-info-repo-tag" key={i}>
{item}
</div>
);
});
};
return (
<div className="flex-col justify-content-center repo-display-info flex-wrap">
<div className="repo-display-info-title flex-row">
<p> {repoInfo.owner} </p>
<p> {' / '} </p>
<p> {repoInfo.name} </p>
</div>
<div> {repoInfo?.description} </div>
<div className="flex-row flex-wrap"> {ProjectTags()} </div>
</div>
);
}
function Tags() {
if (tags && selectedTagList?.length === tags.length) {
return tags.map((item, i) => {
return (
<PanelTag
name={item}
id={i}
key={i}
onClick={(id) => {
if (id !== selectedTag) {
setSelectedTag(id);
setSelectedTagList(
tags?.map((_, i) => {
return i === id;
})
);
}
}}
selected={selectedTagList[i]}
/>
);
});
}
return <></>;
}
const renderOverlay = () => {
let hidden = !(overlayItem && overlayItem.shouldDisplayPopover);
if (overlayItem?.popoverID !== overlayID) {
hidden = true;
}
return (
<GFIOverlay
id={overlayID}
direction="right"
width={isMobile ? '90%' : '60%'}
hidden={hidden}
ref={overlayRef}
callback={() => {
dispatch(createPopoverAction());
}}
animation
>
{overlayItem?.popoverComponent}
</GFIOverlay>
);
};
return (
<div className="repo-display-view-container" ref={ref}>
{renderOverlay()}
<div style={style} className={`flex-col repo-display ${className}`}>
<div className="flex-row repo-display-info-nav">{Tags()}</div>
<Row>
<Col>
{Title()}
{Info()}
</Col>
</Row>
</div>
</div>
);
}
);
GFIRepoDisplayView.displayName = 'GFIRepoDisplayView';
function PanelTag(props: {
name: string;
id: number;
selected: boolean;
onClick: (id: number) => void;
}) {
const { name, id, selected, onClick } = props;
const selectedClass = selected ? 'selected' : '';
const first = id === 0 ? 'first' : '';
const className =
'repo-display-info-panel-tag flex-row align-items-stretch align-center' +
` ${selectedClass}` +
` ${first}`;
return (
<div className={className}>
<div
className={
'repo-display-info-tag flex-row flex-center hoverable' +
` ${selectedClass}`
}
onClick={() => {
onClick(id);
}}
>
{' '}
<p className="no-select"> {name} </p>
</div>
</div>
);
}
export interface GFIIssueMonitor extends GFIRepoBasicProp {
trainingSummary?: GFITrainingSummary;
paging?: number;
}
export const GFIIssueMonitor = forwardRef((props: GFIIssueMonitor, ref) => {
const { repoInfo, trainingSummary, paging } = props;
const [displayIssueList, setDisplayIssueList] = useState<
GFIInfo[] | undefined
>();
const maxPageItems = paging || 6;
const [shouldDisplayPagination, setShouldDisplayPagination] = useState(false);
const [currentPageIdx, setCurrentPageIdx] = useState(1);
const [pageInput, setPageInput] = useState<string>();
const [isLoading, setIsLoading] = useState(true);
const [gfiNum, setGfiNum] = useState(0);
const onUpdate = async () => {
if (!displayIssueList || !gfiNum) {
// not loading
const num = await getGFINum(repoInfo.name, repoInfo.owner);
setGfiNum(num);
setShouldDisplayPagination(num > maxPageItems);
}
const pageLowerBound = (currentPageIdx - 1) * maxPageItems;
const res = await getGFIByRepoName(
repoInfo.name,
repoInfo.owner,
pageLowerBound,
maxPageItems
);
if (Array.isArray(res) && res.length) {
setDisplayIssueList(res);
} else {
setDisplayIssueList(undefined);
setIsLoading(false);
}
setIsLoading(false);
};
useEffect(() => {
onUpdate();
}, [currentPageIdx]);
const render = () => {
// const pageLowerBound = (currentPageIdx - 1) * maxPageItems;
// const pageUpperBound = currentPageIdx * maxPageItems;
const randomId = Math.random() * 1000;
return displayIssueList?.map((issue, i) => (
<GFIIssueListItem
repoInfo={repoInfo}
issue={issue}
key={`gfi-issue-${repoInfo.name}-${issue}-${i}-${randomId}`}
useTips={!(i % maxPageItems)}
trainingSummary={trainingSummary}
/>
));
};
const onPageBtnClicked = useCallback(() => {
if (pageInput && checkIsNumber(pageInput) && displayIssueList) {
const page = parseInt(pageInput, 10);
if (page > 0 && page <= Math.ceil(gfiNum / maxPageItems)) {
setCurrentPageIdx(parseInt(pageInput, 10));
}
}
}, [displayIssueList, maxPageItems, pageInput]);
return (
<div className="flex-col">
{render()}
{displayIssueList ? (
<></>
) : (
<div className="gfi-issue-monitor-empty">
{isLoading
? 'Loading GFIs...'
: 'Currently no GFIs for this repository.'}
</div>
)}
{shouldDisplayPagination && displayIssueList && (
<div
style={{
marginRight: '0.7rem',
marginLeft: '0.7rem',
marginBottom: '0.3rem',
}}
>
<GFIPagination
maxPagingCount={3}
pageNums={Math.ceil(gfiNum / maxPageItems)}
pageIdx={currentPageIdx}
toPage={(page) => setCurrentPageIdx(page)}
needInputArea
onFormInput={(target) => {
const t = target as HTMLTextAreaElement;
setPageInput(t.value);
}}
onPageBtnClicked={onPageBtnClicked}
/>
</div>
)}
</div>
);
});
GFIIssueMonitor.displayName = 'GFIIssueMonitor';
export interface GFIIssueListItem extends GFIRepoBasicProp {
issue: GFIInfo;
useTips: boolean;
trainingSummary?: GFITrainingSummary;
}
type IssueState = 'closed' | 'open' | 'resolved';
interface IssueDisplayData {
issueId: number;
title: string;
body?: string;
state: IssueState;
url: string;
gfi?: GFIInfo;
}
function GFIIssueListItem(props: GFIIssueListItem) {
const dispatch = useDispatch();
const overlayID = useOverlayID();
const { repoInfo, issue, useTips, trainingSummary } = props;
const [displayData, setDisplayData] = useState<IssueDisplayData>();
const updateIssue = async () => {
const res = await getIssueByRepoInfo(
repoInfo.name,
repoInfo.owner,
issue.number
);
if (res) {
let issueState: IssueState = 'open';
if (res.state === 'closed') {
issueState = 'closed';
}
if (res.active_lock_reason === 'resolved') {
issueState = 'resolved';
}
setDisplayData({
issueId: res.number,
title: res.title,
body: res.body,
state: issueState,
url: res.html_url,
gfi: issue,
});
}
};
useEffect(() => {
// use backend data first
setDisplayData({
issueId: issue.number,
title: issue.title,
state: issue.state,
url: `https://github.com/${repoInfo.owner}/${repoInfo.name}/issues/${issue.number}`,
gfi: issue,
});
// update from github later
updateIssue();
}, []);
const issueBtn = () => {
return (
<button
className={`issue-display-item-btn ${
displayData ? displayData.state : ''
}`}
>
<a href={displayData ? displayData.url : ''}>{`#${issue.number}`}</a>
</button>
);
};
const onDetailShow: MouseEventHandler<HTMLDivElement> = useCallback(
(e) => {
const callbackProp: RepoShouldDisplayPopoverState = {
shouldDisplayPopover: true,
popoverComponent: (
<IssueOverlayItem
repoInfo={repoInfo}
issueBtn={issueBtn}
displayData={displayData}
trainingSummary={trainingSummary}
/>
),
popoverID: overlayID,
};
dispatch(createPopoverAction(callbackProp));
},
[repoInfo, displayData, trainingSummary, overlayID]
);
return (
<div
className="issue-display-item flex-row align-center hoverable"
onClick={onDetailShow}
>
<div
style={{
width: '9%',
minWidth: '70px',
}}
>
{issueBtn()}
</div>
<div className="flex-row flex-wrap text-break">
{displayData ? displayData.title : ''}
</div>
{displayData && (
<div
style={{
width: '6%',
minWidth: '65px',
marginLeft: 'auto',
paddingLeft: '0.3rem',
}}
className="flex-row justify-content-center align-center"
>
<div
className={`issue-display-item-prob-tag ${
useTips ? 'tool-tips' : ''
}`}
>
{`${(issue.probability * 100).toFixed(
issue.probability > 0.99995 ? 1 : 2
)}%`}
{useTips && (
<div className="tool-tips-text-top flex-row align-center justify-content-center">
GFI Probability
</div>
)}
</div>
</div>
)}
</div>
);
}
interface IssueOverlayItem extends GFIRepoBasicProp {
issueBtn: () => ReactElement;
displayData?: IssueDisplayData;
trainingSummary?: GFITrainingSummary;
}
function IssueOverlayItem(props: IssueOverlayItem) {
const { repoInfo, issueBtn, displayData, trainingSummary } = props;
const isMobile = useIsMobile();
const flexDirection = isMobile ? 'col' : 'row';
const probability = displayData
? (displayData.gfi.probability * 100).toFixed(2)
: 0;
const simpleTrainDataProps: SimpleTrainInfoTagProp[] | [] = trainingSummary
? [
{
title: 'Issues Resolved',
data: trainingSummary.n_resolved_issues,
},
{
title: 'Resolved By Newcomers',
data: trainingSummary.n_newcomer_resolved,
},
{
title: 'AUC',
data: trainingSummary.auc
? parseFloat(trainingSummary.auc.toFixed(2))
: 0,
},
{
title: 'ACC',
data: trainingSummary.auc
? parseFloat(trainingSummary.auc.toFixed(2))
: 0,
},
]
: [];
/* eslint-disable react/no-children-prop */
return (
<div
className="flex-col repo-overlay-item"
style={{
margin: '1rem 1.5rem',
}}
>
<div className="gfi-overlay-info-title">
<div className={`repo-display-info-title flex-${flexDirection}`}>
<p> {repoInfo.owner} </p>
{!isMobile && <p> {' / '} </p>}
<p style={{ margin: '0' }}> {repoInfo.name} </p>
</div>
<div style={{ fontFamily: 'var(--default-font-family)' }}>
{repoInfo?.description}
</div>
<div
className="flex-row align-center justify-content-start flex-wrap"
style={{ marginBottom: '0.2rem' }}
>
{repoInfo.topics?.map((item, i) => (
<div className="repo-display-info-repo-tag" key={i}>
{item}
</div>
))}
</div>
{simpleTrainDataProps && (
<div className="flex-row issue-demo-data-container-overlay">
{simpleTrainDataProps.map((prop, i) => (
<SimpleTrainInfoTag title={prop.title} data={prop.data} key={i} />
))}
</div>
)}
</div>
<div
className="flex-row align-center"
style={{
margin: '1rem 0',
}}
>
{issueBtn()}
<div
style={{
fontWeight: 'bold',
fontSize: 'larger',
marginLeft: '0.7rem',
}}
>
{displayData?.title}
</div>
<div className="gfi-issue-overlay-item-tag">
Probability {`${probability}%`}
</div>
</div>
{displayData && displayData.body && (
<ReactMarkdown
children={displayData.body}
remarkPlugins={[remarkGfm, remarkGemoji]}
className="markdown markdown-gfi-overlay"
/>
)}
</div>
);
/* eslint-enable react/no-children-prop */
}
export interface GFIRepoStaticsDemonstrator extends GFIRepoBasicProp {
trainingSummary?: GFITrainingSummary;
paging?: boolean;
}
export const GFIRepoStaticsDemonstrator = forwardRef(
(props: GFIRepoStaticsDemonstrator, ref) => {
const { repoInfo, trainingSummary, paging } = props;
const usePaging = !(paging === false && paging !== undefined);
const [displayInfo, setDisplayInfo] = useState<RepoDetail>();
const simpleTrainDataProps: SimpleTrainInfoTagProp[] | [] = trainingSummary
? [
{
title: 'Issues Resolved',
data: trainingSummary.n_resolved_issues,
},
{
title: 'Resolved By Newcomers',
data: trainingSummary.n_newcomer_resolved,
},
{
title: 'AUC',
data: trainingSummary.auc
? parseFloat(trainingSummary.auc.toFixed(2))
: 0,
},
{
title: 'ACC',
data: trainingSummary.auc
? parseFloat(trainingSummary.accuracy.toFixed(2))
: 0,
},
]
: [];
type DataTag =
| 'monthly_stars'
| 'monthly_commits'
| 'monthly_issues'
| 'monthly_pulls';
type DisplayData = { [key in DataTag]?: any[] };
const [displayData, setDisplayData] = useState<DisplayData>();
const dataCategories = [
'monthly_stars',
'monthly_commits',
'monthly_issues',
'monthly_pulls',
];
const dataTitle = [
'Monthly Stars',
'Monthly Commits',
'Monthly Issues',
'Monthly Pulls',
];
const [title, setTitle] = useState<string[]>();
const [selectedIdx, setSelectedIdx] = useState(0);
useEffect(() => {
getRepoDetailedInfo(repoInfo.name, repoInfo.owner).then((res) => {
const result = res as RepoDetail;
setDisplayInfo(result);
});
}, []);
useEffect(() => {
if (displayInfo) {
const info: DisplayData = {};
let key: keyof typeof displayInfo;
const titles = [];
for (key in displayInfo) {
const displayInfoItem = displayInfo[key] as any[];
if (dataCategories.includes(key) && displayInfoItem.length) {
info[key as DataTag] = displayInfoItem;
titles.push(dataTitle[dataCategories.indexOf(key)]);
}
}
setTitle(titles);
setDisplayData(info);
}
}, [displayInfo]);
const RenderGraphs = () => {
let availableIdx = -1;
return dataCategories.map((item, idx) => {
if (displayData && title && Object.keys(displayData).includes(item)) {
availableIdx += 1;
return (
<div
style={
availableIdx === selectedIdx || !usePaging
? {}
: { display: 'none' }
}
key={idx}
>
<RepoGraphContainer
title={dataTitle[idx]}
info={displayData[item as DataTag]}
/>
</div>
);
}
return <></>;
});
};
return (
<>
{simpleTrainDataProps && (
<div className="flex-row issue-demo-data-container">
{simpleTrainDataProps.map((prop, i) => (
<SimpleTrainInfoTag title={prop.title} data={prop.data} key={i} />
))}
</div>
)}
<div className="issue-demo-container">
{RenderGraphs()}
{usePaging && (
<div className="flex-row page-footer-container">
{displayData && Object.keys(displayData).length && (
<GFISimplePagination
nums={Object.keys(displayData).length}
onClick={(idx) => {
setSelectedIdx(idx);
}}
title={title}
/>
)}
</div>
)}
</div>
</>
);
}
);
GFIRepoStaticsDemonstrator.displayName = 'GFIRepoStaticsDemonstrator';
interface SimpleTrainInfoTagProp {
title: string;
data: number;
}
function SimpleTrainInfoTag(props: SimpleTrainInfoTagProp) {
const { title, data } = props;
return (
<div
className="simple-train-info-tag flex-row align-items-stretch"
style={{ marginRight: '0.4rem' }}
>
<div>{title}</div>
<div>{data}</div>
</div>
);
}

View File

@ -1,457 +0,0 @@
import React, { ForwardedRef, forwardRef, useEffect, useState } from 'react';
import type { GFITrainingSummary } from '../../model/api';
import { getGFINum, getTrainingSummary } from '../../api/api';
import '../../style/gfiStyle.css';
import { Group } from '@visx/group';
import { scaleLinear } from '@visx/scale';
import { Bar, LinePath } from '@visx/shape';
import { curveNatural } from '@visx/curve';
import {
GradientLightgreenGreen,
GradientOrangeRed,
GradientTealBlue,
GradientPurpleTeal,
GradientPinkBlue,
} from '@visx/gradient';
export interface GFITrainingSummaryDisplayView {}
interface TrainingSummary {
issueNumTest: number;
issueNumTrain: number;
repoNum: number;
avgAuc: number;
avgAcc: number;
issueResolved: number;
issueResolvedByNewcomers: number;
}
type ActivityTagType = '7Days' | '1Month' | '3Months' | '1Year' | 'Older';
const ActivityTags: ActivityTagType[] = [
'7Days',
'1Month',
'3Months',
'1Year',
'Older',
];
interface RepoActivity {
time: ActivityTagType;
num: number;
}
const getActivityTime: (timeStr: string) => ActivityTagType[] = (
timeStr: string
) => {
const date = new Date(timeStr).getTime();
const now = new Date().getTime();
const day = 24 * 3600 * 1000;
const week = 7 * day;
const month = 31 * day;
const year = 365 * day;
if (now - week <= date) {
return ActivityTags.slice(0);
}
if (now - month <= date) {
return ActivityTags.slice(1);
}
if (now - 3 * month <= date) {
return ActivityTags.slice(2);
}
if (now - year <= day) {
return ActivityTags.slice(3);
}
return ActivityTags.slice(4);
};
export const GFITrainingSummaryDisplayView = forwardRef(
(props, ref: ForwardedRef<HTMLDivElement>) => {
const [originTrainingSummary, setOriginTrainingSummary] =
useState<GFITrainingSummary[]>();
const [modelTrainingSummary, setModelTrainingSummary] = useState<GFITrainingSummary>();
const fullChartDefaultHeight = 75;
const fullChartDefaultHorizontalMargin = 8;
const [fullChartHeight, setFullChartHeight] = useState(
fullChartDefaultHeight
);
const [gfiNum, setGfiNum] = useState(0);
const [fullChartWidth, setFullChartWidth] = useState(0);
const [halfChartWidth, setHalfChartWidth] = useState(0);
const [displayedSummary, setDisplayedSummary] = useState<TrainingSummary>();
const [repoActivitySummary, setRepoActivitySummary] = useState<
RepoActivity[]
>(
ActivityTags.map((item) => ({
time: item,
num: 0,
}))
);
const indexMapping: { [key in ActivityTagType]: number } = {
'7Days': 0,
'1Month': 1,
'3Months': 2,
'1Year': 3,
Older: 4,
};
useEffect(() => {
getTrainingSummary().then((res) => {
if (res) {
setOriginTrainingSummary(res);
}
});
getGFINum().then((res) => {
if (res) {
setGfiNum(res);
}
});
getTrainingSummary("","").then((res) => {
if (res && res.length > 0) {
setModelTrainingSummary(res[0]);
}
});
}, []);
useEffect(() => {
if (originTrainingSummary && originTrainingSummary.length) {
const repoNum = originTrainingSummary.length;
let issueNumTest = 0;
let issueNumTrain = 0;
let totalAcc = 0;
let totalAuc = 0;
let resolved = 0;
let resolvedByNewcomers = 0;
const repoActivity: RepoActivity[] = ActivityTags.map((item) => ({
time: item,
num: 0,
}));
for (const summary of originTrainingSummary) {
issueNumTest += summary.issues_test;
issueNumTrain += summary.issues_train;
totalAcc += summary.accuracy * summary.issues_train;
totalAuc += summary.auc * summary.issues_train;
resolved += summary.n_resolved_issues;
resolvedByNewcomers += summary.n_newcomer_resolved;
getActivityTime(summary.last_updated).forEach((value) => {
repoActivity[indexMapping[value]].num += 1;
});
}
setRepoActivitySummary(repoActivity);
setDisplayedSummary({
issueNumTest,
issueNumTrain,
repoNum,
avgAcc: modelTrainingSummary ? modelTrainingSummary.accuracy : totalAcc / issueNumTrain,
avgAuc: modelTrainingSummary ? modelTrainingSummary.auc : totalAuc / issueNumTrain,
issueResolved: resolved,
issueResolvedByNewcomers: resolvedByNewcomers,
});
}
}, [originTrainingSummary]);
return (
<>
{displayedSummary && (
<div
className="gfi-training-summary-container flex-col no-select"
ref={(el) => {
if (el !== null) {
setFullChartWidth(
el.clientWidth - 2 * fullChartDefaultHorizontalMargin
);
setHalfChartWidth(
(el.clientWidth - 3 * fullChartDefaultHorizontalMargin) / 2.0
);
}
}}
>
<div
className="flex-row justify-content-between align-center flex-wrap"
style={{
marginLeft: `${fullChartDefaultHorizontalMargin}px`,
marginRight: `${fullChartDefaultHorizontalMargin}px`,
marginBottom: '0.5rem',
}}
>
<div className="flex-row gfi-training-nums-displayer-item">
<NumInfoDisplayer
width={halfChartWidth}
height={60}
gradient={
(
<GradientOrangeRed id="g-red-info" />
) as unknown as Element
}
gradientId="g-red-info"
num={displayedSummary.repoNum}
title="Repositories"
/>
</div>
<div className="flex-row gfi-training-nums-displayer-item">
<NumInfoDisplayer
width={halfChartWidth}
height={60}
gradient={
(
<GradientLightgreenGreen id="g-green-info" />
) as unknown as Element
}
gradientId="g-green-info"
num={
displayedSummary.issueNumTest +
displayedSummary.issueNumTrain
}
title="Issues"
/>
</div>
<div className="flex-row gfi-training-nums-displayer-item">
<NumInfoDisplayer
width={halfChartWidth}
height={60}
gradient={
(
<GradientPurpleTeal id="g-purple-info" />
) as unknown as Element
}
gradientId="g-purple-info"
num={gfiNum}
title="Good First Issues"
/>
</div>
<div className="flex-row gfi-training-nums-displayer-item">
<NumInfoDisplayer
width={halfChartWidth}
height={60}
gradient={
(
<GradientPinkBlue id="g-pink-blue-teal-info" />
) as unknown as Element
}
gradientId="g-pink-blue-teal-info"
num={displayedSummary.issueResolved}
title="Issues Resolved"
/>
</div>
</div>
<div className="flex-row justify-content-center">
<AucAccBarDisplayer
width={fullChartWidth}
height={fullChartHeight}
data={[
{ name: 'AUC', value: displayedSummary.avgAuc },
{ name: 'ACC', value: displayedSummary.avgAcc },
]}
/>
</div>
<div
className="flex-row justify-content-center"
style={{ marginTop: '0.5rem' }}
>
<ActivityDisplayer
width={fullChartWidth}
height={120}
data={repoActivitySummary}
/>
</div>
</div>
)}
</>
);
}
);
GFITrainingSummaryDisplayView.displayName = 'GFITrainingSummaryDisplayView';
function NumInfoDisplayer(props: {
width: number;
height: number;
gradient: Element;
gradientId: string;
num: number;
title: string;
}) {
const { width, height, gradient, gradientId, num, title } = props;
// @ts-nocheck
return (
<>
<svg
width={width}
height={height}
className="flex-row justify-content-center align-center"
>
{gradient}
<rect
width={width}
height={height}
fill={`url(#${gradientId})`}
rx={7}
ry={7}
/>
<text
x="50%"
y="40%"
dominantBaseline="middle"
textAnchor="middle"
className="gfi-training-num-info-num"
>
{num}
</text>
<text x="50%" y="75%" className="gfi-training-num-info-title">
{title}
</text>
</svg>
</>
);
}
function AucAccBarDisplayer(props: {
width: number;
height: number;
data: { name: 'AUC' | 'ACC'; value: number }[];
}) {
const { width, height, data } = props;
const barWidth = 25;
const paddingTop = 33;
const margin = (height - barWidth * data.length) / (data.length + 1.0);
const yScale = scaleLinear<number>({
domain: [0, 1],
range: [0, width],
nice: true,
});
return (
<svg width={width} height={height + paddingTop}>
<GradientTealBlue id="teal" />
<rect
width={width}
height={height + paddingTop}
fill="url(#teal)"
rx={7}
ry={7}
/>
<text className="gfi-training-auc-displayer-label-title" y={26} x={12}>
Average AUC & ACC
</text>
<Group>
{data.map((d, idx) => {
return (
<>
<Bar
x={10}
y={margin + idx * (barWidth + margin) + paddingTop}
width={yScale(d.value)}
height={barWidth}
fill="rgba(23, 233, 217, .5)"
rx={10}
ry={10}
/>
<text
x={20}
y={margin + idx * (barWidth + margin) + 14 + paddingTop}
className="gfi-training-auc-displayer-label"
dominantBaseline="middle"
>
{d.name}
</text>
<text
x={yScale(d.value) - 35}
y={margin + idx * (barWidth + margin) + 14 + paddingTop}
className="gfi-training-auc-displayer-label-val"
dominantBaseline="middle"
>
{Math.round(d.value * 100) / 100}
</text>
</>
);
})}
</Group>
</svg>
);
}
function ActivityDisplayer(props: {
width: number;
height: number;
data: RepoActivity[];
}) {
const { width, height, data } = props;
const getMaxY = () => {
let maxNum = 0;
for (const d of data) {
maxNum = Math.max(maxNum, d.num);
}
return maxNum;
};
const graphWidth = width * 0.9;
const graphHeight = height * 0.6;
const yScale = scaleLinear<number>({
domain: [0, getMaxY()],
range: [graphHeight, 0],
});
const marginX = (width - graphWidth * 0.8) / 2.0;
const marginY = (height - graphHeight) / 2.0 - 4;
/* eslint-disable react/jsx-key */
return (
<svg width={width} height={height}>
<g className="flex-row align-center justify-content-center">
<GradientLightgreenGreen id="gradient-act-green" />
<rect
width={width}
height={height}
fill="url(#gradient-act-green)"
rx={7}
ry={7}
/>
<text
className="gfi-training-activity-displayer-title"
dominantBaseline="middle"
textAnchor="end"
x="90%"
y="67%"
>
Repo Last Activities
</text>
<Group>
{data.map((d, idx) => (
<circle
r={3}
cx={(graphWidth / data.length) * idx + marginX}
cy={yScale(d.num) + marginY}
fill="white"
/>
))}
<LinePath<RepoActivity>
curve={curveNatural}
data={data}
x={(d, i) => (graphWidth / data.length) * i + marginX}
y={(d) => yScale(d.num) + marginY}
stroke="white"
strokeWidth={1.5}
strokeOpacity={1}
/>
{data.map((d, idx) => (
<text
x={(graphWidth / data.length) * idx + marginX}
y={yScale(0) + marginY + 14}
fill="white"
textAnchor="middle"
dominantBaseline="middle"
className="gfi-training-activity-displayer-label"
>
{' '}
{d.time}{' '}
</text>
))}
</Group>
</g>
</svg>
);
/* eslint-enable react/jsx-key */
}

View File

@ -1,208 +0,0 @@
import React, {
forwardRef,
MouseEventHandler,
useEffect,
useState,
} from 'react';
import { Container, Col, Form, Button, Dropdown } from 'react-bootstrap';
import { SearchOutlined } from '@ant-design/icons';
import './mainPage.css';
import '../../style/gfiStyle.css';
import { useSelector } from 'react-redux';
import { getLanguageTags } from '../../api/api';
import { GFIRootReducers } from '../../storage/configureStorage';
import { MainPageLangTagSelectedState } from '../../storage/reducers';
export type GFIRepoSearchingFilterType =
| 'Alphabetical'
| 'Number of Stars'
| 'Issue Resolution Time'
| '% of Issues Resolved by New Contributors'
| '# of Predicted Good First Issues';
export const GFI_REPO_FILTER_NONE: GFIRepoSearchingFilterType & string = 'Alphabetical';
export interface GFIMainPageHeader {
onSearch?: (s: string) => void;
onFilterSelect?: (s: GFIRepoSearchingFilterType) => void;
onTagSelected?: (s: string) => void;
}
export const GFIMainPageHeader = forwardRef((props: GFIMainPageHeader, ref) => {
const { onSearch, onFilterSelect, onTagSelected } = props;
const [search, setSearch] = useState<string | undefined>();
const [filterSelected, setFilterSelected] =
useState<GFIRepoSearchingFilterType>('Alphabetical');
const sortedBy: GFIRepoSearchingFilterType[] = [
'Alphabetical',
'Number of Stars',
'Issue Resolution Time',
'% of Issues Resolved by New Contributors',
'# of Predicted Good First Issues',
];
const renderDropDownItem = (
onClick: MouseEventHandler<HTMLElement>,
title: string
) => {
return (
<Dropdown.Item
onClick={onClick}
style={{
fontSize: 'small',
}}
key={title}
>
{title}
</Dropdown.Item>
);
};
const renderDefaultDropDownItems = () => {
return sortedBy.map((value, index, array) => {
return renderDropDownItem((e) => {
setFilterSelected(value);
if (onFilterSelect) {
onFilterSelect(value);
}
}, value as string);
});
};
const [tagArray, setTagArray] = useState<string[]>(['All']);
const [tagSelected, setTagSelected] = useState('All');
useEffect(() => {
getLanguageTags().then((res) => {
if (res) {
setTagArray(['All', ...res]);
}
});
}, []);
const globalSelectedTag = useSelector<
GFIRootReducers,
MainPageLangTagSelectedState
>((state) => {
return state.mainPageLangTagSelectedStateReducer;
});
useEffect(() => {
if (
globalSelectedTag &&
globalSelectedTag.tagSelected &&
tagArray.includes(globalSelectedTag.tagSelected)
) {
setTagSelected(globalSelectedTag.tagSelected);
}
}, [globalSelectedTag]);
const renderTagMenu = () => {
return tagArray.map((value, index, array) => {
return renderDropDownItem((e) => {
setTagSelected(value);
if (onTagSelected) {
onTagSelected(value);
}
}, value);
});
};
return (
<Container className="main-header-container flex-wrap flex-col">
<div
className="flex-row align-center full warp"
id="main-header-container-wrapper"
>
<Col className="flex-row" style={{ padding: '0' }}>
<div className="flex-col full wrap">
<div className="flex-row">
<Form className="main-header-input">
<Form.Control
className="main-header-form main-header-input-text"
placeholder="GitHub URL or Repo Name"
aria-describedby="append-icon"
onChange={(e) => {
setSearch(e.target.value);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
if (search && onSearch) {
onSearch(search);
}
}
}}
/>
</Form>
<Button
className="flex-row flex-center main-header-search"
onClick={() => {
if (search && onSearch) {
onSearch(search);
}
}}
>
<SearchOutlined />
</Button>
</div>
<div
className="flex-row align-center"
style={{
marginTop: '0.5rem',
}}
>
<div className="flex-row align-center">
<div className="main-dropdown-tags">Sort by</div>
<Dropdown
style={{
marginRight: '1rem',
}}
>
<Dropdown.Toggle
variant="light"
className="main-header-dropdown"
>
{filterSelected}
</Dropdown.Toggle>
<Dropdown.Menu
variant="dark"
style={{
minWidth: '7rem',
}}
>
{renderDefaultDropDownItems()}
</Dropdown.Menu>
</Dropdown>
</div>
<div className="flex-row align-center">
<div className="main-dropdown-tags">Language</div>
<Dropdown>
<Dropdown.Toggle
variant="light"
className="main-header-dropdown"
>
{tagSelected}
</Dropdown.Toggle>
<Dropdown.Menu
variant="dark"
style={{
minWidth: '7rem',
}}
>
{renderTagMenu()}
</Dropdown.Menu>
</Dropdown>
</div>
</div>
</div>
</Col>
</div>
</Container>
);
});
GFIMainPageHeader.displayName = 'GFIMainPageHeader';

View File

@ -1,33 +0,0 @@
.main-header-container {
height: 7rem;
background-color: white;
padding: 0;
margin: 0;
}
.main-header-form {
}
.main-header-input {
flex-grow: 1;
}
.main-header-search {
margin-left: auto;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.main-header-input-text {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.main-header-dropdown {
font-size: small;
}
.main-dropdown-tags {
font-size: small;
margin-right: 0.3rem;
}

View File

@ -1,536 +0,0 @@
import React, { forwardRef, useCallback, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { Container, Col, Row } from 'react-bootstrap';
import { useIsMobile, useWindowSize } from '../app/windowContext';
import '../../style/gfiStyle.css';
import {
checkIsNumber,
defaultFontFamily,
checkIsGitRepoURL,
convertFilter,
} from '../../utils';
import { GFINotiToast } from '../login/GFILoginComponents';
import { GFIAlarm, GFIPagination } from '../GFIComponents';
import {
getRepoNum,
getLanguageTags,
searchRepoInfoByNameOrURL,
getPagedRepoDetailedInfo,
getTrainingSummary,
getRepoInfo,
getPagedRepoBrief,
} from '../../api/api';
import { checkGithubLogin } from '../../api/githubApi';
import {
createGlobalProgressBarAction,
createLogoutAction,
createMainPageLangTagSelectedAction,
createPopoverAction,
MainPageLangTagSelectedState,
} from '../../storage/reducers';
import { GFI_REPO_FILTER_NONE, GFIMainPageHeader } from './mainHeader';
import {
GFIIssueMonitor,
GFIRepoDisplayView,
GFIRepoStaticsDemonstrator,
} from './GFIRepoDisplayView';
import { RepoBrief, GFITrainingSummary, RepoSort } from '../../model/api';
import { GFIRootReducers } from '../../storage/configureStorage';
import { GFITrainingSummaryDisplayView } from './GFITrainingSummaryDisplayView';
export function MainPage() {
const dispatch = useDispatch();
useEffect(() => {
checkGithubLogin().then((res) => {
if (!res) {
dispatch(createLogoutAction());
}
});
dispatch(createPopoverAction());
}, []);
const [showLoginMsg, setShowLoginMsg] = useState(false);
const [showSearchMsg, setShowSearchMsg] = useState(false);
const [showBannerMsg, setShowBannerMsg] = useState(true);
const isMobile = useIsMobile();
const { width, height } = useWindowSize();
const userName = useSelector((state: GFIRootReducers) => {
return state.loginReducer?.name;
});
const userAvatarUrl = useSelector((state: GFIRootReducers) => {
return state.loginReducer?.avatar;
});
const emptyRepoInfo: RepoBrief = {
name: '',
owner: '',
description: '',
language: '',
topics: [],
};
const [displayRepoInfo, setDisplayRepoInfo] = useState<
RepoBrief[] | undefined
>([emptyRepoInfo]);
const [alarmConfig, setAlarmConfig] = useState({ show: false, msg: '' });
const showAlarm = (msg: string) => {
setAlarmConfig({ show: true, msg });
};
interface LocationStateLoginType {
state: {
justLogin: boolean;
};
}
const location = useLocation() as LocationStateLoginType;
useEffect(() => {
const query = window.location.search;
const urlParams = new URLSearchParams(query);
const name = urlParams.get('name');
const owner = urlParams.get('owner');
if (name && owner) {
getRepoInfo(name, owner).then((res) => {
if (res) {
handleSearchBtn(name);
}
});
} else {
fetchRepoInfoList(1);
setPageIdx(1);
getRepoNum(selectedTag).then((res) => {
if (res && Number.isInteger(res)) {
setTotalRepos(res);
}
});
}
if ('state' in location && location.state && location.state.justLogin) {
setShowLoginMsg(true);
}
}, []);
const repoCapacity = 5;
const [pageIdx, setPageIdx] = useState(0);
const [totalRepos, setTotalRepos] = useState(0);
const [selectedTag, setSelectedTag] = useState<string>();
const [selectedFilter, setSelectedFilter] = useState<string>();
let [pageFormInput, setPageFormInput] = useState<string | number | undefined>(
0
);
const [trainingSummary, setTrainingSummary] = useState<{
[key: string]: GFITrainingSummary;
}>();
const pageNums = () => {
if (totalRepos % repoCapacity === 0) {
return Math.floor(totalRepos / repoCapacity);
}
return Math.floor(totalRepos / repoCapacity) + 1;
};
const toPage = (i: number) => {
if (i >= 1 && i <= pageNums()) {
setPageIdx(i);
}
};
useEffect(() => {
if (selectedTag || selectedFilter) {
let _tag = selectedTag === "All" ? undefined : selectedTag;
fetchRepoInfoList(1, _tag, convertFilter(selectedFilter));
setPageIdx(1);
dispatch(
createMainPageLangTagSelectedAction({
tagSelected: selectedTag,
})
);
}
}, [selectedTag, selectedFilter]);
useEffect(() => {
if (pageIdx) {
fetchRepoInfoList(pageIdx, selectedTag, convertFilter(selectedFilter));
}
}, [pageIdx]);
const generateTrainingSummaryKey = (name: string, owner: string) =>
owner + name;
useEffect(() => {
if (displayRepoInfo) {
Promise.all(
displayRepoInfo.map((repoInfo) =>
getTrainingSummary(repoInfo.name, repoInfo.owner)
)
).then((values) => {
if (values) {
const res = values.flat();
if (res) {
const trainingSummary: { [key: string]: GFITrainingSummary } = {};
for (const summary of res) {
if (summary) {
trainingSummary[
generateTrainingSummaryKey(summary.name, summary.owner)
] = summary;
}
}
setTrainingSummary(trainingSummary);
}
}
});
}
}, [displayRepoInfo]);
const fetchRepoInfoList = (
pageNum: number,
tag?: string,
filter?: RepoSort
) => {
const beginIdx = (pageNum - 1) * repoCapacity;
dispatch(createGlobalProgressBarAction({ hidden: false }));
getRepoNum(selectedTag).then((res) => {
if (res && Number.isInteger(res)) {
setTotalRepos(res);
}
});
getPagedRepoBrief(beginIdx, repoCapacity, tag, filter).then((repoList) => {
if (repoList && Array.isArray(repoList)) {
const repoInfoList = repoList.map((repo) => {
if ('name' in repo && 'owner' in repo) {
return {
name: repo.name,
owner: repo.owner,
language: repo.language ? repo.language : undefined,
description: repo.description ? repo.description : undefined,
topics: 'topics' in repo ? repo.topics : undefined,
};
}
return emptyRepoInfo;
});
setDisplayRepoInfo(repoInfoList);
}
dispatch(createGlobalProgressBarAction({ hidden: true }));
});
};
const onPageBtnClicked = () => {
if (checkIsNumber(pageFormInput)) {
pageFormInput = Number(pageFormInput);
if (pageFormInput > 0 && pageFormInput <= pageNums()) {
toPage(pageFormInput);
}
}
};
const handleSearchBtn = useCallback((s: string) => {
let repoURL: string | undefined = s;
let repoName;
if (!checkIsGitRepoURL(s)) {
repoURL = undefined;
repoName = s;
}
dispatch(createGlobalProgressBarAction({ hidden: false }));
searchRepoInfoByNameOrURL(repoName, repoURL).then((res) => {
if (res) {
setTotalRepos(1);
setDisplayRepoInfo(res);
setShowSearchMsg(true);
} else {
showAlarm(
"This repository hasn't been added to our database yet. Please connect with its maintainers."
);
}
dispatch(createGlobalProgressBarAction({ hidden: true }));
});
}, []);
const renderInfoComponent = () => {
if (displayRepoInfo && displayRepoInfo.length) {
return displayRepoInfo.map((item, _) => {
const summary = trainingSummary
? trainingSummary[generateTrainingSummaryKey(item.name, item.owner)]
: undefined;
return (
<GFIRepoDisplayView
key={`repo-display-main-${item.name}-${item.owner}`}
className="default-box-shadow"
repoInfo={item}
tags={['GFI', 'Repo Data']}
panels={[
<GFIIssueMonitor
repoInfo={item}
trainingSummary={summary}
key={1}
/>,
<GFIRepoStaticsDemonstrator
repoInfo={item}
trainingSummary={summary}
key={2}
/>,
]}
style={{
border: '1px solid var(--color-border-default)',
borderRadius: '7px',
marginBottom: '1rem',
}}
/>
);
});
}
return <></>;
};
const renderMainArea = () => {
return (
<Row>
<Col className="flex-row align-items-start justify-content-start">
<Container
className="flex-col"
style={{
padding: '0px',
marginLeft: '0px',
width: isMobile ? '100%' : '65%',
}}
>
{renderInfoComponent()}
<GFIPagination
pageIdx={pageIdx}
toPage={(pageNum) => {
toPage(pageNum);
}}
pageNums={pageNums()}
onFormInput={(target) => {
const t = target as HTMLTextAreaElement;
setPageFormInput(t.value);
}}
onPageBtnClicked={() => {
onPageBtnClicked();
}}
maxPagingCount={3}
needInputArea
/>
</Container>
{!isMobile ? (
<Container
style={{
width: '35%',
maxWidth: '430px',
minWidth: '310px',
padding: '0',
}}
>
<div className="flex-col align-center">
<GFIDadaKanban
onTagClicked={(tag) => {
if (tag) {
setSelectedTag(tag);
} else {
setSelectedTag(undefined);
dispatch(
createMainPageLangTagSelectedAction({
tagSelected: 'All',
})
);
}
}}
/>
<GFITrainingSummaryDisplayView />
</div>
</Container>
) : (
<></>
)}
</Col>
</Row>
);
};
return (
<>
<Container className="single-page">
<Row
style={{
marginBottom: alarmConfig.show ? '-15px' : '0',
marginTop: alarmConfig.show ? '15px' : '0',
}}
>
{alarmConfig.show ? (
<GFIAlarm
title={alarmConfig.msg}
onClose={() => {
setAlarmConfig({ show: false, msg: alarmConfig.msg });
}}
/>
) : (
<></>
)}
</Row>
<Row>
<Col>
<Container
style={{
padding: '0px',
marginLeft: '0px',
maxWidth: isMobile ? '100%' : '60%',
}}
>
<GFIMainPageHeader
onSearch={(s) => {
handleSearchBtn(s);
}}
onTagSelected={(s) => {
if (s !== selectedTag) {
setSelectedTag(s !== GFI_REPO_FILTER_NONE ? s : undefined);
}
}}
onFilterSelect={(s) => {
if (s !== selectedFilter) {
const str = s as string;
setSelectedFilter(
str !== GFI_REPO_FILTER_NONE ? s : undefined
);
}
}}
/>
</Container>
</Col>
</Row>
<Row>
<GFINotiToast
show={showBannerMsg}
userName={userName || 'visitor'}
userAvatarUrl={userAvatarUrl}
onClose={() => {
setShowBannerMsg(false);
}}
context="GFI-Bot is under active development and not ready for production yet."
/>
<GFINotiToast
show={showLoginMsg}
userName={userName || 'visitor'}
userAvatarUrl={userAvatarUrl}
onClose={() => {
setShowLoginMsg(false);
}}
/>
<GFINotiToast
show={showSearchMsg}
userName={userName || 'visitor'}
userAvatarUrl={userAvatarUrl}
onClose={() => {
setShowSearchMsg(false);
}}
context="Searching Completed!"
/>
</Row>
{renderMainArea()}
</Container>
<Container
style={{
width,
maxWidth: width,
height,
position: 'fixed',
top: '0',
zIndex: '-1000',
}}
className="background"
/>
</>
);
}
interface GFIDadaKanban {
onTagClicked: (tag?: string) => void;
}
const GFIDadaKanban = forwardRef((props: GFIDadaKanban, ref) => {
const { onTagClicked } = props;
const [langTags, setLangTags] = useState<any[]>([]);
const globalSelectedTag = useSelector<
GFIRootReducers,
MainPageLangTagSelectedState
>((state) => {
return state.mainPageLangTagSelectedStateReducer;
});
useEffect(() => {
if (globalSelectedTag && langTags.includes(globalSelectedTag.tagSelected)) {
const idx = langTags.indexOf(globalSelectedTag.tagSelected);
if (idx !== selectedIdx) {
setSelectedIdx(idx);
}
} else {
setSelectedIdx(-1);
}
}, [globalSelectedTag]);
useEffect(() => {
getLanguageTags().then((res) => {
if (res && Array.isArray(res)) {
setLangTags(res);
}
});
}, []);
const [selectedIdx, setSelectedIdx] = useState<number>();
const renderLanguageTags = () => {
return langTags.map((val, index) => {
const selected =
selectedIdx !== undefined
? selectedIdx === index
? 'selected'
: ''
: '';
return (
<button
className={`gfi-rounded ${selected}`}
key={`lang-tag ${index}`}
onClick={() => {
if (index !== selectedIdx) {
setSelectedIdx(index);
onTagClicked(val);
} else {
setSelectedIdx(-1);
onTagClicked();
}
}}
>
{val}
</button>
);
});
};
return (
<div
className="gfi-wrapper kanban"
style={{
fontFamily: defaultFontFamily,
}}
>
{/* <GFIAlphaWarning /> */}
<div className="kanban wrapper">
<div className="gfi-wrapper tags">
<div style={{ marginBottom: '0.3rem' }}>Languages</div>
<div className="tags wrapper" style={{ marginBottom: '0.1rem' }}>
{renderLanguageTags()}
</div>
</div>
</div>
</div>
);
});
GFIDadaKanban.displayName = 'GFIDadaKanban';

View File

@ -1,645 +0,0 @@
import React, { MouseEventHandler, useEffect, useRef, useState } from 'react';
import {
Button,
Col,
Container,
Dropdown,
Form,
ListGroup,
Nav,
Overlay,
Popover,
Row,
} from 'react-bootstrap';
import { LinkContainer } from 'react-router-bootstrap';
import { withRouter } from 'react-router-dom';
// rollup compatibility issue see:https://github.com/vitejs/vite/issues/2139#issuecomment-1024852072
import { KeepAlive } from 'react-activation';
import '../../style/gfiStyle.css';
import { useDispatch, useSelector } from 'react-redux';
import {
createAccountNavStateAction,
createGlobalProgressBarAction,
} from '../../storage/reducers';
import { GFIRootReducers } from '../../storage/configureStorage';
import { checkIsGitRepoURL, convertFilter } from '../../utils';
import importTips from '../../assets/git-add-demo.png';
import { checkHasRepoPermissions } from '../../api/githubApi';
import { GFIAlarm, GFIAlarmPanelVariants, GFIOverlay } from '../GFIComponents';
import { addRepoToGFIBot, getAddRepoHistory } from '../../api/api';
import type { RepoBrief } from '../../model/api';
import {
GFIIssueMonitor,
GFIRepoDisplayView,
GFIRepoStaticsDemonstrator,
} from '../main/GFIRepoDisplayView';
import { GFIRepoSearchingFilterType } from '../main/mainHeader';
import { useIsMobile } from '../app/windowContext';
import { SearchHistory } from './SearchHistory';
import { RepoSetting } from './RepoSetting';
export interface GFIPortal {}
type GFIUserQueryHistoryItem = {
pending: boolean;
repo: RepoBrief;
};
type SubPanelIDs = 'Add Project' | 'Search History' | 'My Account';
const SubPanelTitles: SubPanelIDs[] & string[] = [
'Add Project',
'Search History',
'My Account',
];
export function GFIPortal(props: GFIPortal) {
const dispatch = useDispatch();
useEffect(() => {
dispatch(createAccountNavStateAction({ show: true }));
}, []);
const [currentPanelID, setCurrentPanelID] = useState<SubPanelIDs & string>(
'Add Project'
);
const renderSubPanel = () => {
if (currentPanelID === 'Add Project') {
return (
<KeepAlive>
<AddProjectComponent />
</KeepAlive>
);
}
if (currentPanelID === 'Search History') {
return <SearchHistory />;
}
if (currentPanelID === 'My Account') {
return <></>;
}
};
return (
<Container className="account-page-sub-container">
<Row className="account-page-sub-container-row">
<Col sm={3}>
<AccountSideBar
actionList={SubPanelTitles}
onClick={(i) => {
setCurrentPanelID(SubPanelTitles[i]);
}}
/>
</Col>
<Col sm={9}> {renderSubPanel()} </Col>
</Row>
</Container>
);
}
export const GFIPortalPageNav = withRouter((props: { id?: string }) => {
return (
<Nav
variant="pills"
className="flex-row justify-content-center align-center"
id={props?.id}
style={{ marginTop: '10px' }}
>
<Nav.Item className="account-nav-container">
<LinkContainer to="/portal">
<Nav.Link eventKey={1} className="account-nav">
Dashboard
</Nav.Link>
</LinkContainer>
</Nav.Item>
<Nav.Item className="account-nav-container">
<LinkContainer to="/repos">
<Nav.Link eventKey={2} className="account-nav" active={false}>
Repo Data
</Nav.Link>
</LinkContainer>
</Nav.Item>
</Nav>
);
});
interface AccountSideBar {
actionList: string[];
onClick?: (i: number) => void;
}
function AccountSideBar(props: AccountSideBar) {
const { actionList, onClick } = props;
const [selectedList, setSelectedList] = useState(
actionList.map((_, i) => {
return !i;
})
);
const userName = useSelector((state: GFIRootReducers) => {
if ('name' in state.loginReducer) return state.loginReducer.name;
return undefined;
});
const userAvatar = useSelector((state: GFIRootReducers) => {
if ('avatar' in state.loginReducer) return state.loginReducer.avatar;
return undefined;
});
const renderItems = () => {
return actionList.map((title, i) => {
return (
<ListGroup.Item
action
as="button"
onClick={() => {
setSelectedList(
selectedList.map((_, idx) => {
return idx === i;
})
);
if (onClick) {
onClick(i);
}
}}
variant={selectedList[i] ? 'primary' : 'light'}
key={i}
>
{title}
</ListGroup.Item>
);
});
};
return (
<div className="flex-col flex-wrap" id="portal-side-bar">
<div className="flex-row align-center portal-side-bar-userinfo">
<div className="flex-col portal-side-bar-userinfo-name">
<div> Hello, </div>
<div> {userName} </div>
</div>
<img src={userAvatar} alt="" />
</div>
<ListGroup>{renderItems()}</ListGroup>
</div>
);
}
function AddProjectComponent() {
const [projectURL, setProjectURL] = useState<string>();
const [showAlarmMsg, setShowAlarmMsg] = useState(false);
type AlarmConfig = {
show: boolean;
msg: string;
variant?: GFIAlarmPanelVariants;
};
const [mainAlarmConfig, setMainAlarmConfig] = useState<AlarmConfig>({
show: false,
msg: '',
variant: 'danger',
});
const [addRepoAlarmConfig, setAddRepoAlarmConfig] = useState<AlarmConfig>({
show: false,
msg: '',
variant: 'success',
});
const dispatch = useDispatch();
const showProgressBar = () => {
dispatch(createGlobalProgressBarAction({ hidden: false }));
};
const hideProgressBar = () => {
dispatch(createGlobalProgressBarAction({ hidden: true }));
};
const overlayRef = useRef<HTMLDivElement>(null);
const [addedRepos, setAddedRepos] = useState<GFIUserQueryHistoryItem[]>();
const [addedRepoIncrement, setAddedRepoIncrement] = useState(false);
const fetchAddedRepos = (onComplete?: () => void) => {
getAddRepoHistory(convertFilter(filterSelected)).then((res) => {
const finishedQueries: GFIUserQueryHistoryItem[] | undefined =
res?.finished_queries?.map((info) => ({
pending: false,
repo: info,
}));
let pendingQueries: GFIUserQueryHistoryItem[] | undefined =
res?.queries?.map((info) => ({
pending: true,
repo: info,
}));
if (!Array.isArray(pendingQueries)) {
pendingQueries = [];
}
let completeQueries = '';
if (finishedQueries && addedRepos) {
for (const finishedQuery of finishedQueries) {
for (const reposAdded of addedRepos) {
if (
reposAdded.pending &&
reposAdded.repo.owner === finishedQuery.repo.owner &&
reposAdded.repo.name === finishedQuery.repo.name
) {
completeQueries += `${finishedQuery.repo.owner}/${finishedQuery.repo.name} `;
}
}
}
if (completeQueries !== '') {
setAddRepoAlarmConfig({
show: true,
msg: `Repos: ${completeQueries}have been successfully added`,
variant: 'success',
});
}
}
setAddedRepos(
finishedQueries
? finishedQueries.concat(pendingQueries)
: pendingQueries
);
if (onComplete) {
onComplete();
}
setAddedRepoIncrement(!addedRepoIncrement);
});
};
useEffect(() => {
fetchAddedRepos();
}, []);
const [intervalID, setIntervalId] = useState<number>();
useEffect(() => {
if (intervalID) {
clearInterval(intervalID);
}
setIntervalId(setInterval(fetchAddedRepos, 10000));
return () => {
if (intervalID) {
clearInterval(intervalID);
}
};
}, [addedRepos, addedRepoIncrement]);
const addGFIRepo = () => {
let shouldDisplayAlarm = true;
if (projectURL && checkIsGitRepoURL(projectURL)) {
const urls = projectURL.split('/');
const repoName = urls[urls.length - 1].split('.git')[0];
const repoOwner = urls[urls.length - 2];
if (repoName && repoOwner) {
showProgressBar();
checkHasRepoPermissions(repoName, repoOwner).then((res) => {
if (res) {
addRepoToGFIBot(repoName, repoOwner).then((result?: string) => {
if (result) {
setMainAlarmConfig({
show: true,
msg: `Query ${repoOwner}/${repoName} ${result}`,
variant: 'success',
});
fetchAddedRepos(() => {
hideProgressBar();
});
} else {
setMainAlarmConfig({
show: true,
msg: `Connection Lost`,
variant: 'danger',
});
hideProgressBar();
}
});
} else {
setMainAlarmConfig({
show: true,
msg: `You\'re not a maintainer of ${repoOwner}/${repoName} or this is a private repository`,
variant: 'danger',
});
hideProgressBar();
}
});
shouldDisplayAlarm = false;
}
}
setShowAlarmMsg(shouldDisplayAlarm);
};
const [overlayTarget, setOverlayTarget] = useState<EventTarget>();
const [showOverlay, setShowOverlay] = useState(false);
const overlayContainer = useRef(null);
const popoverRef = useRef<HTMLDivElement>(null);
const onErrorTipClick: MouseEventHandler<HTMLDivElement> = (e) => {
setOverlayTarget(e.target);
setShowOverlay(!showOverlay);
};
const checkIfClosePopover = (e: MouseEvent) => {
if (!popoverRef?.current?.contains(e.target as Node)) {
setShowOverlay(false);
}
};
useEffect(() => {
if (showOverlay) {
document.addEventListener('mousedown', checkIfClosePopover);
} else {
document.removeEventListener('mousedown', checkIfClosePopover);
}
return () => {
document.removeEventListener('mousedown', checkIfClosePopover);
};
}, [showOverlay]);
const repoInfoPanelRef = useRef<HTMLDivElement>(null);
const [addedRepoDisplayPanelConfig, setAddedRepoDisplayPanelConfig] =
useState<RepoBrief>();
const [showPopover, setShowPopover] = useState(false);
type FilterType = GFIRepoSearchingFilterType;
const [filterSelected, setFilterSelected] = useState<FilterType>('Alphabetical');
const filters: FilterType[] = [
'Alphabetical',
'Number of Stars',
'Issue Resolution Time',
'% of Issues Resolved by New Contributors',
'# of Predicted Good First Issues',
];
const onRepoHistoryClicked = (repoInfo: RepoBrief) => {
setAddedRepoDisplayPanelConfig(repoInfo);
setShowPopover(true);
};
const renderRepoHistory = () => {
if (addedRepos && addedRepos.length) {
return addedRepos.map((item, i) => {
return (
<RepoHistoryTag
pending={item.pending}
repoInfo={item.repo}
available
onClick={item.pending ? () => {} : onRepoHistoryClicked}
key={i}
/>
);
});
}
return (
<RepoHistoryTag
pending
repoInfo={{
name: 'None',
owner: 'Try to add your projects!',
description: '',
language: '',
topics: [],
}}
available={false}
/>
);
};
const onFilterSelected = (filter: FilterType) => {
if (filter !== filterSelected) {
setFilterSelected(filter);
}
};
useEffect(() => {
fetchAddedRepos();
}, [filterSelected]);
const isMobile = useIsMobile();
return (
<div className="flex-col">
{mainAlarmConfig.show ? (
<GFIAlarm
title={mainAlarmConfig.msg}
onClose={() =>
setMainAlarmConfig({
show: false,
msg: '',
})
}
variant={mainAlarmConfig?.variant}
/>
) : (
<></>
)}
<div className="account-page-panel-title project-add-comp-title">
Add Your Project To GFI-Bot
</div>
<div className="project-add-comp-tips">
<p>
{' '}
<strong>Notice: </strong> We&apos;ll register the repository to our
database and use it for data training and predictions.{' '}
</p>
<p>
{' '}
Make sure that you are one of the maintainers of the repository.{' '}
</p>
</div>
<div className="project-adder">
<Form className="flex-col project-adder-form">
<Form.Label className="project-adder-label">
{' '}
Please input a GitHub Repo URL{' '}
</Form.Label>
<Form.Control
placeholder="GitHub URL"
onChange={(e) => {
setProjectURL(e.target.value);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
addGFIRepo();
}
}}
/>
<div
className="flex-row align-center"
style={{ marginTop: '0.5rem' }}
>
{showAlarmMsg && (
<div ref={overlayContainer}>
<div
className="hoverable project-add-alarm"
onClick={onErrorTipClick}
>
Please input a correct GitHub Repo URL
</div>
<Overlay
show={showOverlay}
target={overlayTarget}
container={overlayContainer}
placement="bottom-start"
>
<Popover className="fit" ref={popoverRef}>
<Popover.Body className="fit">
<img
src={importTips}
alt=""
className="project-add-overlay-warn-tip"
/>
</Popover.Body>
</Popover>
</Overlay>
</div>
)}
<Button
size="sm"
variant="outline-primary"
style={{ marginLeft: 'auto' }}
onClick={() => {
addGFIRepo();
}}
>
{' '}
Add Project{' '}
</Button>
</div>
</Form>
</div>
<div className="flex-row align-center project-add-comp-added">
<div className="account-page-panel-title">Projects Added</div>
<div className="flex-row align-center" style={{ marginLeft: 'auto' }}>
<div style={{ fontSize: 'small', marginRight: '0.7rem' }}>
{' '}
Sorted By{' '}
</div>
<Dropdown>
<Dropdown.Toggle variant="light" style={{ fontSize: 'small' }}>
{filterSelected}
</Dropdown.Toggle>
<Dropdown.Menu align="end" variant="dark">
{filters.map((item) => {
return (
<Dropdown.Item
onClick={(e) => {
onFilterSelected(item);
}}
style={{ fontSize: 'small' }}
key={item}
>
{item as string}
</Dropdown.Item>
);
})}
</Dropdown.Menu>
</Dropdown>
</div>
</div>
{addRepoAlarmConfig.show ? (
<div style={{ marginBottom: '-15px', marginTop: '5px' }}>
<GFIAlarm
title={addRepoAlarmConfig.msg}
onClose={() => {
setAddRepoAlarmConfig({
show: false,
msg: '',
variant: 'success',
});
}}
variant={addRepoAlarmConfig.variant}
/>
</div>
) : (
<></>
)}
<div
className="flex-row flex-wrap align-center"
style={{ marginTop: '0.7rem' }}
>
{renderRepoHistory()}
</div>
<GFIOverlay
className="gfi-portal-overlay"
callback={() => setShowPopover(false)}
hidden={!showPopover}
ref={overlayRef}
width={isMobile ? '90%' : '40%'}
id="gfi-portal-overlay"
direction="right"
animation
>
{addedRepoDisplayPanelConfig && (
<GFIRepoDisplayView
className="gfi-portal-overlay-panel"
key={`added-repo-panel-${addedRepoDisplayPanelConfig.owner}-${addedRepoDisplayPanelConfig.name}`}
repoInfo={addedRepoDisplayPanelConfig}
tags={['Settings', 'GFI', 'Repo Data']}
panels={[
<RepoSetting repoInfo={addedRepoDisplayPanelConfig} key={1} />,
<GFIIssueMonitor
repoInfo={addedRepoDisplayPanelConfig}
key={2}
/>,
<GFIRepoStaticsDemonstrator
repoInfo={addedRepoDisplayPanelConfig}
paging={false}
key={3}
/>,
]}
style={{
marginBottom: '0.5rem',
transition: '0.2s',
display: showPopover ? '' : 'none',
}}
ref={repoInfoPanelRef}
/>
)}
</GFIOverlay>
<div className="account-page-panel-title project-add-comp-tutorial">
Tutorial
</div>
<div className="account-page-panel-tutorial">
<p> To Be Completed. </p>
<p>
{' '}
We describe our envisioned use cases for GFI-Bot in this{' '}
<a href="https://github.com/osslab-pku/gfi-bot/blob/main/USE_CASES.md">
documentation
</a>
.{' '}
</p>
</div>
</div>
);
}
function RepoHistoryTag(props: {
pending: boolean;
repoInfo: RepoBrief;
available: boolean;
onClick?: (repoInfo: RepoBrief) => void;
}) {
const { pending, repoInfo, available, onClick } = props;
const isPending = available
? pending
? 'query-pending'
: 'query-succeed'
: 'query-none';
const stateMsg = available ? (pending ? 'Pending' : 'Succeed') : '';
return (
<div
className={`repo-history-tag ${isPending} hoverable`}
onClick={() => {
if (onClick) {
onClick(repoInfo);
}
}}
>
<div>
{' '}
{repoInfo.owner} {available ? '|' : ''} {stateMsg}{' '}
</div>
<div> {repoInfo.name} </div>
</div>
);
}

View File

@ -1,297 +0,0 @@
import React, { useEffect, useRef, useState } from 'react';
import { Form, Button } from 'react-bootstrap';
import { GFIRepoBasicProp } from '../main/GFIRepoDisplayView';
import '../../style/gfiStyle.css';
import { GFIAlarm, GFIAlarmPanelVariants } from '../GFIComponents';
import {
deleteRepoQuery,
getRepoConfig,
updateRepoConfig,
updateRepoInfo,
updateTags,
} from '../../api/api';
import type { RepoGFIConfig } from '../../model/api';
import { checkIsNumber } from '../../utils';
export type RepoSettingPops = GFIRepoBasicProp;
export function RepoSetting(props: RepoSettingPops) {
const { repoInfo } = props;
const gfiThresholdRef = useRef<HTMLInputElement>(null);
const gfiTagNameRef = useRef<HTMLInputElement>(null);
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
const [showComment, setShowComment] = useState(false);
const [newcomerThresholdSelected, setNewcomerThresholdSelected] = useState(1);
const [showDeleteAlarm, setShowDeleteAlarm] = useState(false);
const [currentRepoConfig, setCurrentRepoConfig] = useState<RepoGFIConfig>();
const [showConfigAlarmBanner, setShowConfigAlarmBanner] = useState(false);
const [configAlarmBanner, setConfigAlarmBanner] = useState<{
variant: GFIAlarmPanelVariants;
title: string;
}>({
variant: 'danger',
title: '',
});
const loadRepoConfig = () => {
getRepoConfig(repoInfo.name, repoInfo.owner).then((config) => {
if (config) {
setCurrentRepoConfig(config);
}
});
};
useEffect(() => {
loadRepoConfig();
}, []);
useEffect(() => {
if (currentRepoConfig) {
setShowComment(currentRepoConfig.need_comment);
setNewcomerThresholdSelected(currentRepoConfig.newcomer_threshold);
}
}, [currentRepoConfig]);
const onBotConfigSubmit = () => {
if (gfiThresholdRef.current && gfiTagNameRef.current) {
let gfiThreshold = gfiThresholdRef.current.value;
if (!gfiThreshold && currentRepoConfig) {
gfiThreshold = currentRepoConfig.gfi_threshold.toString();
}
let gfiTag = gfiTagNameRef.current.value;
if (!gfiTag && currentRepoConfig) {
gfiTag = currentRepoConfig.issue_tag;
}
if (
checkIsNumber(gfiThreshold) &&
parseFloat(gfiThreshold) > 0 &&
parseFloat(gfiThreshold) < 1 &&
gfiTag
) {
const repoConfig: RepoGFIConfig = {
newcomer_threshold: newcomerThresholdSelected,
issue_tag: gfiTag,
gfi_threshold: parseFloat(gfiThreshold),
need_comment: showComment,
};
updateRepoConfig(repoInfo.name, repoInfo.owner, repoConfig).then(
(res) => {
if (res === 'success') {
setShowConfigAlarmBanner(true);
setConfigAlarmBanner({
variant: 'success',
title: 'Repo config successfully updated!',
});
} else {
setShowConfigAlarmBanner(true);
setConfigAlarmBanner({
variant: 'danger',
title: 'Repo config update failed',
});
}
loadRepoConfig();
}
);
} else {
setShowConfigAlarmBanner(true);
setConfigAlarmBanner({
variant: 'danger',
title: 'Please input a GFI threshold between 0 and 1.',
});
}
}
};
const deleteRepo = () => {
deleteRepoQuery(repoInfo.name, repoInfo.owner).then(() => {
setShowDeleteAlarm(false);
window.location.reload();
});
};
const updateGFIInfo = () => {
updateRepoInfo(repoInfo.name, repoInfo.owner).then((res) => {
setShowUpdateBanner(true);
});
};
const updateGFITags = () => {
updateTags(repoInfo.name, repoInfo.owner).then((res) => {
setShowUpdateBanner(true);
});
};
return (
<div className="gfi-repo-setting-container flex-col flex-wrap align-items-stretch">
<div style={{ margin: '0 1rem' }}>
{showUpdateBanner && (
<GFIAlarm
variant="success"
title={`Updating ${repoInfo.owner} / ${repoInfo.name}, we'll send you an email after successfully updated `}
onClose={() => setShowUpdateBanner(false)}
/>
)}
</div>
<div style={{ margin: '0 1rem' }}>
{showConfigAlarmBanner && (
<GFIAlarm
variant={configAlarmBanner.variant}
title={configAlarmBanner.title}
onClose={() => setShowConfigAlarmBanner(false)}
/>
)}
</div>
<div className="gfi-repo-setting-item-container">
<div className="gfi-repo-setting-item-title">GFI-Bot Settings</div>
<div className="gfi-repo-setting-item flex-col">
{currentRepoConfig && (
<Form className="flex-col">
<div className="flex-row justify-content-between align-items-start flex-wrap">
<div className="gfi-repo-setting-form-col">
<Form.Group controlId="gfi-threshold">
<Form.Label className="gfi-repo-setting-form-label">
GFI Threshold
</Form.Label>
<Form.Control
placeholder={currentRepoConfig.gfi_threshold.toString()}
ref={gfiThresholdRef}
/>
<Form.Text className="text-muted">
Threshold for issue labeled as a GFI.
</Form.Text>
</Form.Group>
</div>
<div className="gfi-repo-setting-form-col">
<Form.Group controlId="newcomer-threshold">
<Form.Label className="gfi-repo-setting-form-label">
Newcomer Threshold
</Form.Label>
<Form.Select
onChange={(e) => {
setNewcomerThresholdSelected(parseInt(e.target.value));
}}
>
{[0, 1, 2, 3, 4].map((i, idx) => (
<option
selected={idx + 1 === newcomerThresholdSelected}
key={idx}
>
{i + 1}
</option>
))}
</Form.Select>
<Form.Text className="text-muted">
Max commits as a newcomer.
</Form.Text>
</Form.Group>
</div>
<div className="gfi-repo-setting-form-col">
<Form.Group controlId="gfi-tag-name">
<Form.Label className="gfi-repo-setting-form-label">
Issue Tag Name
</Form.Label>
<Form.Control
placeholder={currentRepoConfig.issue_tag}
ref={gfiTagNameRef}
/>
<Form.Text className="text-muted">
Issue Tag for GFIs
</Form.Text>
</Form.Group>
</div>
</div>
<div className="gfi-repo-setting-form-col">
<Form.Group controlId="gfi-tag-name">
<Form.Check
checked={showComment}
onChange={() => setShowComment(!showComment)}
label="Need comments for GFIs"
/>
</Form.Group>
</div>
<Button
style={{ marginLeft: 'auto' }}
size="sm"
variant="outline-primary"
onClick={() => {
onBotConfigSubmit();
}}
>
{' '}
Submit{' '}
</Button>
</Form>
)}
</div>
</div>
<div className="flex-row gfi-repo-setting-btns">
<Button
variant="outline-success"
size="sm"
onClick={() => {
updateGFITags();
}}
>
Tag GFIs
</Button>
<Button
variant="outline-warning"
size="sm"
onClick={() => {
updateGFIInfo();
}}
>
Force Update GFIs
</Button>
<Button
variant="outline-danger"
size="sm"
onClick={() => {
if (!showDeleteAlarm) {
setShowDeleteAlarm(true);
}
}}
>
Delete Repo
</Button>
</div>
<div className="flex-row gfi-repo-setting-btns">
{showDeleteAlarm && (
<GFIAlarm className="no-btn gfi-repo-setting-alarm">
<div>
&nbsp;Warning: You&apos;re going to delete your repository in
GFI-Bot&nbsp;
</div>
<div className="flex-row gfi-repo-setting-alarm-btns">
<Button
className="gfi-repo-setting-alarm-btn"
variant="outline-success"
size="sm"
onClick={() => setShowDeleteAlarm(false)}
>
{' '}
Dismiss{' '}
</Button>
<Button
className="gfi-repo-setting-alarm-btn"
variant="outline-danger"
size="sm"
onClick={(e) => {
e.preventDefault();
deleteRepo();
}}
>
{' '}
Continue{' '}
</Button>
</div>
</GFIAlarm>
)}
</div>
</div>
);
}

View File

@ -1,145 +0,0 @@
import React, { useEffect, useRef, useState } from 'react';
import { ListGroup } from 'react-bootstrap';
import { DeleteOutlined } from '@ant-design/icons';
import type { RepoBrief, SearchedRepo } from '../../model/api';
import { deleteUserSearch, getRepoInfo, getUserSearches } from '../../api/api';
import '../../style/gfiStyle.css';
import {
GFIIssueMonitor,
GFIRepoDisplayView,
GFIRepoStaticsDemonstrator,
} from '../main/GFIRepoDisplayView';
import { GFIOverlay } from '../GFIComponents';
import { useIsMobile } from '../app/windowContext';
export function SearchHistory() {
const [searchHistory, setSearchHistory] = useState<SearchedRepo[]>();
const [showPopover, setShowPopover] = useState(false);
const overlayRef = useRef<HTMLDivElement>(null);
const isMobile = useIsMobile();
const setSearchRes = (res: SearchedRepo[]) => {
const res_reversed = res.reverse();
setSearchHistory(res_reversed);
setSelectedList(res_reversed.map((_, idx) => !idx));
};
useEffect(() => {
getUserSearches().then((res) => {
if (res) {
setSearchRes(res);
}
});
}, []);
const [selectedList, setSelectedList] = useState<boolean[]>();
const [repoDisplay, setRepoDisplay] = useState<RepoBrief>();
const onItemClicked = (name: string, owner: string, idx: number) => {
if (repoDisplay?.name !== name || repoDisplay?.owner !== owner) {
getRepoInfo(name, owner).then((res) => {
if (res) {
setRepoDisplay(res);
setShowPopover(true);
}
});
} else if (repoDisplay) {
setShowPopover(true);
}
setSelectedList(selectedList?.map((item, i) => i === idx));
};
const deleteSearch = (name: string, owner: string, id: number) => {
deleteUserSearch(name, owner, id).then((res) => {
if (res) {
setSearchRes(res);
}
});
};
const render = () => {
if (searchHistory && selectedList) {
return searchHistory.map((item, idx) => {
let numTag = '';
if (!idx) {
numTag += ' gfi-list-first';
}
if (idx === searchHistory.length - 1) {
numTag += ' gfi-list-last';
}
return (
<div className="flex-row align-center" key={idx}>
<ListGroup.Item
className={`gfi-search-history-item-wrapper ${numTag}`}
id={`gfi-search-history-item-${item.owner}-${item.name}-${idx}`}
action
as="button"
variant={selectedList[idx] ? 'primary' : 'light'}
onClick={() => {
onItemClicked(item.name, item.owner, idx);
}}
>
<div className="gfi-search-history-item flex-row">
<div className="flex-row">
<div> {item.owner} </div>
<div> {' / '} </div>
<div style={{ fontWeight: 'bold' }}> {item.name} </div>
</div>
<div>{item.created_at}</div>
</div>
</ListGroup.Item>
<DeleteOutlined
style={{ fontSize: '120%', marginLeft: '0.7rem' }}
className="hoverable"
onClick={() => {
deleteSearch(item.name, item.owner, item.increment);
}}
/>
</div>
);
});
}
};
return (
<>
<ListGroup className="gfi-search-history-container">
{searchHistory && render()}
</ListGroup>
<GFIOverlay
className="gfi-search-history-overlay"
callback={() => setShowPopover(false)}
hidden={!showPopover}
ref={overlayRef}
width={isMobile ? '90%' : '40%'}
id="gfi-search-history-overlay"
direction="right"
animation
>
{repoDisplay && (
<GFIRepoDisplayView
className="gfi-portal-overlay-panel"
key={`added-repo-panel-${repoDisplay.owner}-${repoDisplay.name}`}
repoInfo={repoDisplay}
tags={['GFI', 'Repo Data']}
panels={[
<GFIIssueMonitor repoInfo={repoDisplay} paging={14} key={1} />,
<GFIRepoStaticsDemonstrator
repoInfo={repoDisplay}
paging={false}
key={2}
/>,
]}
style={{
marginBottom: '0.5rem',
transition: '0.2s',
display: showPopover ? '' : 'none',
}}
/>
)}
</GFIOverlay>
</>
);
}

View File

@ -1,111 +0,0 @@
import React from 'react';
import { Col, Container, Row } from 'react-bootstrap';
import ReactECharts from 'echarts-for-react';
export interface RepoGraphContainerProps {
info?: any[];
title?: string;
}
export const RepoGraphContainer = (props: RepoGraphContainerProps) => {
const dataMonthParser = (info: any[]) => {
return info.map((item, _) => {
return item.month;
});
};
const dataCountParser = (info: any[]) => {
return info.map((item, _) => {
return item.count;
});
};
// desciption for ISO date format
// https://www.w3schools.com/js/js_date_methods.asp
const dateDescriptor = (date: string) =>
new Date(date).toLocaleDateString('en-US', {
month: 'short',
year: 'numeric',
});
const issueDataParser = (info: any[] | undefined) => {
if (typeof info !== 'undefined') {
return info.map((tempInfo, i) => {
return {
count: tempInfo.count,
month: dateDescriptor(tempInfo.month),
};
});
}
return [];
};
const renderData = (info: any[] | undefined) => {
if (info && info.length) {
const detailedInfo = issueDataParser(info);
const xData = dataMonthParser(detailedInfo);
const yData = dataCountParser(detailedInfo);
return <RepoDataGraph xData={xData} yData={yData} />;
}
};
const render = () => {
if (props.info && props.info.length) {
return (
<Container>
<Row>
<Col
style={{
textAlign: 'left',
fontWeight: 'bolder',
fontSize: 'larger',
marginBottom: '10px',
marginLeft: '40px',
}}
>
{props.title}
</Col>
</Row>
<Row>
<Col>{renderData(props.info)}</Col>
</Row>
</Container>
);
}
return <></>;
};
return render();
};
interface RepoDataGraphProps {
xData: any[];
yData: any[];
}
function RepoDataGraph(props: RepoDataGraphProps) {
const options = {
grid: { top: 10, right: 10, bottom: 50, left: 40 },
xAxis: {
type: 'category',
data: props.xData,
},
yAxis: {
type: 'value',
},
series: [
{
data: props.yData,
type: 'line',
smooth: 'true',
animation: false,
},
],
tooltip: {
trigger: 'axis',
},
animation: false,
};
return <ReactECharts option={options} />;
}

View File

@ -1,320 +0,0 @@
import React, { useEffect, useState } from 'react';
import { Alert, Badge, Col, Container, ListGroup, Row } from 'react-bootstrap';
import '../../style/gfiStyle.css';
import { useDispatch } from 'react-redux';
import { checkIsNumber } from '../../utils';
import { GFIAlarm, GFIPagination } from '../GFIComponents';
import { RepoGraphContainer } from './repoDataDemonstrator';
import { getRepoNum, getPagedRepoDetailedInfo } from '../../api/api';
import {
createAccountNavStateAction,
createGlobalProgressBarAction,
} from '../../storage/reducers';
export function Repositories() {
const repoListCapacity = 5;
const [pageIdx, setPageIdx] = useState<number>(1);
const [totalRepos, setTotalRepos] = useState<number>(0);
const [showAlarm, setShowAlarm] = useState<boolean>(false);
const dispatch = useDispatch();
useEffect(() => {
dispatch(createAccountNavStateAction({ show: true }));
}, []);
useEffect(() => {
getRepoNum().then((num) => {
if (num && Number.isInteger(num)) {
setTotalRepos(num);
} else {
setTotalRepos(0);
setShowAlarm(true);
}
});
}, [pageIdx]);
const [infoList, setInfoList] = useState<any[]>([]);
useEffect(() => {
const beginIdx = (pageIdx - 1) * repoListCapacity;
dispatch(createGlobalProgressBarAction({ hidden: false }));
dispatch(createAccountNavStateAction({ show: true }));
getPagedRepoDetailedInfo(beginIdx, repoListCapacity)
.then((repoList) => {
if (repoList && Array.isArray(repoList)) {
setInfoList(repoList);
} else {
setInfoList([]);
setShowAlarm(true);
}
})
.then(() => {
setActiveCardIdx(0);
dispatch(createGlobalProgressBarAction({ hidden: true }));
});
}, [pageIdx]);
const [activeCardIdx, setActiveCardIdx] = useState<number>(0);
const [pageFormInput, setPageFormInput] = useState<string>('0');
const projectCardOnClick = (idx: number) => {
setActiveCardIdx(idx);
};
const projectsInfos = (info: any, index: number) => {
return (
<RepoInfoCard
key={`infoCard${index}`}
initInfo={info}
index={index}
nowActive={activeCardIdx}
callback={projectCardOnClick}
/>
);
};
const renderProjectsInfos = (infoArray?: any[]) => {
if (infoArray && Array.isArray(infoArray)) {
return infoArray.map((info, idx) => {
return projectsInfos(info, idx);
});
}
};
const pageNums = () => {
if (totalRepos % repoListCapacity === 0) {
return Math.floor(totalRepos / repoListCapacity);
}
return Math.floor(totalRepos / repoListCapacity) + 1;
};
const toPage = (i: number) => {
if (i >= 1 && i <= pageNums()) {
setPageIdx(i);
}
};
const onFormInput = (target: EventTarget) => {
const t = target as HTMLTextAreaElement;
setPageFormInput(t.value);
};
const onPageBtnClicked = () => {
if (checkIsNumber(pageFormInput)) {
const pageInput = parseInt(pageFormInput);
if (pageInput > 0 && pageInput <= pageNums()) {
toPage(pageInput);
} else {
window.alert(`Out of page index, max page number is ${pageNums()}`);
}
} else {
window.alert('Please input a number');
}
};
// a little trick
type CardInfoList = {
monthly_stars?: any[];
monthly_issues?: any[];
monthly_commits?: any[];
};
const [showCards, setShowCards] = useState<boolean>(false);
const [cardInfoList, setCardInfoList] = useState<CardInfoList>({});
const [cardInfoListToDisplay, setCardInfoListToDisplay] =
useState<CardInfoList>({});
useEffect(() => {
if (infoList.length && activeCardIdx < infoList.length) {
setShowCards(false);
setCardInfoListToDisplay({});
const parsedInfoList = infoList[activeCardIdx];
if (parsedInfoList) {
setCardInfoList(parsedInfoList);
if (showAlarm) {
setShowAlarm(false);
}
} else {
setCardInfoList({});
}
} else {
setCardInfoList({});
}
}, [activeCardIdx, infoList]);
useEffect(() => {
setTimeout(() => {
setShowCards(true);
setCardInfoListToDisplay(cardInfoList);
}, 200);
}, [cardInfoList]);
const renderAlarmInfo = () => {
if (showAlarm) {
return (
<Row
style={{
marginTop: '-15px',
}}
>
<Col>
<GFIAlarm
title="Lost connection with server"
onClose={() => {
setShowAlarm(false);
}}
/>
</Col>
</Row>
);
}
return <></>;
};
return (
<Container className="single-page account-page-sub-container">
{renderAlarmInfo()}
<Row>
<Col
sm={4}
style={{
minWidth: '330px',
}}
>
<Row>
<Col>
<Alert variant="success">
<Alert.Heading>
{' '}
Data from {totalRepos} different GitHub repositories{' '}
</Alert.Heading>
</Alert>
</Col>
</Row>
<Row>
<Col>
<ListGroup
style={{
marginBottom: '10px',
}}
>
{renderProjectsInfos(infoList)}
</ListGroup>
</Col>
</Row>
<Row>
<GFIPagination
pageIdx={pageIdx}
toPage={(pageNum) => toPage(pageNum)}
pageNums={pageNums()}
onFormInput={(target) => onFormInput(target)}
onPageBtnClicked={() => onPageBtnClicked()}
maxPagingCount={3}
needPadding
needInputArea
/>
</Row>
</Col>
<Col sm={8}>
<RepoGraphContainer
info={
'monthly_stars' in cardInfoListToDisplay
? cardInfoListToDisplay.monthly_stars
: []
}
title="Stars By Month"
/>
<RepoGraphContainer
info={
'monthly_issues' in cardInfoListToDisplay
? cardInfoListToDisplay.monthly_issues
: []
}
title="Issues By Month"
/>
<RepoGraphContainer
info={
'monthly_commits' in cardInfoListToDisplay
? cardInfoListToDisplay.monthly_commits
: []
}
title="Commits By Month"
/>
</Col>
</Row>
</Container>
);
}
interface RepoInfoCardProps {
initInfo: {
language?: string;
name?: string;
owner?: string;
monthly_stars: any[];
};
nowActive: number;
index: number;
callback: (idx: number) => void;
}
function RepoInfoCard(props: RepoInfoCardProps) {
const [isActive, setIsActive] = useState(false);
const [idx] = useState(props.index);
useEffect(() => {
setIsActive(props.nowActive === idx);
}, [props.nowActive, idx]);
const getStars = (monthly_stars: any[]) => {
let counter = 0;
monthly_stars.forEach((value) => {
if (value.count && checkIsNumber(value.count)) {
counter += Number(value.count);
}
});
return counter;
};
return (
<ListGroup.Item
action
as="button"
onClick={() => props.callback(idx)}
variant={isActive ? 'primary' : 'light'}
>
<Row>
<Col
style={{
fontWeight: 'bold',
textDecoration: isActive ? 'underline' : 'none',
}}
sm={9}
>
{' '}
{props.initInfo.name}{' '}
</Col>
<Col sm={3}>
<Badge
pill
style={{ position: 'absolute', right: '5px', top: '5px' }}
>
{' '}
Stars: {getStars(props.initInfo.monthly_stars)}{' '}
</Badge>
</Col>
</Row>
<Row>
<Col sm={9}> Language: {props.initInfo.language} </Col>
</Row>
<Row>
<Col sm={9}> Owner: {props.initInfo.owner} </Col>
</Row>
</ListGroup.Item>
);
}

View File

@ -1,13 +0,0 @@
const reportWebVitals = (onPerfEntry) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -1,5 +0,0 @@
// 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

@ -1,42 +0,0 @@
import { combineReducers, createStore, Reducer } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import {
AccountNavState,
accountNavStateReducer,
GlobalProgressBarState,
globalProgressBarStateReducer,
loginReducer,
MainPageLangTagSelectedState,
mainPageLangTagSelectedStateReducer,
showMainPagePopoverReducer,
} from './reducers';
import { RepoShouldDisplayPopoverState } from '../pages/main/GFIRepoDisplayView';
const persistConfig = {
key: 'root',
storage,
blacklist: [],
};
const persistReducers = persistReducer(persistConfig, loginReducer);
const combinedReducers = combineReducers({
loginReducer: persistReducers,
mainPopoverReducer: showMainPagePopoverReducer,
globalProgressBarReducer: globalProgressBarStateReducer,
mainPageLangTagSelectedStateReducer,
accountNavStateReducer,
});
export const store = createStore(combinedReducers);
export const persistor = persistStore(store);
export interface GFIRootReducers {
loginReducer: any;
mainPopoverReducer: RepoShouldDisplayPopoverState;
globalProgressBarReducer: GlobalProgressBarState;
accountNavStateReducer: AccountNavState;
mainPageLangTagSelectedStateReducer: MainPageLangTagSelectedState;
}

View File

@ -1,8 +0,0 @@
import { store } from './configureStorage';
export const userInfo = () => ({
hasLogin: store.getState().loginReducer.hasLogin,
name: store.getState().loginReducer.name,
githubLogin: store.getState().loginReducer.loginName,
githubToken: store.getState().loginReducer.token,
});

View File

@ -1,226 +0,0 @@
import { Reducer } from 'redux';
import { RepoShouldDisplayPopoverState } from '../pages/main/GFIRepoDisplayView';
export type LoginState = {
hasLogin: boolean;
id?: string | number;
loginName?: string;
name?: string;
token?: string;
avatar?: string;
};
const initialLoginState: LoginState = {
hasLogin: false,
};
const LOGIN = 'LOGIN';
const LOGOUT = 'LOGOUT';
export const createLogoutAction = () => {
return {
type: LOGOUT,
};
};
export const createLoginAction = (
id: string,
loginName: string,
name: string,
token: string,
avatar: string
) => {
return {
type: LOGIN,
id,
loginName,
name,
token,
avatar,
};
};
export interface LoginAction {
type: 'LOGIN';
id?: string | number;
loginName?: string;
name?: string;
token?: string;
avatar?: string;
}
export interface LogoutAction {
type: 'LOGOUT';
}
export const loginReducer: Reducer<LoginState, LoginAction | LogoutAction> = (
state = initialLoginState,
action: LoginAction | LogoutAction
) => {
switch (action.type) {
case LOGIN: {
return {
hasLogin: true,
id: action.id,
loginName: action.loginName,
name: action.name,
token: action.token,
avatar: action.avatar,
};
}
case LOGOUT:
return { hasLogin: false };
default:
return state;
}
};
type POPOVER_ACTION_TYPE = 'POPOVER';
const POPOVER_ACTION_TYPE: POPOVER_ACTION_TYPE = 'POPOVER';
export interface PopoverAction extends RepoShouldDisplayPopoverState {
type: POPOVER_ACTION_TYPE;
}
export const createPopoverAction: (
p?: RepoShouldDisplayPopoverState
) => PopoverAction = (p) => {
return {
type: 'POPOVER',
shouldDisplayPopover: p ? p.shouldDisplayPopover : false,
popoverComponent: p ? p.popoverComponent : undefined,
popoverID: p ? p.popoverID : undefined,
};
};
const initialPopover: RepoShouldDisplayPopoverState = {};
export const showMainPagePopoverReducer: Reducer<
RepoShouldDisplayPopoverState,
PopoverAction
> = (state = initialPopover, action) => {
if (action.type === POPOVER_ACTION_TYPE) {
return {
shouldDisplayPopover: action.shouldDisplayPopover,
popoverComponent: action.popoverComponent,
popoverID: action.popoverID,
};
}
return state;
};
export interface GlobalProgressBarState {
hidden: boolean;
}
const initialProgressBarState: GlobalProgressBarState = {
hidden: true,
};
type PROGRESS_BAR_ACTION_TYPE = 'PROGRESSBAR';
const PROGRESS_BAR_ACTION_TYPE: PROGRESS_BAR_ACTION_TYPE = 'PROGRESSBAR';
export interface ProgressBarAction extends GlobalProgressBarState {
type: PROGRESS_BAR_ACTION_TYPE;
}
export const createGlobalProgressBarAction: (
p?: GlobalProgressBarState
) => ProgressBarAction = (p) => {
let hidden = p?.hidden;
if (hidden === undefined) {
hidden = true;
}
return {
type: 'PROGRESSBAR',
hidden,
};
};
export const globalProgressBarStateReducer: Reducer<
GlobalProgressBarState,
ProgressBarAction
> = (state = initialProgressBarState, action) => {
if (action.type === 'PROGRESSBAR') {
let { hidden } = action;
if (hidden === undefined) {
hidden = true;
}
return {
hidden,
};
}
return state;
};
export interface AccountNavState {
show: boolean;
}
type ACCOUNT_NAV_ACTION_TYPE = 'ACCOUNT_NAV';
const ACCOUNT_NAV_ACTION_TYPE: ACCOUNT_NAV_ACTION_TYPE = 'ACCOUNT_NAV';
export interface AccountNavStateAction extends AccountNavState {
type: ACCOUNT_NAV_ACTION_TYPE;
}
const initialAccountNavState: AccountNavState = {
show: false,
};
export const createAccountNavStateAction: (
p: AccountNavState
) => AccountNavStateAction = (p) => {
return {
type: 'ACCOUNT_NAV',
show: p.show,
};
};
export const accountNavStateReducer: Reducer<
AccountNavState,
AccountNavStateAction
> = (state = initialAccountNavState, action) => {
if (action.type === ACCOUNT_NAV_ACTION_TYPE) {
return {
show: action.show,
};
}
return state;
};
type MAIN_LANG_SELECT_ACTION_TYPE = 'MAIN_LANG_SELECT';
const MAIN_LANG_SELECT_ACTION_TYPE: MAIN_LANG_SELECT_ACTION_TYPE =
'MAIN_LANG_SELECT';
export interface MainPageLangTagSelectedState {
tagSelected?: string;
}
export interface MainPageLangTagSelectedAction
extends MainPageLangTagSelectedState {
type: MAIN_LANG_SELECT_ACTION_TYPE;
}
const initMainPageLangTagSelectedState: MainPageLangTagSelectedState = {};
export const createMainPageLangTagSelectedAction: (
p: MainPageLangTagSelectedState
) => MainPageLangTagSelectedAction = (p) => {
return {
type: MAIN_LANG_SELECT_ACTION_TYPE,
tagSelected: p.tagSelected,
};
};
export const mainPageLangTagSelectedStateReducer: Reducer<
MainPageLangTagSelectedState,
MainPageLangTagSelectedAction
> = (state = initMainPageLangTagSelectedState, action) => {
if (action.type === MAIN_LANG_SELECT_ACTION_TYPE) {
return {
tagSelected: action.tagSelected,
};
}
return state;
};

File diff suppressed because it is too large Load Diff

View File

@ -1,73 +0,0 @@
import { GFIRepoSearchingFilterType } from './pages/main/mainHeader';
import { RepoSort } from './model/api';
export const checkIsNumber = (val: string | number | undefined) => {
const reg = /^\d+.?\d*/;
if (typeof val === 'number') {
val = val.toString();
}
if (val) {
return reg.test(val);
}
return false;
};
export const checkIsPercentage = (val: string) => {
return /^\d+(\.\d+)?%$/.test(val);
};
// export const checkIsGitRepoURL = (val: string) => {
// const isGitUrl = require('is-git-url');
// return isGitUrl(val);
// };
// ↑ above shouldn't work with browsers
export const checkIsGitRepoURL = (val: string) => {
return /((git|ssh|http(s)?)|(git@[\w\.]+))(:(\/\/)?)([\w\.@\:/\-~]+)(\.git)?(\/)?/.test(
val
);
};
export const defaultFontFamily =
'-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif';
export const monospaceFontFamily = 'Consolas, monaco, monospace';
export const checkHasUndefinedProperty = (obj: any) => {
for (const key in obj) {
if (obj[key] === undefined) return true;
}
return false;
};
const filterNames = {
'popularity': 'Number of Stars',
'median_issue_resolve_time': 'Issue Resolution Time',
'newcomer_friendly': '% of Issues Resolved by New Contributors',
'gfis': '# of Predicted Good First Issues',
};
const nameToFilter = Object.keys(filterNames).reduce((acc, cur) => {
acc[filterNames[cur]] = cur;
return acc;
}, {} as { [key: string]: string });
/** convert semantic filter names -> backend args */
export const convertFilter = (s: string): RepoSort | undefined => {
if (Object.keys(filterNames).includes(s)) {
return s as RepoSort;
} else if (Object.keys(nameToFilter).includes(s)) {
return nameToFilter[s] as RepoSort;
} else {
console.error('invalid filter name', s, nameToFilter, filterNames);
return undefined;
}
};
export const checkIsValidUrl = (url: string) => {
try {
return Boolean(new URL(url));
} catch (e) {
return false;
}
};

View File

@ -1,104 +0,0 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"lib": ["DOM", "ESNext"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "ESNext" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
"types": ["vite/client"], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": false /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into portal `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true,
/* Skip type checking all .d.ts files. */
"jsx": "react-jsx"
},
"exclude": ["build", "node_modules"]
}

View File

@ -1,38 +0,0 @@
import { defineConfig, loadEnv } from 'vite';
import { splitVendorChunkPlugin } from 'vite';
import react from '@vitejs/plugin-react';
import { version } from './package.json';
process.env.REACT_APP_VERSION = version;
export default defineConfig(({command, mode}) => {
let env = loadEnv(mode, process.cwd(), 'REACT_APP_');
const processEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith('REACT_APP_')));
env = { ...env, ...processEnv };
console.log(mode, env);
let clientPort = undefined;
if ("GFIBOT_HTTPS_PORT" in process.env) {
clientPort = parseInt(process.env.GFIBOT_HTTPS_PORT);
}
return {
plugins: [
react(),
splitVendorChunkPlugin(),
],
envPrefix: 'REACT_APP_',
build: {
outDir: 'build',
},
define: {
__APP_ENV__: env.APP_ENV,
'process.env': env,
},
server: {
hmr: {
clientPort: clientPort,
},
}
}
});