chore: 前端项目基于v1.2.2初始化

This commit is contained in:
maxmon 2021-04-20 01:43:46 +08:00
parent e6179c116b
commit d7a4de38fe
37 changed files with 12206 additions and 0 deletions

18
fe/.babelrc Normal file
View File

@ -0,0 +1,18 @@
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-vue-jsx", "transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"]
}
}
}

9
fe/.editorconfig Normal file
View File

@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

5
fe/.eslintignore Normal file
View File

@ -0,0 +1,5 @@
/build/
/config/
/dist/
/*.js
/test/unit/coverage/

29
fe/.eslintrc.js Normal file
View File

@ -0,0 +1,29 @@
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
// allow async-await
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}

17
fe/.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
.DS_Store
node_modules/
/dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
/test/unit/coverage/
/test/e2e/reports/
selenium-debug.log
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln

10
fe/.postcssrc.js Normal file
View File

@ -0,0 +1,10 @@
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {}
}
}

30
fe/README.md Normal file
View File

@ -0,0 +1,30 @@
# dw-tool-ner
> Datawhale's ner tool.
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
# run unit tests
npm run unit
# run e2e tests
npm run e2e
# run all tests
npm test
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).

41
fe/build/build.js Normal file
View File

@ -0,0 +1,41 @@
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})

View File

@ -0,0 +1,54 @@
'use strict'
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
const versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version),
versionRequirement: packageConfig.engines.node
}
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
const warnings = []
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (let i = 0; i < warnings.length; i++) {
const warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}

BIN
fe/build/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

101
fe/build/utils.js Normal file
View File

@ -0,0 +1,101 @@
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options)
for (const extension in loaders) {
const loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
exports.createNotifierCallback = () => {
const notifier = require('node-notifier')
return (severity, errors) => {
if (severity !== 'error') return
const error = errors[0]
const filename = error.file && error.file.split('!').pop()
notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
}

View File

@ -0,0 +1,22 @@
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}

View File

@ -0,0 +1,91 @@
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'@': resolve('src'),
}
},
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}

View File

@ -0,0 +1,95 @@
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})

View File

@ -0,0 +1,149 @@
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig

7
fe/config/dev.env.js Normal file
View File

@ -0,0 +1,7 @@
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})

80
fe/config/index.js Normal file
View File

@ -0,0 +1,80 @@
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/v1/': {
target: 'http://39.102.94.103:9060/',
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/dw-tool-ner/v1.2.2/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}

4
fe/config/prod.env.js Normal file
View File

@ -0,0 +1,4 @@
'use strict'
module.exports = {
NODE_ENV: '"production"'
}

7
fe/config/test.env.js Normal file
View File

@ -0,0 +1,7 @@
'use strict'
const merge = require('webpack-merge')
const devEnv = require('./dev.env')
module.exports = merge(devEnv, {
NODE_ENV: '"testing"'
})

20
fe/index.html Normal file
View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>dw-tool-ner</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
<style>
html, body {
display: inline-block;
margin: 0;
width: 100%;
height: 100%;
}
</style>
</body>
</html>

90
fe/package.json Normal file
View File

@ -0,0 +1,90 @@
{
"name": "dw-tool-ner",
"version": "1.0.0",
"description": "Datawhale's ner tool.",
"author": "maxmon",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"unit": "jest --config test/unit/jest.conf.js --coverage",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit test/e2e/specs",
"build": "node build/build.js"
},
"dependencies": {
"element-ui": "^2.15.1",
"less": "^4.1.1",
"less-loader": "^8.0.0",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-eslint": "^8.2.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-jest": "^21.0.2",
"babel-loader": "^7.1.1",
"babel-plugin-dynamic-import-node": "^1.2.0",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.22.0",
"chalk": "^2.0.1",
"chromedriver": "^2.27.2",
"copy-webpack-plugin": "^4.0.1",
"cross-spawn": "^5.0.1",
"css-loader": "^0.28.0",
"eslint": "^4.15.0",
"eslint-config-standard": "^10.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^3.0.1",
"eslint-plugin-vue": "^4.0.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^2.30.1",
"jest": "^22.0.4",
"jest-serializer-vue": "^0.3.0",
"nightwatch": "^0.9.12",
"node-notifier": "^5.1.2",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"selenium-server": "^3.0.1",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-jest": "^1.0.2",
"vue-loader": "^13.3.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"webpack": "^3.6.0",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-server": "^2.9.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}

27
fe/src/App.vue Normal file
View File

@ -0,0 +1,27 @@
<template>
<div id="app">
<router-view class="router-view"/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style scoped>
#app {
flex-direction: column;
width: 100%;
height: 100%;
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
.router-view {
height: 100%;
}
</style>

BIN
fe/src/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@ -0,0 +1,758 @@
<template>
<div>
<span class="home" @click="goHome">whaleAnno</span>
<h1 class="out-title">{{projectName}}{{projectType}}</h1>
<div class="layout" @dragover="stopPrev" @drop="setFiles($event)">
<div class="left">
<div class="file-list">
<div v-for="file in files" :key="file" @click="setNowText(file)"
:class="['file', nowFile===file?'selected':'', nersCache[file]&&nersCache[file].length?'checked':'', ].join(' ')"
>
{{ file }}
</div>
</div>
<div class="out-btn" @click="outAllNers">导出json结果</div>
</div>
<div class="right">
<div class="title">
<span>{{ nowFile }}</span>
<div class="type-box">
<span v-for="type in typeList" :key="type" @click="setType(type)" @contextmenu="delType(type, $event)" :class="nowType===type?'type selected':'type'"
:style="{
backgroundColor: types[type] ? types[type].color : '#fff'
}"
@mouseover="setFocus(type)"
@mouseleave="setFocus('')"
>
<input class="color-input" :value="types[type].color" type="color" @change="changeColor(type, $event)" @click.stop/>
{{ type }} {{ fastTypeKey[type] ? `${fastTypeKey[type]}` : '' }}
</span>
<input class="type-input" placeholder="新增标签" @blur="addType" @keypress="typeInput"/>
</div>
</div>
<div id="ner-box" class="ner-box" @mouseup="setMode('')" @mouseleave="setMode('');setFocus('')" @keydown="setTypeByFastKey" @mouseover="setFocus('ner-box')">
<div class="word-rect-area">
<span class="rect" v-for="(word, idx) in nowNers" :key="idx">
<span v-for="(w, i) in word.name" :key="`${word}${w}${i}`">
<!-- <span class="ner-type"
v-if="i===0"
:style="{
left: `${((word.start+i)%columnWordCount)*20}px`,
top: `${((word.start+i)/columnWordCount|0)*35 - 14}px`,
}"
>{{word.type}}</span> -->
<span class="ner-anchor"
v-if="i === 0 || ((word.start%columnWordCount)+i) % columnWordCount === 0"
:style="{
border: '1px solid #ccc',
position: 'absolute',
display: 'inline-block',
left: `${((word.start+i)%columnWordCount)*20 + (word.isSmall && i === 0 ? 2 : 0)}px`,
top: `${((word.start+i)/columnWordCount|0)*35 + (word.isSmall ? 0 : -2)}px`,
width: `${(Math.min(word.end-(word.start+i), columnWordCount, columnWordCount - (word.start+i)%columnWordCount))*20 - (word.isSmall && i === 0 ? 4 : 0)}px`,
height: `${word.isSmall?18:22}px`,
background: `${types[word.type]?types[word.type]['color']:'000000'}`,
lineHeight: '25px',
borderTopLeftRadius: `${(i===0)?6:0}px`,
borderBottomLeftRadius: `${(i===0)?6:0}px`,
borderLeft: `${i===0?1:0} solid #ccc`,
borderTopRightRadius: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length <= columnWordCount)?6:0}px`,
borderBottomRightRadius: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length <= columnWordCount)?6:0}px`,
borderRight: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length < columnWordCount)?1:0} solid #ccc`
}"></span>
</span>
</span>
</div>
<span class="word" v-for="(word, idx) in nowText" :key="idx" @contextmenu="stopPrev" @mousedown="startSelect(idx, $event)" @mousemove="pointWord(idx)"
>
{{ word }}
</span>
</div>
<div class="page-btn-box">
<button class="page-btn" @click="changePage(-1)" @mouseover="setFocus('page-up')" @mouseleave="setFocus('')">上一页 {{ fastTypeKey['page-up'] ? `${fastTypeKey['page-up']}` : '' }}</button>
<button class="page-btn" @click="changePage(+1)" @mouseover="setFocus('page-down')" @mouseleave="setFocus('')">下一页 {{ fastTypeKey['page-down'] ? `${fastTypeKey['page-down']}` : '' }}</button>
<button class="page-btn"
:disabled="!nersCache[nowFile] || JSON.stringify(nersCache[nowFile]) === JSON.stringify(ners)"
@click="save" @mouseover="setFocus('save')" @mouseleave="setFocus('')"
>保存 {{ fastTypeKey['save'] ? `${fastTypeKey['save']}` : '' }}</button>
</div>
</div>
<div class="result-box">
<div class="result" v-for="(ner, idx) in ners" :key="idx"
:class="nowType===ner.type?'result selected':'result'"
:style="{
backgroundColor: types[ner.type] ? types[ner.type].color : `#fff`,
}"
>
<span class="result-type">{{ ner.type }}</span>
<span class="result-name">{{ ner.name }}</span>
</div>
</div>
</div>
</div>
</template>
<script>
function getColor () {
const idxs = '0123456789abcdef'
let color = '#'
for (let i = 0; i < 6; i += 1) {
color += idxs[Math.random() * idxs.length | 0]
}
return color
}
function get (url, cb) {
query('GET', url, '', cb)
}
function post (url, data, cb) {
query('POST', url, data, cb)
}
function query (method, url, data = '', cb) {
var xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.setRequestHeader('content-type', 'application/json')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const result = JSON.parse(xhr.responseText)
if (result.errCode !== 0) {
alert(result.errMsg)
} else {
cb && cb(result.info)
}
}
}
xhr.send(JSON.stringify(data))
}
get('/v1/index', function (data) {
console.log('data', data)
})
function updateType2Server (projectName, typeList, types) {
const entityTypes = typeList.map((type) => {
return {
type,
color: types[type].color
}
})
post('/v1/project/update_entity_types', {
projectName: projectName,
entityTypes: JSON.stringify(entityTypes)
})
}
export default {
name: 'NER',
data () {
return {
projectName: '', //
projectType: '', //
columnWordCount: 10, //
files: [ //
],
textDic: { //
},
startIdx: -1, //
endIdx: -1, // endendIdx+1
nowFile: '', //
nowText: '', //
ners: [], //
nowNer: {}, //
nowType: 'person', //
typeList: ['person', 'location', 'organiztion'], //
nowFocus: '', // //
fastKeyType: {}, //
fastTypeKey: {}, //
types: { //
'person': {
color: '#e61490'
},
'location': {
color: '#0aab8a'
},
'organiztion': {
color: '#2770cd'
}
},
wordsType: [], //
//
wordsOutType: [], //
nersCache: { //
},
mode: '' // 'select'
}
},
computed: {
wordColor: function (...args) {
return '#ff0000'
},
nowNers: function () {
if (this.nowNer) {
return [...this.ners, this.nowNer]
}
return this.ners
}
},
methods: {
goHome: function () {
this.$router.push({path: '/'})
},
save: function () {
const that = this
//
post('/v1/anno/create', {
projectName: that.projectName,
fileName: that.nowFile,
annoDetails: JSON.stringify(that.ners)
})
that.$set(that.nersCache, that.nowFile, [...that.ners])
},
/**
* 选中目标文件
* @param name 文件名
*/
setNowText: function (newFile) {
const that = this
that.save()
that.nowFile = newFile
that.nowText = that.textDic[newFile]
const hasCache = !!that.nersCache[newFile]
that.$set(that, 'ners', that.nersCache[newFile] ? [...that.nersCache[newFile]] : [])
that.flushWordsType()
get(`/v1/anno/query?projectName=${that.projectName}&fileName=${newFile}`, function (info) {
// 线
if (!hasCache && info.annoDetails) {
that.$set(that, 'ners', JSON.parse(info.annoDetails))
that.$set(that.nersCache, that.nowFile, [...that.ners])
that.flushWordsType()
}
//
that.$set(that.textDic, newFile, info.fileContent)
that.nowText = that.textDic[newFile]
})
},
changePage: function (d) {
const nowIdx = this.files.indexOf(this.nowFile)
let newIdx = nowIdx + d
if (newIdx < 0) newIdx = 0
if (newIdx >= this.files.length) newIdx = this.files.length - 1
this.setNowText(this.files[newIdx])
},
/**
* 标注文本
* @param idx 点击文字的定位
*/
pointWord: function (idx, config = {}) {
if (this.mode === 'select') {
this.endIdx = idx
const type = this.nowType
const start = Math.min(this.startIdx, this.endIdx)
const end = Math.max(this.startIdx, this.endIdx) + 1
const name = this.nowText.substring(start, end)
this.$set(this, 'nowNer', { name, type, start, end, isMove: !config.isDefaultClick })
return idx
}
},
/**
* 配置标注类型
* @param 类型
*/
setType: function (type, ev) {
this.$set(this, 'nowType', type)
},
delType: function (type, ev) {
const that = this
ev.preventDefault() //
//
const newTypes = {}
const newTypeList = []
const { typeList, types } = that
for (let i = 0; i < typeList.length; i++) {
const srcType = typeList[i]
if (type !== srcType) {
newTypeList.push(srcType)
newTypes[srcType] = types[srcType]
}
}
that.typeList = newTypeList
that.types = newTypes
that.flushWordsType()
updateType2Server(that.projectName, that.typeList, that.types)
},
/**
* 增加类型
* @param 类型
*/
addType: function (ev) {
const that = this
const newType = ev.target.value
ev.target.value = ''
if (!newType) return false
if (that.types[newType]) return false
that.$set(that.types, newType, {
color: getColor()
})
that.typeList.push(newType)
updateType2Server(that.projectName, that.typeList, that.types)
},
typeInput: function (ev) {
if (ev.code === 'Enter' || ev.code === 'NumpadEnter') {
this.addType(ev)
}
},
setMode: function (mode) {
//
if (this.mode === 'select') {
this.endSelect()
}
this.mode = mode
},
flushWordsType: function () {
const ners = JSON.parse(JSON.stringify(this.ners))
if (this.nowNer) ners.push(this.nowNer)
this.wordsType = []
for (let i = 0; i < ners.length; i += 1) {
const ner = ners[i]
for (let j = ner.start; j < ner.end; j += 1) {
this.wordsType[j] = ner.type
}
}
this.$set(this, 'wordsType', this.wordsType)
//
this.wordsOutType = []
for (let i = 0; i < ners.length; i += 1) {
const ner = ners[i]
let isNeedOut = false
for (let j = ner.start; j < ner.end; j += 1) {
if (ner.type !== this.wordsType[j]) {
isNeedOut = true
break
}
}
if (isNeedOut) {
for (let j = ner.start; j < ner.end; j += 1) {
this.wordsOutType[j] = ner.type
}
}
}
this.$set(this, 'wordsOutType', this.wordsOutType)
},
startSelect: function (idx, event) {
if (event.which === 3) {
event.preventDefault()
//
const ners = this.ners
for (let i = ners.length - 1; i >= 0; i -= 1) {
const ner = ners[i]
if (idx >= ner.start && idx < ner.end) {
ners.splice(i, 1)
this.$set(this, 'ners', ners)
this.flushWordsType()
return true
}
}
return true
}
this.setMode('select')
this.$set(this, 'nowNer', {})
this.startIdx = idx
this.endIdx = idx
this.pointWord(idx, {isDefaultClick: true})
},
checkIsRepeat: function (tarNer) {
for (let i = 0; i < this.ners.length; i += 1) {
const ner = this.ners[i]
if (ner.start === tarNer.start && ner.end === tarNer.end) {
return true
}
}
return false
},
endSelect: function () {
const isRepeat = this.checkIsRepeat(this.nowNer)
if (!isRepeat && this.nowNer.isMove) {
delete this.nowNer.isMove
this.ners.push(this.nowNer)
this.$set(this, 'ners', this.ners.sort((a, b) => {
return (a.start - b.start) + (b.end - a.end) * 0.001
}))
}
this.$set(this, 'nowNer', undefined)
this.flushWordsType()
this.startIdx = -1
},
stopPrev: function (event) {
event.preventDefault()
},
setFiles: function (event) {
//
event.stopPropagation()
event.preventDefault()
//
var data = event.dataTransfer
var files = data.files
//
this.processFiles(files)
},
processFiles: function (files) {
var that = this
that.$set(that, 'files', [])
that.$set(that, 'textDic', {})
for (let i = 0; i < files.length; i += 1) {
const file = files[i]
// FileReader
const reader = new FileReader()
//
reader.onload = function (e) {
// 使URLdropBox
// dropBox.style.backgroundImage = "url('" + e.target.result + "')";
//
that.$set(that.files, i, file.name)
that.$set(that.textDic, file.name, e.target.result)
}
//
// reader.readAsDataURL(file)
//
reader.readAsText(file, 'UTF-8')
// reader.readAsText(file, 'GB2321')
}
},
outAllNers () {
this.nersCache[this.nowFile] = this.ners
const out = []
for (const fileName in this.nersCache) {
const file = fileName
const text = this.textDic[fileName]
const entity = this.nersCache[fileName]
out.push({ file, text, entity })
}
this.saveTxt(`${Date.now()}.json`, JSON.stringify(out))
},
saveTxt (fileName, content) {
var element = document.createElement('a')
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content))
element.setAttribute('download', fileName)
element.style.display = 'none'
document.body.appendChild(element)
element.click()
document.body.removeChild(element)
},
setFastKey (event) {
console.log(event)
},
setTypeByFastKey (event) {
console.log(event)
},
setFocus (tar) {
this.nowFocus = tar
},
//
changeColor (tarType, ev) {
const that = this
console.log(tarType, ev.target.value)
that.$set(that.types[tarType], 'color', ev.target.value)
updateType2Server(that.projectName, that.typeList, that.types)
}
},
watch: {
ners: function () {
// ner
let nowSmallAreaEnd
for (let i = 0; i < this.ners.length; i++) {
const ner = this.ners[i]
ner.isSmall = false
if (nowSmallAreaEnd) {
if (ner.start <= nowSmallAreaEnd) {
ner.isSmall = true
}
}
if (!nowSmallAreaEnd) nowSmallAreaEnd = ner.end - 1
nowSmallAreaEnd = Math.max(nowSmallAreaEnd, ner.end - 1)
}
}
},
mounted () {
const that = this
console.log(that.$route)
const { projectName, projectType, entityTypes } = that.$route.query
if (projectName) {
that.projectName = projectName
that.projectType = projectType
//
that.entityTypes = entityTypes ? JSON.parse(entityTypes) : []
const types = {}
that.typeList = that.entityTypes.map((entityType) => {
types[entityType.type] = {
color: entityType.color
}
return entityType.type
})
that.types = types
get(`/v1/files/query?projectName=${projectName}&pageNumber=1&pageSize=99999999`, function (info) {
that.$set(that, 'files', info)
})
}
function calcColumnWordCount () {
const nerBox = document.getElementById('ner-box')
const nerBoxWidth = nerBox.offsetWidth
return (nerBoxWidth - 2 * 15) / 20 | 0
}
that.$set(that, 'columnWordCount', calcColumnWordCount())
window.onresize = function () {
that.$set(that, 'columnWordCount', calcColumnWordCount())
}
//
window.onkeydown = function (ev) {
if (that.nowFocus) {
const { key } = ev
if (that.nowFocus === 'ner-box') {
//
const type = that.fastKeyType[key]
if (type) {
if (type === 'page-up') {
//
that.changePage(-1)
} else if (type === 'page-down') {
//
that.changePage(+1)
} else if (type === 'save') {
//
that.save()
} else {
//
const type = that.fastKeyType[key]
that.setType(type)
}
}
} else {
//
const oldKey = that.fastTypeKey[that.nowFocus]
if (oldKey) {
that.$set(that.fastKeyType, oldKey, undefined)
}
//
that.$set(that.fastKeyType, key, that.nowFocus)
// ->
const typeKey = {}
for (const key in that.fastKeyType) {
const type = that.fastKeyType[key]
typeKey[type] = key
}
that.$set(that, 'fastTypeKey', typeKey)
}
}
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.home {
position: absolute;
top: 0;
left: 0;
padding: 5px 10px;
color: #fff;
cursor: pointer;
}
.home:hover {
opacity: .6;
}
.out-title {
display: inline-block;
background: #1161ca;
color: white;
margin: 0;
width: 100%;
height: 92px;
line-height: 92px;
border-bottom: 2px solid #ccc;
box-sizing: border-box;
vertical-align: middle;
}
.layout {
display: flex;
flex-direction: row;
height: calc(100% - 92px);
}
.title {
padding: 0 12px;
text-align: left;
}
.left {
position: relative;
color: white;
width: 120px;
background: #054ba8;
}
.left .file {
margin: 12px 0;
cursor: pointer;
}
.left .file.checked {
color: #ccc;
}
.left .file.selected {
background: #033271;
z-index: 5;
}
.left .file-list {
overflow: auto;
height: calc(100% - 41px);
}
.left .out-btn {
position: absolute;
display: inline-block;
bottom: 0;
left: 0;
right: 0;
height: 41px;
line-height: 41px;
vertical-align: middle;
margin: auto;
cursor: pointer;
background: #054ba8;
}
.left .out-btn:hover {
opacity: .6;
}
.right {
padding: 12px 0;
display: flex;
flex: 1;
flex-direction: column;
user-select: none;
}
.type-box {
display: inline;
line-height: 40px;
}
.type,
.type-input,
.page-btn {
display: inline-block;
margin-left: 10px;
padding: 0 4px;
min-width: 100px;
height: 32px;
font-size: 18px;
line-height: 30px;
border-radius: 4px;
background: #eee;
/* opacity: .6; */
vertical-align: middle;
outline:none;
}
.page-btn {
cursor: pointer;
opacity: 1;
}
.page-btn:active {
opacity: 0.6;
}
.type-input {
width: 100px;
background: white;
}
.type {
box-sizing: content-box;
/* box-shadow: 2px 2px 0px #ccc; */
border: 1px solid #ccc;
border-bottom: 3px solid #ccc;
}
.type.selected,
.result.selected {
position: relative;
opacity: 1 !important;
background: white;
border: 0;
}
.type.selected {
transform: translateX(0px) translateY(2px);
border: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
.ner-box {
position: relative;
flex: 1;
padding: 14px;
margin: 14px;
border: 1px solid #ccc;
text-align: left;
/* font-size: 0; */
}
.ner-box .word {
display: inline-block;
position: relative;
margin-bottom: 15px;
width: 20px;
height: 20px;
line-height: 20px;
vertical-align: bottom;
box-sizing: border-box;
text-align: center;
font-size: 16px;
z-index: 4;
}
.ner-box .ner-type {
position: absolute;
top: -14px;
left: 0;
font-size: 12px;
line-height: 15px;
vertical-align: bottom;
z-index: 1;
word-break: keep-all;
background: white;
}
.ner-box .ner-anchor {
z-index: 2;
}
.result-box {
width: 120px;
}
.result {
overflow: hidden;
padding: 0 4px;
height: 22px;
text-align: left;
}
.result-type,
.result-name {
width: 30%;
display: inline-block;
overflow: hidden;
vertical-align: top;
line-height: 22px;
}
.result-name {
width: calc(100% - 30% - 8px);
}
.word-rect-area {
position: absolute;
top: 14px;
right: 14px;
left: 14px;
bottom: 14px;
z-index: 3;
pointer-events: none;
}
.word-rect-area .rect {
position: absolute;
pointer-events: none;
}
.color-input {
margin: 0;
outline: none;
border: 0px;
padding: 0;
width: 18px;
height: 22px;
line-height: 32px;
background-color: #0000;
}
</style>

View File

@ -0,0 +1,230 @@
<template>
<div>
<h1 class="out-title"><span class="home" @click="goHome">whaleAnno</span></h1>
<div class="layout">
<div v-if="page==='list'" class="project-box">
<div class="project-box-titile">
<h3 class="inner-title">我的项目</h3>
<div class="btn-area">
<button class="button" @click="toEdit()">新建项目</button>
</div>
</div>
<div class="list-box">
<div v-if="projects.length === 0" class="project" style="border:none;color:#ccc;">暂无</div>
<div class="project" v-for="project in projects" :key="project.projectName">
<p class="name">{{project.projectName}}</p>
<p class="type">{{project.projectType}}</p>
<div class="btn-area">
<button class="button" @click="toNerAnno(project)">开始标注</button>
<button class="button" @click="toEdit(project)">配置</button>
</div>
</div>
</div>
</div>
<div v-if="page==='edit' || page==='create'" class="edit-box">
<p>名称<input class="name-input" type="text" name="name" @change="setName" :value="name" :disabled="page==='edit'"/></p>
<p>类型
<select class="type-input" name="type" @change="setType" :value="type">
<option value ="命名实体识别">命名实体识别</option>
</select>
</p>
<p class="edit-box-btn-area">
<button class="button" @click="submit">提交</button>
<button class="button" @click="toList">取消</button>
</p>
</div>
</div>
</div>
</template>
<script>
function get (url, cb) {
query('GET', url, '', cb)
}
function post (url, data, cb) {
query('POST', url, data, cb)
}
function query (method, url, data = '', cb) {
var xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.setRequestHeader('content-type', 'application/json')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const result = JSON.parse(xhr.responseText)
if (result.errCode !== 0) {
alert(result.errMsg)
} else {
cb && cb(result.info)
}
}
}
xhr.send(JSON.stringify(data))
}
export default {
name: 'home',
data () {
return {
projects: [],
name: '',
type: '',
page: 'list'
}
},
computed: {
},
watch: {
name: console.log
},
methods: {
goHome () {
this.page = 'list'
},
setName (ev) {
this.name = ev.target.value
},
setType (ev) {
this.type = ev.target.value
},
submit () {
const that = this
post('/v1/project/create', {
projectName: that.name,
projectType: that.type,
entityTypes: ''
}, function () {
that.type = ''
that.name = ''
get('/v1/index', function (info) {
that.$set(that, 'projects', info)
that.name = ''
that.type = ''
that.page = 'list'
})
})
},
toNerAnno (project) {
const { projectName, projectType, entityTypes } = project
this.$router.push({path: '/NER', query: { projectName, projectType, entityTypes }})
},
toEdit (project = {}) {
console.log('project', project)
this.name = project.projectName || ''
this.type = project.projectType || ''
this.page = project.projectName ? 'edit' : 'create'
console.log(this.name, 'this.name')
},
toList () {
this.page = 'list'
}
},
mounted () {
const that = this
//
get('/v1/index', function (info) {
that.$set(that, 'projects', info)
})
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.out-title {
display: inline-block;
background: #1161ca;
color: white;
margin: 0;
width: 100%;
height: 92px;
line-height: 92px;
border-bottom: 2px solid #ccc;
box-sizing: border-box;
vertical-align: middle;
}
.home {
cursor: pointer;
}
.home:hover {
opacity: 0.6;
}
.layout {
display: flex;
flex-direction: row;
height: calc(100% - 92px);
}
.button {
color: #fff;
background-color: #1161ca;
border-radius: 4px;
border: 1px solid #ccc;
padding: 5px 10px;
}
.project-box-titile {
margin: auto;
width: 500px;
max-width: 100%;
position: relative;
}
.project-box-titile .inner-title {
margin: 0;
line-height: 60px;
height: 60px;
text-align: left;
}
.project-box {
width: 100%;
}
.list-box {
margin: auto;
width: 500px;
max-width: 100%;
}
.project {
position: relative;
display: flex;
box-sizing: border-box;
margin-top: 10px;
padding: 5px 10px;
flex-direction: column;
width: 100%;
height: 60px;
text-align: left;
border: 1px solid #ccc;
}
.project .name,
.project .type {
margin: 0;
}
.edit-box {
width: 260px;
margin: auto;
margin-top: 0;
text-align: left;
padding: 5px 10px;
}
.edit-box .name-input,
.edit-box .type-input {
margin-top: 10px;
min-width: 180px;
}
.edit-box-btn-area {
display: flex;
flex-direction: row;
justify-content: space-evenly;
margin-top: 20px;
}
.project .type {
margin-top: 5px;
font-size: 12px;
}
.btn-area {
position: absolute;
text-align: right;
right: 10px;
width: 200px;
height: 60px;
line-height: 60px;
top: 0;
}
</style>

18
fe/src/main.js Normal file
View File

@ -0,0 +1,18 @@
import Vue from 'vue'
import App from './App'
import router from './router'
import { Button, Select, Menu, MenuItem } from 'element-ui'
Vue.config.productionTip = false
Vue.use(Button)
Vue.use(Select)
Vue.use(Menu)
Vue.use(MenuItem)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
})

25
fe/src/router/index.js Normal file
View File

@ -0,0 +1,25 @@
import Vue from 'vue'
import Router from 'vue-router'
import NER from '@/components/NER'
import home from '@/components/home'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/NER',
name: 'NER',
component: NER,
props: {
entityTypes: true
}
},
{
path: '/',
name: 'home',
component: home,
props: true
}
]
})

