2
0
mirror of https://github.com/frappe/books.git synced 2024-11-08 14:50:56 +00:00

Move to Vue

- First cut
This commit is contained in:
Faris Ansari 2018-06-01 18:05:51 +05:30
parent d920bcb4bd
commit 0887c4e74c
42 changed files with 1626 additions and 8 deletions

18
.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"]
}
}
}

5
.eslintignore Normal file
View File

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

30
.eslintrc.js Normal file
View File

@ -0,0 +1,30 @@
// 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',
'semi': 'off'
}
}

10
.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": {}
}
}

41
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'
))
})
})

54
build/check-versions.js Normal file
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)
}
}

101
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')
})
}
}

22
build/vue-loader.conf.js Normal file
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,92 @@
'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: {
'vue$': 'vue/dist/vue.esm.js',
'@': 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'
}
}

95
build/webpack.dev.conf.js Executable file
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)
}
})
})

149
build/webpack.prod.conf.js Normal file
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
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"'
})

81
config/index.js Normal file
View File

@ -0,0 +1,81 @@
'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: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true
}
},
// 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: false,
// 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: '/',
/**
* 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
config/prod.env.js Normal file
View File

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

7
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"'
})

12
index.html Normal file
View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Frappe Accounting</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

View File

@ -14,21 +14,89 @@
"license": "MIT",
"scripts": {
"test": "mocha tests",
"start": "nodemon server.js",
"build": "rollup -c",
"watch": "rollup -c --watch",
"server": "node start.js",
"watch:server": "nodemon start.js",
"electron": "EIO_WS_ENGINE=ws electron main.js",
"electron-pack": "electron-packager . --overwrite",
"postinstall": "electron-builder install-app-deps"
"install-native-deps": "electron-builder install-app-deps",
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"build": "node build/build.js"
},
"dependencies": {
"frappejs": "^0.0.7"
"bootstrap": "^4.1.1",
"frappejs": "^0.0.7",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
"devDependencies": {
"electron": "1.8.4",
"electron-builder": "^20.6.2",
"electron-packager": "^11.2.0"
}
"electron-packager": "^11.2.0",
"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",
"sass-loader": "^7.0.1",
"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"
]
}

View File

@ -8,7 +8,7 @@ module.exports = {
async start() {
await server.start({
backend: 'sqlite',
connectionParams: { dbPath: 'test.db' },
connectionParams: { dbPath: 'test.db', enableCORS: true },
staticPath: path.resolve(__dirname, '../www'),
models: require('../models')
})

49
src/App.vue Normal file
View File

@ -0,0 +1,49 @@
<template>
<div id="app">
<frappe-desk>
<router-view :key="$route.path" />
</frappe-desk>
</div>
</template>
<script>
import frappe from 'frappejs';
import HTTPClient from 'frappejs/backends/http';
import Observable from 'frappejs/utils/observable';
import common from 'frappejs/common';
import coreModels from 'frappejs/models';
import models from '../models';
import io from 'socket.io-client';
import Desk from '@/components/Desk';
frappe.init();
frappe.registerLibs(common);
frappe.registerModels(coreModels);
frappe.registerModels(models);
const server = 'localhost:8000';
frappe.fetch = window.fetch.bind();
frappe.db = new HTTPClient({ server });
const socket = io.connect(`http://${server}`);
frappe.db.bindSocketClient(socket);
frappe.registerModels(models);
frappe.docs = new Observable();
frappe.getSingle('SystemSettings');
window.frappe = frappe;
export default {
name: 'App',
components: {
FrappeDesk: Desk
}
}
</script>
<style lang="scss">
@import "~bootstrap/scss/bootstrap";
html {
font-size: 14px;
}
</style>

BIN
src/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

24
src/components/Desk.vue Normal file
View File

@ -0,0 +1,24 @@
<template>
<div class="frappe-desk row no-gutters">
<frappe-sidebar></frappe-sidebar>
<frappe-main>
<frappe-navbar></frappe-navbar>
<slot></slot>
</frappe-main>
</div>
</template>
<script>
import Sidebar from './Sidebar';
import Main from './Main';
import Navbar from './Navbar';
export default {
components: {
FrappeSidebar: Sidebar,
FrappeMain: Main,
FrappeNavbar: Navbar
}
};
</script>
<style>
</style>

94
src/components/Form.vue Normal file
View File

@ -0,0 +1,94 @@
<template>
<keep-alive>
<div class="frappe-form">
<form-actions
v-if="shouldRenderForm"
:doctype="doctype" :name="name"
@save="save"
/>
<form-layout
v-if="shouldRenderForm"
:doc="doc"
:fields="meta.fields"
@field-change="updateDoc"
/>
<not-found v-else />
</div>
</keep-alive>
</template>
<script>
import frappe from 'frappejs';
import FormLayout from './FormLayout';
import FormActions from './FormActions';
export default {
name: 'Form',
props: ['doctype', 'name'],
components: {
FormActions,
FormLayout
},
data() {
return {
doc: null,
notFound: false,
invalid: false
}
},
computed: {
meta() {
return frappe.getMeta(this.doctype);
},
shouldRenderForm() {
return this.name && this.doc && !this.notFound;
}
},
async created() {
if (!this.name) return;
try {
this.doc = await frappe.getDoc(this.doctype, this.name);
} catch(e) {
this.notFound = true;
}
},
methods: {
async save() {
if (!this.checkValidity()) {
this.invalid = true;
return;
}
try {
let oldName = this.doc.name;
if (this.doc._notInserted) {
await this.doc.insert();
} else {
await this.doc.update();
}
// frappe.ui.showAlert({ message: frappe._('Saved'), color: 'green' });
if (oldName !== this.doc.name) {
this.$router.push(`/edit/${this.doctype}/${this.doc.name}`);
return;
}
} catch (e) {
console.error(e);
// frappe.ui.showAlert({ message: frappe._('Failed'), color: 'red' });
return;
}
},
updateDoc(fieldname, value) {
this.$data[fieldname] = value;
this.doc.set(fieldname, value);
},
checkValidity() {
return true;
},
}
};
</script>
<style>
.frappe-form {
height: calc(100vh - 50px);
}
</style>

View File

@ -0,0 +1,11 @@
<template>
<div class="frappe-form-actions d-flex justify-content-between align-items-center p-3 border-bottom">
<h5 class="m-0">{{ name }}</h5>
<button class="btn btn-primary btn-sm" @click="$emit('save')">Save</button>
</div>
</template>
<script>
export default {
props: ['doctype', 'name']
}
</script>

View File

@ -0,0 +1,34 @@
<template>
<form class="frappe-form-layout p-3">
<frappe-control
v-for="docfield in fields"
:key="docfield.fieldname"
:docfield="docfield"
:value="$data[docfield.fieldname]"
@change="$emit('field-change', docfield.fieldname, $event)"
/>
</form>
</template>
<script>
import FrappeControl from './controls/FrappeControl'
export default {
name: 'FormLayout',
props: ['doc', 'fields'],
data() {
const dataObj = {};
for (let field of this.fields) {
dataObj[field.fieldname] = this.doc[field.fieldname];
}
return dataObj;
},
created() {
this.doc.on('change', ({ doc, fieldname }) => {
this[fieldname] = doc[fieldname];
});
},
components: {
FrappeControl
}
}
</script>

View File

@ -0,0 +1,113 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<ul>
<li>
<a
href="https://vuejs.org"
target="_blank"
>
Core Docs
</a>
</li>
<li>
<a
href="https://forum.vuejs.org"
target="_blank"
>
Forum
</a>
</li>
<li>
<a
href="https://chat.vuejs.org"
target="_blank"
>
Community Chat
</a>
</li>
<li>
<a
href="https://twitter.com/vuejs"
target="_blank"
>
Twitter
</a>
</li>
<br>
<li>
<a
href="http://vuejs-templates.github.io/webpack/"
target="_blank"
>
Docs for This Template
</a>
</li>
</ul>
<h2>Ecosystem</h2>
<ul>
<li>
<a
href="http://router.vuejs.org/"
target="_blank"
>
vue-router
</a>
</li>
<li>
<a
href="http://vuex.vuejs.org/"
target="_blank"
>
vuex
</a>
</li>
<li>
<a
href="http://vue-loader.vuejs.org/"
target="_blank"
>
vue-loader
</a>
</li>
<li>
<a
href="https://github.com/vuejs/awesome-vue"
target="_blank"
>
awesome-vue
</a>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

76
src/components/List.vue Normal file
View File

@ -0,0 +1,76 @@
<template>
<keep-alive>
<div class="frappe-list">
<list-actions :doctype="doctype" @new="newDoc"></list-actions>
<ul class="list-group">
<list-item v-for="doc of data" :key="doc.name"
:id="doc.name" :isActive="doc.name === $route.params.name"
@click.native="openForm(doc.name)"
@keypress.native="selectAboveListItem"
>
{{ doc[meta.titleField || 'name'] }}
</list-item>
</ul>
</div>
</keep-alive>
</template>
<script>
import frappe from 'frappejs';
import ListActions from './ListActions';
import ListItem from './ListItem';
export default {
name: 'List',
props: ['doctype'],
components: {
ListActions,
ListItem
},
data() {
return {
data: [],
activeItem: ''
}
},
computed: {
meta() {
return frappe.getMeta(this.doctype);
}
},
async mounted() {
const data = await frappe.db.getAll({
doctype: this.doctype,
fields: ['name', ...this.meta.keywordFields]
});
this.data = data;
},
methods: {
async newDoc() {
let doc = await frappe.getNewDoc(this.doctype);
this.$router.push(`/edit/${this.doctype}/${doc.name}`);
},
openForm(name) {
this.activeItem = name;
this.$router.push(`/edit/${this.doctype}/${name}`);
},
selectAboveListItem(index) {
console.log(index);
// this.openForm(this.data[index - 1].name);
}
}
}
</script>
<style lang="scss" scoped>
@import "../styles/variables";
.list-group-item {
border-left: none;
border-right: none;
border-radius: 0;
}
.list-group-item:not(.active):hover {
background-color: $light;
}
</style>

View File

@ -0,0 +1,11 @@
<template>
<div class="frappe-list-actions d-flex justify-content-between align-items-center p-3 border-bottom">
<h5 class="m-0">{{ doctype }} List</h5>
<button class="btn btn-primary btn-sm" @click="$emit('new')">New</button>
</div>
</template>
<script>
export default {
props: ['doctype']
}
</script>

View File

@ -0,0 +1,32 @@
<template>
<div class="frappe-list-form row no-gutters">
<div class="col-4 border-right">
<frappe-list :doctype="doctype" />
</div>
<div class="col-8">
<frappe-form v-if="name" :doctype="doctype" :name="name" />
</div>
</div>
</template>
<script>
import List from './List';
import Form from './Form';
export default {
data() {
return {
doctype: this.$route.params.doctype,
name: this.$route.params.name
}
},
components: {
FrappeList: List,
FrappeForm: Form
}
}
</script>
<style>
.frappe-list-form {
min-height: calc(100vh - 57px);
}
</style>

View File

@ -0,0 +1,14 @@
<template>
<div :class="['list-group-item d-flex align-items-center', isActive ? 'active' : '']">
<div class="custom-control custom-checkbox d-flex">
<input type="checkbox" class="custom-control-input" :id="id">
<label class="custom-control-label" :for="id"></label>
</div>
<slot></slot>
</div>
</template>
<script>
export default {
props: ['id', 'isActive']
}
</script>

5
src/components/Main.vue Normal file
View File

@ -0,0 +1,5 @@
<template>
<main class="frappe-main col-10">
<slot></slot>
</main>
</template>

View File

@ -0,0 +1,7 @@
<template>
<nav class="frappe-navbar navbar navbar-light bg-light row no-gutters border-bottom border-top">
<form class="form-inline col-4 pr-3">
<input type="search" name="search" class="form-control shadow-none w-100" placeholder="Search...">
</form>
</nav>
</template>

View File

@ -0,0 +1,12 @@
<template>
<div class="frappe-not-found d-flex align-items-center justify-content-center">
<div class="alert alert-danger">
The page you are looking for is not found
</div>
</div>
</template>
<style>
.frappe-not-found {
height: 100%;
}
</style>

View File

@ -0,0 +1,75 @@
<template>
<div class="frappe-sidebar col-2 bg-light border-right">
<div class="navbar border-bottom">
<div class="navbar-text">
TennisMart
</div>
</div>
<div class="my-3" v-for="(sidebarGroup, index) in sidebarConfig" :key="index">
<h6 v-if="sidebarGroup.title" class="sidebar-heading nav-link text-muted text-uppercase m-0">
{{ sidebarGroup.title }}
</h6>
<nav class="nav flex-column">
<li class="nav-item">
<a v-for="item in sidebarGroup.items" :key="item.route"
:href="item.route"
:class="['nav-link', isActive(item) ? 'text-light bg-primary' : 'text-dark']"
>
{{ item.label }}
</a>
</li>
</nav>
</div>
</div>
</template>
<script>
export default {
data() {
return {
sidebarConfig: [
{
items: [
{
label: 'ToDo', route: '#/list/ToDo'
}
]
},
{
title: 'Masters',
items: [
{
label: 'Item', route: '#/list/Item'
},
{
label: 'Party', route: '#/list/Party'
}
]
},
{
title: 'Reports',
items: [
{
label: 'General Ledger', route: '#/report/general-ledger'
}
]
}
]
}
},
methods: {
isActive(item) {
return this.$route.path === item.route.slice(1);
}
}
}
</script>
<style>
.frappe-sidebar {
min-height: calc(100vh);
}
.sidebar-heading {
font-size: 0.8rem;
}
</style>

View File

@ -0,0 +1,59 @@
<script>
import Awesomplete from 'awesomplete';
import Data from './Data';
export default {
extends: Data,
created() {
this.setupAwesomplete();
},
methods: {
setupAwesomplete() {
const input = this.$refs.input;
this.awesomplete = new Awesomplete(input, {
minChars: 0,
maxItems: 99,
filter: () => true,
sort: (a, b) => {
if (a.value === '__newitem' || b.value === '__newitem') {
return -1;
}
return a.value > b.value;
}
});
// rebuild the list on input
this.input.addEventListener('input', async event => {
let list = await this.getList(this.input.value);
// action to add new item
list.push({
label: frappe._('+ New {0}', this.label),
value: '__newItem'
});
this.awesomplete.list = list;
});
// new item action
this.input.addEventListener('awesomplete-select', async e => {
if (e.text && e.text.value === '__newItem') {
e.preventDefault();
const newDoc = await frappe.getNewDoc(this.getTarget());
const formModal = await frappe.desk.showFormModal(
this.getTarget(),
newDoc.name
);
if (formModal.form.doc.meta.hasField('name')) {
formModal.form.doc.set('name', this.input.value);
}
formModal.once('save', async () => {
await this.updateDocValue(formModal.form.doc.name);
});
}
});
}
}
};
</script>

View File

@ -0,0 +1,54 @@
<script>
export default {
render(h) {
return this.getWrapperElement(h);
},
props: ['docfield', 'value'],
computed: {
id() {
return this.docfield.fieldname + '-'
+ document.querySelectorAll(`[data-fieldname="${this.docfield.fieldname}"]`).length;
}
},
methods: {
getWrapperElement(h) {
return h('div', {
class: ['form-group'],
attrs: {
'data-fieldname': this.docfield.fieldname
}
}, [this.getLabelElement(h), this.getInputElement(h)]);
},
getLabelElement(h) {
return h('label', {
attrs: {
for: this.id
},
domProps: {
textContent: this.docfield.label
}
});
},
getInputElement(h) {
return h('input', {
class: ['form-control'],
attrs: this.getInputAttrs(),
on: {
change: (e) => {
this.$emit('change', e.target.value)
}
},
ref: 'input'
})
},
getInputAttrs() {
return {
id: this.id,
type: 'text',
placeholder: '',
value: this.value
}
}
}
}
</script>

View File

@ -0,0 +1,8 @@
<script>
import Base from './Base';
export default {
name: 'Data',
extends: Base
}
</script>

View File

@ -0,0 +1,24 @@
<template>
<component :is="component" :docfield="docfield" :value="value" @change="$emit('change', $event)"/>
</template>
<script>
import Data from './Data';
import Select from './Select';
import Text from './Text';
import Autocomplete from './Autocomplete';
export default {
props: ['docfield', 'value'],
computed: {
component() {
return {
Data,
Select,
Text,
Autocomplete,
Link: Autocomplete
}[this.docfield.fieldtype];
}
}
}
</script>

View File

@ -0,0 +1,34 @@
<script>
import Base from './Base';
export default {
extends: Base,
methods: {
getInputElement(h) {
const options = this.docfield.options.map(option =>
h('option', {
attrs: {
key: option,
selected: option === this.value
},
domProps: {
textContent: option
}
})
);
return h('select', {
class: ['form-control'],
attrs: {
id: this.id
},
on: {
change: (e) => {
this.$emit('change', e.target.value)
}
},
ref: 'input'
}, options)
}
}
}
</script>

View File

@ -0,0 +1,26 @@
<script>
import Base from './Base';
export default {
extends: Base,
methods: {
getInputElement(h) {
return h('textarea', {
class: ['form-control'],
attrs: {
id: this.id,
rows: 3
},
domProps: {
value: this.value
},
on: {
change: (e) => {
this.$emit('change', e.target.value)
}
},
ref: 'input'
});
}
}
}
</script>

18
src/main.js Normal file
View File

@ -0,0 +1,18 @@
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import NotFound from './components/NotFound';
Vue.config.productionTip = false
Vue.component('not-found', NotFound);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})

40
src/router/index.js Normal file
View File

@ -0,0 +1,40 @@
import Vue from 'vue'
import Router from 'vue-router'
import ListAndForm from '@/components/ListAndForm'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/list/:doctype',
name: 'List',
component: ListAndForm
},
{
path: '/edit/:doctype/:name',
name: 'Form',
component: ListAndForm
}
// {
// path: '/tree/:doctype',
// name: '',
// component: ''
// },
// {
// path: '/table/:doctype',
// name: '',
// component: ''
// },
// {
// path: '/print/:doctype/:name',
// name: '',
// component: ''
// },
// {
// path: '/new/:doctype',
// name: '',
// component: ''
// }
]
})

View File

@ -0,0 +1,2 @@
@import "~bootstrap/scss/functions";
@import "~bootstrap/scss/variables";