0
fe/static/.gitkeep Normal file
View File

View File

@ -0,0 +1,27 @@
// A custom Nightwatch assertion.
// The assertion name is the filename.
// Example usage:
//
// browser.assert.elementCount(selector, count)
//
// For more information on custom assertions see:
// http://nightwatchjs.org/guide#writing-custom-assertions
exports.assertion = function (selector, count) {
this.message = 'Testing if element <' + selector + '> has count: ' + count
this.expected = count
this.pass = function (val) {
return val === this.expected
}
this.value = function (res) {
return res.value
}
this.command = function (cb) {
var self = this
return this.api.execute(function (selector) {
return document.querySelectorAll(selector).length
}, [selector], function (res) {
cb.call(self, res)
})
}
}

View File

@ -0,0 +1,46 @@
require('babel-register')
var config = require('../../config')
// http://nightwatchjs.org/gettingstarted#settings-file
module.exports = {
src_folders: ['test/e2e/specs'],
output_folder: 'test/e2e/reports',
custom_assertions_path: ['test/e2e/custom-assertions'],
selenium: {
start_process: true,
server_path: require('selenium-server').path,
host: '127.0.0.1',
port: 4444,
cli_args: {
'webdriver.chrome.driver': require('chromedriver').path
}
},
test_settings: {
default: {
selenium_port: 4444,
selenium_host: 'localhost',
silent: true,
globals: {
devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port)
}
},
chrome: {
desiredCapabilities: {
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true
}
},
firefox: {
desiredCapabilities: {
browserName: 'firefox',
javascriptEnabled: true,
acceptSslCerts: true
}
}
}
}

48
fe/test/e2e/runner.js Normal file
View File

@ -0,0 +1,48 @@
// 1. start the dev server using production config
process.env.NODE_ENV = 'testing'
const webpack = require('webpack')
const DevServer = require('webpack-dev-server')
const webpackConfig = require('../../build/webpack.prod.conf')
const devConfigPromise = require('../../build/webpack.dev.conf')
let server
devConfigPromise.then(devConfig => {
const devServerOptions = devConfig.devServer
const compiler = webpack(webpackConfig)
server = new DevServer(compiler, devServerOptions)
const port = devServerOptions.port
const host = devServerOptions.host
return server.listen(port, host)
})
.then(() => {
// 2. run the nightwatch test suite against it
// to run in additional browsers:
// 1. add an entry in test/e2e/nightwatch.conf.js under "test_settings"
// 2. add it to the --env flag below
// or override the environment flag, for example: `npm run e2e -- --env chrome,firefox`
// For more information on Nightwatch's config file, see
// http://nightwatchjs.org/guide#settings-file
let opts = process.argv.slice(2)
if (opts.indexOf('--config') === -1) {
opts = opts.concat(['--config', 'test/e2e/nightwatch.conf.js'])
}
if (opts.indexOf('--env') === -1) {
opts = opts.concat(['--env', 'chrome'])
}
const spawn = require('cross-spawn')
const runner = spawn('./node_modules/.bin/nightwatch', opts, { stdio: 'inherit' })
runner.on('exit', function (code) {
server.close()
process.exit(code)
})
runner.on('error', function (err) {
server.close()
throw err
})
})

19
fe/test/e2e/specs/test.js Normal file
View File

@ -0,0 +1,19 @@
// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage
module.exports = {
'default e2e tests': function (browser) {
// automatically uses dev Server port from /config.index.js
// default: http://localhost:8080
// see nightwatch.conf.js
const devServer = browser.globals.devServerURL
browser
.url(devServer)
.waitForElementVisible('#app', 5000)
.assert.elementPresent('.hello')
.assert.containsText('h1', 'Welcome to Your Vue.js App')
.assert.elementCount('img', 1)
.end()
}
}

7
fe/test/unit/.eslintrc Normal file
View File

@ -0,0 +1,7 @@
{
"env": {
"jest": true
},
"globals": {
}
}

30
fe/test/unit/jest.conf.js Normal file
View File

@ -0,0 +1,30 @@
const path = require('path')
module.exports = {
rootDir: path.resolve(__dirname, '../../'),
moduleFileExtensions: [
'js',
'json',
'vue'
],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
},
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
},
testPathIgnorePatterns: [
'<rootDir>/test/e2e'
],
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
setupFiles: ['<rootDir>/test/unit/setup'],
mapCoverage: true,
coverageDirectory: '<rootDir>/test/unit/coverage',
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/main.js',
'!src/router/index.js',
'!**/node_modules/**'
]
}

3
fe/test/unit/setup.js Normal file
View File

@ -0,0 +1,3 @@
import Vue from 'vue'
Vue.config.productionTip = false

View File

@ -0,0 +1,11 @@
import Vue from 'vue'
import HelloWorld from '@/components/HelloWorld'
describe('HelloWorld.vue', () => {
it('should render correct contents', () => {
const Constructor = Vue.extend(HelloWorld)
const vm = new Constructor().$mount()
expect(vm.$el.querySelector('.hello h1').textContent)
.toEqual('Welcome to Your Vue.js App')
})
})

10078
fe/yarn.lock Normal file

File diff suppressed because it is too large Load Diff