chore: remove dead files, init snake demo for preact-css

This commit is contained in:
dntzhang 2019-10-05 14:26:21 +08:00
parent a53dfff64f
commit 6fbdb2a5c1
47 changed files with 2612 additions and 719 deletions

View File

@ -1,21 +0,0 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -1,29 +0,0 @@
# vue
## Project setup
```
npm install
```
### Compiles and hot-reloads for development
```
npm run serve
```
### Compiles and minifies for production
```
npm run build
```
### Run your tests
```
npm run test
```
### Lints and fixes files
```
npm run lint
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

View File

@ -1,5 +0,0 @@
module.exports = {
presets: [
'@vue/app'
]
}

View File

@ -1,47 +0,0 @@
{
"name": "vue",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^2.6.5",
"vue": "^2.6.10",
"vuex": "^3.1.1"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^3.11.0",
"@vue/cli-plugin-eslint": "^3.11.0",
"@vue/cli-service": "^3.11.0",
"babel-eslint": "^10.0.1",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.0.0",
"vue-template-compiler": "^2.6.10"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions"
]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -1,17 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>vue</title>
</head>
<body>
<noscript>
<strong>We're sorry but vue doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

View File

@ -1,28 +0,0 @@
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue + Omis App"/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'app',
components: {
HelloWorld
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

View File

@ -1,37 +0,0 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<button @click="store.sub">-</button><span>{{state.count}}</span><button @click="store.add">+</button>
</div>
</template>
<script>
import {$v} from '../omis/omis'
export default $v({
name: 'HelloWorld',
props: {
msg: String
},
useSelf: ['count']
})
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

View File

@ -1,16 +0,0 @@
import { $v } from './omis/omis'
import App from './App.vue'
$v.render(App, '#app', new class {
data = {
count: 1
}
sub = () => {
this.data.count--
}
add = () => {
this.data.count++
}
})

View File

@ -1,232 +0,0 @@
export function obaa(target, arr, callback) {
let eventPropArr = []
if (isArray(target)) {
if (target.length === 0) {
target.__o_ = {
__r_: target,
__p_: '#'
}
}
mock(target, target)
}
for (let prop in target) {
if (target.hasOwnProperty(prop)) {
if (callback) {
if (isArray(arr) && isInArray(arr, prop)) {
eventPropArr.push(prop)
watch(target, prop, null, target)
} else if (isString(arr) && prop === arr) {
eventPropArr.push(prop)
watch(target, prop, null, target)
}
} else {
eventPropArr.push(prop)
watch(target, prop, null, target)
}
}
}
if (!target.__c_) {
target.__c_ = []
}
let propChanged = callback ? callback : arr
target.__c_.push({
all: !callback,
propChanged,
eventPropArr
})
}
let triggerStr = [
'concat',
'copyWithin',
'fill',
'pop',
'push',
'reverse',
'shift',
'sort',
'splice',
'unshift',
'size'
].join(',')
let methods = [
'concat',
'copyWithin',
'entries',
'every',
'fill',
'filter',
'find',
'findIndex',
'forEach',
'includes',
'indexOf',
'join',
'keys',
'lastIndexOf',
'map',
'pop',
'push',
'reduce',
'reduceRight',
'reverse',
'shift',
'slice',
'some',
'sort',
'splice',
'toLocaleString',
'toString',
'unshift',
'values',
'size'
]
function mock(target, root) {
methods.forEach(item => {
target[item] = function() {
let old = Array.prototype.slice.call(this, 0)
let result = Array.prototype[item].apply(
this,
Array.prototype.slice.call(arguments)
)
if (new RegExp('\\b' + item + '\\b').test(triggerStr)) {
for (let cprop in this) {
if (this.hasOwnProperty(cprop) && !isFunction(this[cprop])) {
watch(this, cprop, this.__o_.__p_, root)
}
}
//todo
onPropertyChanged(
'Array-' + item,
this,
old,
this,
this.__o_.__p_,
root
)
}
return result
}
target[
'pure' + item.substring(0, 1).toUpperCase() + item.substring(1)
] = function() {
return Array.prototype[item].apply(
this,
Array.prototype.slice.call(arguments)
)
}
})
}
function watch(target, prop, path, root) {
if (prop === '__o_') return
if (isFunction(target[prop])) return
if (!target.__o_)
target.__o_ = {
__r_: root
}
if (path !== undefined && path !== null) {
target.__o_.__p_ = path
} else {
target.__o_.__p_ = '#'
}
let currentValue = (target.__o_[prop] = target[prop])
Object.defineProperty(target, prop, {
get() {
return this.__o_[prop]
},
set(value) {
let old = this.__o_[prop]
this.__o_[prop] = value
onPropertyChanged(prop, value, old, this, target.__o_.__p_, root)
},
configurable: true,
enumerable: true
})
if (typeof currentValue === 'object') {
if (isArray(currentValue)) {
mock(currentValue, root)
if (currentValue.length === 0) {
if (!currentValue.__o_) currentValue.__o_ = {}
if (path !== undefined && path !== null) {
currentValue.__o_.__p_ = path + '-' + prop
} else {
currentValue.__o_.__p_ = '#-' + prop
}
}
}
for (let cprop in currentValue) {
if (currentValue.hasOwnProperty(cprop)) {
watch(currentValue, cprop, target.__o_.__p_ + '-' + prop, root)
}
}
}
}
function onPropertyChanged(prop, value, oldValue, target, path, root) {
if (value !== oldValue && !(nan(value) && nan(oldValue)) && root.__c_) {
let rootName = getRootName(prop, path)
for (let i = 0, len = root.__c_.length; i < len; i++) {
let handler = root.__c_[i]
if (
handler.all ||
isInArray(handler.eventPropArr, rootName) ||
rootName.indexOf('Array-') === 0
) {
handler.propChanged.call(target, prop, value, oldValue, path)
}
}
}
if (prop.indexOf('Array-') !== 0 && typeof value === 'object') {
watch(target, prop, target.__o_.__p_, root)
}
}
function isFunction(obj) {
return Object.prototype.toString.call(obj) === '[object Function]'
}
function nan(value) {
return typeof value === 'number' && isNaN(value)
}
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]'
}
function isString(obj) {
return typeof obj === 'string'
}
function isInArray(arr, item) {
for (let i = arr.length; --i > -1; ) {
if (item === arr[i]) return true
}
return false
}
function getRootName(prop, path) {
if (path === '#') {
return prop
}
return path.split('-')[1]
}
obaa.add = function(obj, prop) {
watch(obj, prop, obj.__o_.__p_, obj.__o_.__r_)
}
obaa.set = function(obj, prop, value) {
watch(obj, prop, obj.__o_.__p_, obj.__o_.__r_)
obj[prop] = value
}
//@ts-ignore
/* eslint-disable */
Array.prototype.size = function (length) {
this.length = length
}

View File

@ -1,36 +0,0 @@
import { $ } from './react'
import { $v } from './vue'
const root = getGlobal()
const omis = {
$,
$v
}
root.Omis = omis
root.omis = omis
root.Omis.version = '2.0.0'
export default omis
export { $, $v }
function getGlobal() {
if (
typeof global !== 'object' ||
!global ||
global.Math !== Math ||
global.Array !== Array
) {
return (
self ||
window ||
global ||
(function() {
return this
})()
)
}
return global
}

View File

@ -1,151 +0,0 @@
const OBJECTTYPE = '[object Object]'
const ARRAYTYPE = '[object Array]'
export function getUsing(data, paths) {
const obj = []
paths.forEach((path, index) => {
const isPath = typeof path === 'string'
if (isPath) {
obj[index] = getTargetByPath(data, path)
} else {
const key = Object.keys(path)[0]
const value = path[key]
if (typeof value === 'string') {
obj[index] = getTargetByPath(data, value)
} else {
const tempPath = value[0]
if (typeof tempPath === 'string') {
const tempVal = getTargetByPath(data, tempPath)
obj[index] = value[1] ? value[1](tempVal) : tempVal
} else {
const args = []
tempPath.forEach(path => {
args.push(getTargetByPath(data, path))
})
obj[index] = value[1].apply(null, args)
}
}
obj[key] = obj[index]
}
})
return obj
}
export function getTargetByPath(origin, path) {
const arr = path
.replace(/]/g, '')
.replace(/\[/g, '.')
.split('.')
let current = origin
for (let i = 0, len = arr.length; i < len; i++) {
current = current[arr[i]]
}
return current
}
export function getPath(obj) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
const result = {}
obj.forEach(item => {
if (typeof item === 'string') {
result[item] = true
} else {
const tempPath = item[Object.keys(item)[0]]
if (typeof tempPath === 'string') {
result[tempPath] = true
} else if (typeof tempPath[0] === 'string') {
result[tempPath[0]] = true
} else {
tempPath[0].forEach(path => (result[path] = true))
}
}
})
return result
}
return getUpdatePath(obj)
}
export function getUpdatePath(data) {
const result = {}
dataToPath(data, result)
return result
}
function dataToPath(data, result) {
Object.keys(data).forEach(key => {
result[key] = true
const type = Object.prototype.toString.call(data[key])
if (type === OBJECTTYPE) {
_objToPath(data[key], key, result)
} else if (type === ARRAYTYPE) {
_arrayToPath(data[key], key, result)
}
})
}
function _objToPath(data, path, result) {
Object.keys(data).forEach(key => {
result[path + '.' + key] = true
delete result[path]
const type = Object.prototype.toString.call(data[key])
if (type === OBJECTTYPE) {
_objToPath(data[key], path + '.' + key, result)
} else if (type === ARRAYTYPE) {
_arrayToPath(data[key], path + '.' + key, result)
}
})
}
function _arrayToPath(data, path, result) {
data.forEach((item, index) => {
result[path + '[' + index + ']'] = true
delete result[path]
const type = Object.prototype.toString.call(item)
if (type === OBJECTTYPE) {
_objToPath(item, path + '[' + index + ']', result)
} else if (type === ARRAYTYPE) {
_arrayToPath(item, path + '[' + index + ']', result)
}
})
}
export function needUpdate(diffResult, updatePath) {
for (let keyA in diffResult) {
if (updatePath[keyA]) {
return true
}
for (let keyB in updatePath) {
if (includePath(keyA, keyB)) {
return true
}
}
}
return false
}
function includePath(pathA, pathB) {
if (pathA.indexOf(pathB) === 0) {
const next = pathA.substr(pathB.length, 1)
if (next === '[' || next === '.') {
return true
}
}
return false
}
export function fixPath(path) {
let mpPath = ''
const arr = path.replace('#-', '').split('-')
arr.forEach((item, index) => {
if (index) {
if (isNaN(Number(item))) {
mpPath += '.' + item
} else {
mpPath += '[' + item + ']'
}
} else {
mpPath += item
}
})
return mpPath
}

View File

@ -1,4 +0,0 @@
export function $(options) {
}

View File

@ -1,96 +0,0 @@
import Vue from 'vue'
import Vuex from 'vuex'
import { obaa } from './obaa'
import { getPath, needUpdate, fixPath } from './path'
Vue.use(Vuex)
const components = []
const updateSelfComponents = []
export function $v(options) {
const beforeCreate = options.beforeCreate
const destroyed = options.destroyed
const use = options.use
const useSelf = options.useSelf
options.computed = options.computed || {}
options.beforeCreate = function () {
if (use) {
this.__$updatePath_ = getPath(use)
components.push(this)
}
if (useSelf) {
this.__$updateSelfPath_ = getPath(useSelf)
updateSelfComponents.push(this)
}
beforeCreate && beforeCreate.apply(this, arguments)
}
options.destroyed = function () {
for (let i = 0, len = components.length; i < len; i++) {
if (components[i] === this) {
components.splice(i, 1)
break
}
}
destroyed && destroyed.apply(this, arguments)
}
options.computed.state = function () {
return this.$store.data
}
options.computed.store = function () {
return this.$store
}
return options
}
$v.render = function (comp, renderTo, store) {
Vue.config.productionTip = false
new Vue({
render: h => h(comp),
store
}).$mount(renderTo)
obaa(store.data, (prop, val, old, path) => {
const patch = {}
patch[fixPath(path + '-' + prop)] = true
components.forEach(component => {
if (
component.__$updatePath_ &&
needUpdate(patch, component.__$updatePath_)
) {
recUpdate(component)
}
})
updateSelfComponents.forEach(component => {
if (
component.__$updateSelfPath_ &&
needUpdate(patch, component.__$updateSelfPath_)
) {
component.$forceUpdate()
}
})
})
}
function recUpdate(root) {
root.$forceUpdate()
root.$children.forEach(child => {
recUpdate(child)
})
}

View File

@ -0,0 +1,63 @@
{
"parser": "babel-eslint",
"extends": ["prettier"],
"plugins": ["prettier"],
"env": {
"browser": true,
"mocha": true,
"node": true,
"es6": true
},
"parserOptions": {
"ecmaFeatures": {
"modules": true,
"jsx": true
}
},
"globals": {
"sinon": true,
"expect": true
},
"rules": {
"prettier/prettier": "error",
"no-cond-assign": 1,
"no-empty": 0,
"no-console": 1,
"semi": [1, "never"],
"camelcase": 0,
"comma-style": 2,
"comma-dangle": [2, "never"],
"indent": ["error", 2],
"no-mixed-spaces-and-tabs": [2, "smart-tabs"],
"no-trailing-spaces": [2, { "skipBlankLines": true }],
"max-nested-callbacks": [2, 3],
"no-eval": 2,
"no-implied-eval": 2,
"no-new-func": 2,
"guard-for-in": 0,
"eqeqeq": 0,
"no-else-return": 2,
"no-redeclare": 2,
"no-dupe-keys": 2,
"radix": 2,
"strict": [2, "never"],
"no-shadow": 0,
"callback-return": [1, ["callback", "cb", "next", "done"]],
"no-delete-var": 2,
"no-undef-init": 2,
"no-shadow-restricted-names": 2,
"handle-callback-err": 0,
"no-lonely-if": 2,
"keyword-spacing": 2,
"constructor-super": 2,
"no-this-before-super": 2,
"no-dupe-class-members": 2,
"no-const-assign": 2,
"prefer-spread": 2,
"no-useless-concat": 2,
"no-var": 2,
"object-shorthand": 2,
"prefer-arrow-callback": 2,
"quotes": [1, "single"]
}
}

View File

@ -0,0 +1,69 @@
## Develop
```bash
npm install
npm start
```
## Release
```bash
npm run build
```
## Eslint + Prettier
``` bash
npm run fix
```
## Directory description
```
├─ config
├─ public
├─ scripts
├─ src
│ ├─ assets
│ ├─ elements //Store all custom elements
│ ├─ store //Store all this store of pages
│ ├─ admin.js //Entry js of compilerwill build to admin.html
│ └─ index.js //Entry js of compilerwill build to index.html
```
## Build Scripts
```json
"scripts": {
"start": "node scripts/start.js",
"build": "PUBLIC_URL=. node scripts/build.js",
"build-windows": "set PUBLIC_URL=.&& node scripts/build.js",
"fix": "eslint src --fix"
}
```
You can set up the PUBLIC_URL, such as:
```bash
...
"build": "PUBLIC_URL=https://fe.wxpay.oa.com/dv node scripts/build.js",
"build-windows": "set PUBLIC_URL=https://fe.wxpay.oa.com/dv&& node scripts/build.js",
...
```
## Switch omi and omio
Add or remove the alias config in package.json to switch omi and omio
```js
...
"alias": {
"omi": "omio"
}
...
```
## License
MIT

View File

@ -0,0 +1,28 @@
let fs = require('fs'),
fileList = [];
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
function walk(path) {
let dirList = fs.readdirSync(path);
dirList.forEach(function (item) {
if (!fs.statSync(path + '/' + item).isDirectory()) {
if (item.endsWith('\.js')) {
fileList.push(item.substr(0, item.length - 3));
}
} else {
//walk(path + '/' + item);
}
});
}
walk('./src');
module.exports = fileList;

View File

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

View File

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

View File

@ -0,0 +1,12 @@
'use strict';
const path = require('path');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
return `module.exports = ${JSON.stringify(path.basename(filename))};`;
},
};

View File

@ -0,0 +1,55 @@
'use strict';
const path = require('path');
const fs = require('fs');
const url = require('url');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveApp('src/index.js'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveApp('src/setupTests.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
};

View File

@ -0,0 +1,22 @@
'use strict';
if (typeof Promise === 'undefined') {
// Rejection tracking prevents a common issue where React gets into an
// inconsistent state due to an error, but it gets swallowed by a Promise,
// and the user has no idea what causes React's erratic future behavior.
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js');
}
// fetch() polyfill for making API calls.
require('whatwg-fetch');
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');
// In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet.
// We don't polyfill it in the browser--this is user's responsibility.
if (process.env.NODE_ENV === 'test') {
require('raf').polyfill(global);
}

View File

@ -0,0 +1,316 @@
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
const fileList = require('./entry');
const pjson = require('../package.json');
let entry = {};
let htmlWebpackPlugins = [];
fileList.forEach(function (item) {
entry[item] = [
require.resolve('./polyfills'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appSrc + '/' + item + '.js',
];
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
inject: true,
chunks: [item],
template: paths.appHtml,
filename: item + '.html'
}));
});
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: entry,
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
path: paths.appBuild,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/[name].bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
alias: pjson.alias,
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
// {
// test: /\.(js|jsx|mjs)$/,
// enforce: 'pre',
// use: [
// {
// options: {
// formatter: eslintFormatter,
// eslintPath: require.resolve('eslint'),
// },
// loader: require.resolve('eslint-loader'),
// },
// ],
// include: paths.appSrc,
// },
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
//include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
"presets": [
"@babel/preset-env",
[
"@babel/preset-react",
{
"pragma": "Preact.h", // default pragma is React.createElement
"pragmaFrag": "Preact.Fragment", // default is React.Fragment
"throwIfNamespace": false // defaults to true
}
]
],
"plugins": [
"@babel/plugin-proposal-class-properties",
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"@babel/plugin-proposal-function-bind",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-syntax-dynamic-import"
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
{
test: /[\\|\/]_[\S]*\.css$/,
use: [
'to-string-loader',
'css-loader'
]
},
{
test: /[\\|\/]_[\S]*\.less$/,
use: [
'to-string-loader',
'css-loader',
'less-loader'
]
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
...htmlWebpackPlugins,
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// Generates an `index.html` file with the <script> injected.
// new HtmlWebpackPlugin({
// inject: true,
// chunks:["index"],
// template: paths.appHtml,
// }),
// new HtmlWebpackPlugin({
// inject: true,
// chunks:["admin"],
// template:paths.appHtml,
// filename:'admin.html'
// }),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
//new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
mode: 'development'
};

View File

@ -0,0 +1,371 @@
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const miniCssExtractPlugin = require('mini-css-extract-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
const fileList = require('./entry');
const pjson = require('../package.json');
let entry = {};
let htmlWebpackPlugins = [];
fileList.forEach(function (item) {
entry[item] = [
require.resolve('./polyfills'),
paths.appSrc + '/' + item + '.js',
];
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
inject: true,
chunks:[item],
template: paths.appHtml,
filename: item + '.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}))
});
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? // Making sure that the publicPath goes back to to build folder.
{ publicPath: Array(cssFilename.split('/').length).join('../') }
: {};
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: shouldUseSourceMap ? 'source-map' : false,
// In production, we only want to load the polyfills and the app code.
entry: entry,
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
alias: pjson.alias,
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
// {
// test: /\.(js|jsx|mjs)$/,
// enforce: 'pre',
// use: [
// {
// options: {
// formatter: eslintFormatter,
// eslintPath: require.resolve('eslint'),
// },
// loader: require.resolve('eslint-loader'),
// },
// ],
// include: paths.appSrc,
// },
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works just like "file" loader but it also embeds
// assets smaller than specified size as data URLs to avoid requests.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
//include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
"presets": [
"@babel/preset-env",
[
"@babel/preset-react",
{
"pragma": "Preact.h", // default pragma is React.createElement
"pragmaFrag": "Preact.Fragment", // default is React.Fragment
"throwIfNamespace": false // defaults to true
}
]
],
"plugins": [
"@babel/plugin-proposal-class-properties",
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"@babel/plugin-proposal-function-bind",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-syntax-dynamic-import"
],
compact: true,
},
},
{
test: /[\\|\/]_[\S]*\.css$/,
use: [
'to-string-loader',
'css-loader'
]
},
{
test: /[\\|\/]_[\S]*\.less$/,
use: [
'to-string-loader',
'css-loader',
'less-loader'
]
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// "file" loader makes sure assets end up in the `build` folder.
// When you `import` an asset, you get its filename.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
// Generates an `index.html` file with the <script> injected.
...htmlWebpackPlugins,
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Minify the code.
// new webpack.optimize.UglifyJsPlugin({
// compress: {
// warnings: false,
// // Disabled because of an issue with Uglify breaking seemingly valid code:
// // https://github.com/facebookincubator/create-react-app/issues/2376
// // Pending further investigation:
// // https://github.com/mishoo/UglifyJS2/issues/2011
// comparisons: false,
// },
// mangle: {
// safari10: true,
// },
// output: {
// comments: false,
// // Turned on because emoji and regex is not minified properly using default
// // https://github.com/facebookincubator/create-react-app/issues/2488
// ascii_only: true,
// },
// sourceMap: shouldUseSourceMap,
// }),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
// new ExtractTextPlugin({
// filename: cssFilename,
// }),
new miniCssExtractPlugin({
filename: cssFilename
}),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json',
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
new SWPrecacheWebpackPlugin({
// By default, a cache-busting query parameter is appended to requests
// used to populate the caches, to ensure the responses are fresh.
// If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: 'service-worker.js',
logger(message) {
if (message.indexOf('Total precache size is') === 0) {
// This message occurs for every build and is a bit too noisy.
return;
}
if (message.indexOf('Skipping static resource') === 0) {
// This message obscures real errors so we ignore it.
// https://github.com/facebookincubator/create-react-app/issues/2612
return;
}
console.log(message);
},
minify: true,
// For unknown URLs, fallback to the index page
navigateFallback: publicUrl + '/index.html',
// Ignores URLs starting from /__ (useful for Firebase):
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
navigateFallbackWhitelist: [/^(?!\/__).*/],
// Don't precache sourcemaps (they're large) and build asset manifest:
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
mode: 'production',
optimization: {
minimize: true
}
};

View File

@ -0,0 +1,108 @@
'use strict';
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const config = require('./webpack.config.dev');
const paths = require('./paths');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const host = process.env.HOST || '0.0.0.0';
// const fileList = require('./entry');
// let rewrites = [];
// fileList.forEach(function (item) {
// rewrites.push({ from: new RegExp('^\/' + item + '.html', 'g'), to: '/build/' + item + '.html' })
// });
module.exports = function(proxy, allowedHost) {
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebookincubator/create-react-app/issues/2271
// https://github.com/facebookincubator/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through Webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
// By default files from `contentBase` will not trigger a page reload.
watchContentBase: true,
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the Webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// It is important to tell WebpackDevServer to use the same "root" path
// as we specified in the config. In development, we always serve from /.
publicPath: config.output.publicPath,
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.plugin` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebookincubator/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebookincubator/create-react-app/issues/1065
watchOptions: {
ignored: ignoredFiles(paths.appSrc),
},
// Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === 'https',
host: host,
overlay: false,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true
//rewrites: rewrites
},
public: allowedHost,
proxy,
before(app) {
// This lets us open files from the runtime error overlay.
app.use(errorOverlayMiddleware());
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432
app.use(noopServiceWorkerMiddleware());
},
};
};

View File

@ -0,0 +1,21 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
/node_modules
# 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*

View File

@ -0,0 +1,145 @@
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.2.2",
"@babel/plugin-proposal-class-properties": "^7.2.3",
"@babel/plugin-proposal-decorators": "^7.2.3",
"@babel/plugin-proposal-function-bind": "^7.2.0",
"@babel/plugin-proposal-object-rest-spread": "^7.2.0",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/plugin-transform-runtime": "^7.2.0",
"@babel/preset-env": "^7.2.3",
"@babel/preset-react": "^7.0.0",
"@babel/runtime": "^7.3.1",
"autoprefixer": "7.1.6",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "7.2.3",
"babel-jest": "20.0.3",
"babel-loader": "^8.0.5",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
"css": "^2.2.4",
"css-loader": "^1.0.1",
"dotenv": "4.0.0",
"dotenv-expand": "4.2.0",
"eslint": "^4.18.2",
"eslint-config-prettier": "^3.1.0",
"eslint-loader": "1.9.0",
"eslint-plugin-flowtype": "2.39.1",
"eslint-plugin-import": "2.8.0",
"eslint-plugin-jsx-a11y": "5.1.1",
"eslint-plugin-prettier": "^3.0.0",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"file": "^0.2.2",
"file-loader": "^2.0.0",
"fs-extra": "3.0.1",
"html-webpack-plugin": "^4.0.0-beta.5",
"jest": "20.0.4",
"less": "^3.10.0",
"less-loader": "^5.0.0",
"mini-css-extract-plugin": "^0.5.0",
"object-assign": "4.1.1",
"omi": "latest",
"omi-router": "latest",
"omio": "latest",
"omis": "^2.0.3",
"omiu": "latest",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"postcss-flexbugs-fixes": "3.2.0",
"postcss-loader": "2.0.8",
"preact": "^10.0.0",
"prettier": "^1.14.3",
"promise": "8.0.1",
"raf": "3.4.0",
"react-dev-utils": "^7.0.1",
"reomi": "latest",
"resolve": "1.6.0",
"style-loader": "0.19.0",
"sw-precache-webpack-plugin": "^0.11.5",
"to-string-loader": "^1.1.5",
"url": "^0.11.0",
"url-loader": "^1.1.2",
"webpack": "^4.28.3",
"webpack-cli": "^3.2.0",
"webpack-dev-server": "^3.1.10",
"webpack-manifest-plugin": "^2.0.4",
"webpack-merge": "^4.2.1",
"whatwg-fetch": "2.0.3"
},
"scripts": {
"start": "node scripts/start.js",
"build": "PUBLIC_URL=. node scripts/build.js",
"build-windows": "set PUBLIC_URL=.&& node scripts/build.js",
"fix": "eslint src --fix"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
},
"babel": {
"presets": [
"@babel/preset-env",
[
"@babel/preset-react",
{
"pragma": "Omi.h"
}
]
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/transform-runtime",
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"@babel/plugin-proposal-function-bind",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-syntax-dynamic-import"
]
},
"prettier": {
"singleQuote": true,
"semi": false,
"tabWidth": 2,
"useTabs": false
},
"alias": {
"react": "preact"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

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

View File

@ -0,0 +1,15 @@
{
"short_name": "Omi App",
"name": "Omi Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,150 @@
'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('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
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;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
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.publicUrl;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
);
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, 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
) {
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(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}

View File

@ -0,0 +1,107 @@
'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('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 paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
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('http://bit.ly/2mwWSwH')}`);
console.log();
}
// 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.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
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();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});

View File

@ -0,0 +1,27 @@
'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');
let argv = process.argv.slice(2);
// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
argv.push('--watch');
}
jest.run(argv);

View File

@ -0,0 +1,14 @@
body {
background: #efcc19;
padding: 0;
margin: 0;
font: 20rpx/1 HanHei SC, PingHei, PingFang SC, STHeitiSC-Light, Helvetica Neue, Helvetica, Arial, sans-serif;
overflow: hidden;
cursor: default;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-moz-font-feature-settings: "liga", "kern";
direction: ltr;
text-align: left
}

View File

@ -0,0 +1,43 @@
.game {
border: 2rpx solid #000;
padding: 10rpx 0 5rpx 0;
width: 725rpx;
margin: 10rpx auto;
background-color: #9ead86;
text-align: center;
}
.game p {
width: 725rpx;
height: 44rpx;
white-space: nowrap;
margin: 0;
padding: 0;
}
*{
box-sizing: border-box;
}
.game b {
display: inline-block;
width: 40rpx;
height: 40rpx;
padding: 4rpx;
border: 4rpx solid #879372;
margin: 0 4rpx 4rpx 0;
}
.game b.s:after {
background: #000;
}
.game b:after {
content: "";
display: block;
width: 24rpx;
height: 24rpx;
background: #879372;
overflow: hidden;
}

View File

@ -0,0 +1,25 @@
import * as Preact from 'preact'
import { $ } from 'omis'
require('../../utils/css').add(require('./_index.css'))
export default $({
render() {
const { map } = $.store.data
return <div className="game">
{map.map(row => {
return <p>
{row.map(col => {
if (col) {
return <b className='s'></b>
}
return <b></b>
})}
</p>
})}
</div>
},
use: ['map']
})

View File

@ -0,0 +1,204 @@
.r {
float: right
}
.l {
float: left
}
.clear {
clear: both
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none
}
h1{
text-align: center;
font-size: 25px;
}
.ctrl {
width: 580rpx;
height: 330rpx;
margin: 20rpx auto 0;
position: relative
}
.btn {
text-align: center;
color: #111;
position: absolute;
white-space: nowrap;
line-height: 1.6
}
.btn.small {
font-size: 16rpx
}
.btn i {
display: block;
position: relative;
border: 1rpx solid #000;
border-radius: 50%;
box-shadow: 0 3rpx 3rpx rgba(0, 0, 0, .2)
}
.btn i:after,
.btn i:before {
content: "";
display: block;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
border-radius: 50%;
box-shadow: inset 0 5rpx 10rpx hsla(0, 0%, 100%, .8)
}
.btn i:after {
box-shadow: inset 0 -5rpx 10rpx rgba(0, 0, 0, .8)
}
.btn i._23aw:before {
box-shadow: inset 0 -3rpx 6rpx hsla(0, 0%, 100%, .6)
}
.btn i._23aw:after {
box-shadow: inset 0 5rpx 5rpx rgba(0, 0, 0, .6)
}
.btn.cm-btn i {
background: #5a65f1;
background: -moz-linear-gradient(top, #6e77ef, #6e77ef)
}
.btn.pp i {
background: #2dc421;
background: -moz-linear-gradient(top, #4bc441, #4bc441)
}
.btn.reset i {
background: #dd1a1a;
background: -moz-linear-gradient(top, #dc3333, #dc3333)
}
.btn.space i {
width: 160rpx;
height: 160rpx
}
.btn i:active {
transform: scale(0.9);
}
.btn.cm-btn-dir i {
width: 100rpx;
height: 100rpx
}
.btn.small i {
width: 52rpx;
height: 52rpx;
box-shadow: 1rpx 1rpx 1rpx rgba(0, 0, 0, .2)
}
.btn.small i:after,
.btn.small i:before {
box-shadow: inset 0 3rpx 6rpx hsla(0, 0%, 100%, .8)
}
.btn.small i:after {
box-shadow: inset 0 -3rpx 6rpx rgba(0, 0, 0, .8)
}
.btn.small i._23aw:before {
box-shadow: inset 0 -1rpx 2rpx hsla(0, 0%, 100%, .6)
}
.btn.small i._23aw:after {
box-shadow: inset 0 3rpx 3rpx rgba(0, 0, 0, .7)
}
.btn.cm-btn-dir em {
display: block;
width: 0;
height: 0;
border: 8rpx solid;
border-color: transparent transparent #111;
position: absolute;
top: 50%;
left: 50%;
margin: -18rpx 0 0 -8rpx
}
.up {
top: 0rpx;
left: 374rpx;
}
.up em{
transform: translate(0rpx, 70rpx) scale(1, 2);
}
.up span {
position: absolute;
top: 5rpx;
left: 102rpx
}
.down{
top: 180rpx;
left: 374rpx;
}
.down em{
transform: translate(0rpx, -71rpx) rotate(180deg) scale(1, 2);
}
.left{
top: 90rpx;
left: 284rpx;
}
.left em{
transform: translate(60rpx, -12rpx) rotate(270deg) scale(1, 2);
}
.right{
top: 90rpx; left: 464rpx;
}
.right em{
transform: translate(-60rpx, -12rpx) rotate(90deg) scale(1, 2);
}
.space{
top: 100rpx;
left: 52rpx;
}
.reset{
top: 0rpx;
left: 156rpx;
}
.pp{
top: 0rpx;
left: 60rpx;
}

View File

@ -0,0 +1,31 @@
import * as Preact from 'preact'
import Game from '../game'
import store from '../../stores/index'
import { $ } from 'omis'
require('../../utils/css').add(require('./_index.css'))
export default $({
render() {
const { store } = $
const { paused } = store.data
return <div className="container">
<h1>[P]REACT + OMIS SNAKE</h1>
<Game></Game>
<div className="ctrl">
<div className="btn cm-btn cm-btn-dir up" onClick={store.turnUp}><i></i><em></em><span>Up</span></div>
<div className="btn cm-btn cm-btn-dir down" onClick={store.turnDown}><i></i><em></em><span>Down</span></div>
<div className="btn cm-btn cm-btn-dir left" onClick={store.turnLeft}><i></i><em></em><span >Left</span></div>
<div className="btn cm-btn cm-btn-dir right" onClick={store.turnRight}><i></i><em></em><span >Right</span></div>
<div className="btn cm-btn space" onClick={store.toggleSpeed}><i></i><span >Gear</span></div>
<div className="btn reset small" onClick={store.reset}><i ></i><span >Reset</span></div>
<div className="btn pp small" onClick={store.pauseOrPlay}><i></i><span >{paused ? 'Play' : 'Pause'}</span></div>
</div>
</div>
},
useSelf: ['paused'],
store
})

View File

@ -0,0 +1,5 @@
import * as Preact from 'preact'
import Index from './components/index'
import './assets/index.css'
Preact.render(<Index />, document.getElementById('root'))

View File

@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,124 @@
import Snake from './snake'
class Game {
constructor() {
this.map = []
this.size = 16
this.loop = null
this.interval = 500
this.paused = false
this._preDate = Date.now()
this.init()
this.onTick = null
}
init() {
this.snake = new Snake()
for (let i = 0; i < this.size; i++) {
const row = []
for (let j = 0; j < this.size; j++) {
row.push(0)
}
this.map.push(row)
}
}
tick() {
this.makeFood()
const eating = this.eat()
this.snake.move(eating)
this.mark()
}
mark() {
const map = this.map
for (let i = 0; i < this.size; i++) {
for (let j = 0; j < this.size; j++) {
map[i][j] = 0
}
}
for (let k = 0, len = this.snake.body.length; k < len; k += 2) {
this.snake.body[k + 1] %= this.size
this.snake.body[k] %= this.size
if (this.snake.body[k + 1] < 0) this.snake.body[k + 1] += this.size
if (this.snake.body[k] < 0) this.snake.body[k] += this.size
map[this.snake.body[k + 1]][this.snake.body[k]] = 1
}
if (this.food) {
map[this.food[1]][this.food[0]] = 1
}
}
start() {
this.loop = setInterval(() => {
if (Date.now() - this._preDate > this.interval) {
this._preDate = Date.now()
if (!this.paused) {
this.tick()
this.onTick && this.onTick()
}
}
}, 16)
}
stop() {
clearInterval(this.loop)
}
pause() {
this.paused = true
}
play() {
this.paused = false
}
reset() {
this.paused = false
this.interval = 500
this.snake.body = [3, 1, 2, 1, 1, 1]
this.food = null
this.snake.dir = 'right'
}
toggleSpeed() {
this.interval === 500 ? (this.interval = 150) : (this.interval = 500)
}
makeFood() {
if (!this.food) {
this.food = [this._rd(0, this.size - 1), this._rd(0, this.size - 1)]
for (let k = 0, len = this.snake.body.length; k < len; k += 2) {
if (this.snake.body[k + 1] === this.food[1]
&& this.snake.body[k] === this.food[0]) {
this.food = null
this.makeFood()
break
}
}
}
}
eat() {
for (let k = 0, len = this.snake.body.length; k < len; k += 2) {
if (this.snake.body[k + 1] === this.food[1]
&& this.snake.body[k] === this.food[0]) {
this.food = null
return true
}
}
}
_rd(from, to) {
return from + Math.floor(Math.random() * (to + 1))
}
}
export default Game

View File

@ -0,0 +1,50 @@
class Snake {
constructor() {
this.body = [3, 1, 2, 1, 1, 1]
this.dir = 'right'
}
move(eating) {
const b = this.body
if (!eating) {
b.pop()
b.pop()
}
switch (this.dir) {
case 'up':
b.unshift(b[0], b[1] - 1)
break
case 'right':
b.unshift(b[0] + 1, b[1])
break
case 'down':
b.unshift(b[0], b[1] + 1)
break
case 'left':
b.unshift(b[0] - 1, b[1])
break
default:;
}
}
turnUp() {
if (this.dir !== 'down')
this.dir = 'up'
}
turnRight() {
if (this.dir !== 'left')
this.dir = 'right'
}
turnDown() {
if (this.dir !== 'up')
this.dir = 'down'
}
turnLeft() {
if (this.dir !== 'right')
this.dir = 'left'
}
}
export default Snake

View File

@ -0,0 +1,49 @@
import Game from '../models/game'
const game = new Game()
const { snake, map } = game
game.start()
class Store {
data = {
map,
paused: false
}
turnUp() {
snake.turnUp()
}
turnRight() {
snake.turnRight()
}
turnDown() {
snake.turnDown()
}
turnLeft() {
snake.turnLeft()
}
pauseOrPlay = () => {
if (game.paused) {
game.play()
this.data.paused = false
} else {
game.pause()
this.data.paused = true
}
}
reset() {
game.reset()
}
toggleSpeed() {
game.toggleSpeed()
}
}
export default new Store()

View File

@ -0,0 +1,11 @@
export function add(css) {
const style = document.createElement('style')
style.textContent = rpx(css)
document.querySelector('head').appendChild(style)
}
function rpx(str) {
return str.replace(/([1-9]\d*|0)(\.\d*)*rpx/g, (a, b) => {
return (window.innerWidth * Number(b)) / 750 + 'px'
})
}

View File

@ -0,0 +1,391 @@
/**
* omis v2.0.0 http://omijs.org
* Observable store system for JavaScript apps.
* By dntzhang https://github.com/dntzhang
* Github: https://github.com/Tencent/omi
* MIT Licensed.
*/
import React from 'react';
function obaa(target, arr, callback) {
var eventPropArr = [];
if (isArray(target)) {
if (target.length === 0) {
target.__o_ = {
__r_: target,
__p_: '#'
};
}
mock(target, target);
}
for (var prop in target) {
if (target.hasOwnProperty(prop)) {
if (callback) {
if (isArray(arr) && isInArray(arr, prop)) {
eventPropArr.push(prop);
watch(target, prop, null, target);
} else if (isString(arr) && prop === arr) {
eventPropArr.push(prop);
watch(target, prop, null, target);
}
} else {
eventPropArr.push(prop);
watch(target, prop, null, target);
}
}
}
if (!target.__c_) {
target.__c_ = [];
}
var propChanged = callback ? callback : arr;
target.__c_.push({
all: !callback,
propChanged: propChanged,
eventPropArr: eventPropArr
});
}
var triggerStr = ['concat', 'copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'size'].join(',');
var methods = ['concat', 'copyWithin', 'entries', 'every', 'fill', 'filter', 'find', 'findIndex', 'forEach', 'includes', 'indexOf', 'join', 'keys', 'lastIndexOf', 'map', 'pop', 'push', 'reduce', 'reduceRight', 'reverse', 'shift', 'slice', 'some', 'sort', 'splice', 'toLocaleString', 'toString', 'unshift', 'values', 'size'];
function mock(target, root) {
methods.forEach(function (item) {
target[item] = function () {
var old = Array.prototype.slice.call(this, 0);
var result = Array.prototype[item].apply(this, Array.prototype.slice.call(arguments));
if (new RegExp('\\b' + item + '\\b').test(triggerStr)) {
for (var cprop in this) {
if (this.hasOwnProperty(cprop) && !isFunction(this[cprop])) {
watch(this, cprop, this.__o_.__p_, root);
}
}
//todo
onPropertyChanged('Array-' + item, this, old, this, this.__o_.__p_, root);
}
return result;
};
target['pure' + item.substring(0, 1).toUpperCase() + item.substring(1)] = function () {
return Array.prototype[item].apply(this, Array.prototype.slice.call(arguments));
};
});
}
function watch(target, prop, path, root) {
if (prop === '__o_') return;
if (isFunction(target[prop])) return;
if (!target.__o_) target.__o_ = {
__r_: root
};
if (path !== undefined && path !== null) {
target.__o_.__p_ = path;
} else {
target.__o_.__p_ = '#';
}
var currentValue = target.__o_[prop] = target[prop];
Object.defineProperty(target, prop, {
get: function get() {
return this.__o_[prop];
},
set: function set(value) {
var old = this.__o_[prop];
this.__o_[prop] = value;
onPropertyChanged(prop, value, old, this, target.__o_.__p_, root);
},
configurable: true,
enumerable: true
});
if (typeof currentValue === 'object') {
if (isArray(currentValue)) {
mock(currentValue, root);
if (currentValue.length === 0) {
if (!currentValue.__o_) currentValue.__o_ = {};
if (path !== undefined && path !== null) {
currentValue.__o_.__p_ = path + '-' + prop;
} else {
currentValue.__o_.__p_ = '#-' + prop;
}
}
}
for (var cprop in currentValue) {
if (currentValue.hasOwnProperty(cprop)) {
watch(currentValue, cprop, target.__o_.__p_ + '-' + prop, root);
}
}
}
}
function onPropertyChanged(prop, value, oldValue, target, path, root) {
if (value !== oldValue && !(nan(value) && nan(oldValue)) && root.__c_) {
var rootName = getRootName(prop, path);
for (var i = 0, len = root.__c_.length; i < len; i++) {
var handler = root.__c_[i];
if (handler.all || isInArray(handler.eventPropArr, rootName) || rootName.indexOf('Array-') === 0) {
handler.propChanged.call(target, prop, value, oldValue, path);
}
}
}
if (prop.indexOf('Array-') !== 0 && typeof value === 'object') {
watch(target, prop, target.__o_.__p_, root);
}
}
function isFunction(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
function nan(value) {
return typeof value === 'number' && isNaN(value);
}
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function isString(obj) {
return typeof obj === 'string';
}
function isInArray(arr, item) {
for (var i = arr.length; --i > -1;) {
if (item === arr[i]) return true;
}
return false;
}
function getRootName(prop, path) {
if (path === '#') {
return prop;
}
return path.split('-')[1];
}
obaa.add = function (obj, prop) {
watch(obj, prop, obj.__o_.__p_, obj.__o_.__r_);
};
obaa.set = function (obj, prop, value) {
watch(obj, prop, obj.__o_.__p_, obj.__o_.__r_);
obj[prop] = value;
};
//@ts-ignore
/* eslint-disable */
Array.prototype.size = function (length) {
this.length = length;
};
function getPath(obj) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
var result = {};
obj.forEach(function (item) {
if (typeof item === 'string') {
result[item] = true;
} else {
var tempPath = item[Object.keys(item)[0]];
if (typeof tempPath === 'string') {
result[tempPath] = true;
} else if (typeof tempPath[0] === 'string') {
result[tempPath[0]] = true;
} else {
tempPath[0].forEach(function (path) {
return result[path] = true;
});
}
}
});
return result;
}
return getUpdatePath(obj);
}
function getUpdatePath(data) {
var result = {};
dataToPath(data, result);
return result;
}
function dataToPath(data, result) {
Object.keys(data).forEach(function (key) {
result[key] = true;
var type = Object.prototype.toString.call(data[key]);
if (type === '[object Object]') {
_objToPath(data[key], key, result);
} else if (type === '[object Array]') {
_arrayToPath(data[key], key, result);
}
});
}
function _objToPath(data, path, result) {
Object.keys(data).forEach(function (key) {
result[path + '.' + key] = true;
delete result[path];
var type = Object.prototype.toString.call(data[key]);
if (type === '[object Object]') {
_objToPath(data[key], path + '.' + key, result);
} else if (type === '[object Array]') {
_arrayToPath(data[key], path + '.' + key, result);
}
});
}
function _arrayToPath(data, path, result) {
data.forEach(function (item, index) {
result[path + '[' + index + ']'] = true;
delete result[path];
var type = Object.prototype.toString.call(item);
if (type === '[object Object]') {
_objToPath(item, path + '[' + index + ']', result);
} else if (type === '[object Array]') {
_arrayToPath(item, path + '[' + index + ']', result);
}
});
}
function needUpdate(diffResult, updatePath) {
for (var keyA in diffResult) {
if (updatePath[keyA]) {
return true;
}
for (var keyB in updatePath) {
if (includePath(keyA, keyB)) {
return true;
}
}
}
return false;
}
function includePath(pathA, pathB) {
if (pathA.indexOf(pathB) === 0) {
var next = pathA.substr(pathB.length, 1);
if (next === '[' || next === '.') {
return true;
}
}
return false;
}
function fixPath(path) {
var mpPath = '';
var arr = path.replace('#-', '').split('-');
arr.forEach(function (item, index) {
if (index) {
if (isNaN(Number(item))) {
mpPath += '.' + item;
} else {
mpPath += '[' + item + ']';
}
} else {
mpPath += item;
}
});
return mpPath;
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var components = [];
var updateSelfComponents = [];
var isSelf = false;
var currentComponent = null;
function $(options) {
if (options.store) {
$.store = options.store;
obaa($.store.data, function (prop, val, old, path) {
var patch = {};
patch[fixPath(path + '-' + prop)] = true;
components.forEach(function (component) {
if (component.__$updatePath_ && needUpdate(patch, component.__$updatePath_)) {
component.setState({ __$id_: component.state.__$id_++ });
isSelf = false;
}
});
updateSelfComponents.forEach(function (component) {
if (component.__$updateSelfPath_ && needUpdate(patch, component.__$updateSelfPath_)) {
component.setState({ __$id_: component.state.__$id_++ });
isSelf = true;
currentComponent = component;
}
});
});
}
var updatePath = options.use && getPath(options.use);
var updateSelfPath = options.useSelf && getPath(options.useSelf);
return function (_React$Component) {
_inherits(_class2, _React$Component);
function _class2(props) {
_classCallCheck(this, _class2);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.state = {
__$id_: 0
};
if (updatePath) {
components.push(_this);
_this.__$updatePath_ = updatePath;
}
if (updateSelfPath) {
updateSelfComponents.push(_this);
_this.__$updateSelfPath_ = updateSelfPath;
}
return _this;
}
_class2.prototype.shouldComponentUpdate = function shouldComponentUpdate() {
if (currentComponent === this) return true;
return !isSelf;
};
_class2.prototype.render = function render() {
return options.render.apply(this, arguments);
};
return _class2;
}(React.Component);
}
function $v(options) {}
var root = getGlobal();
var omis = {
$: $,
$v: $v
};
root.Omis = omis;
root.omis = omis;
root.Omis.version = '2.0.0';
function getGlobal() {
if (typeof global !== 'object' || !global || global.Math !== Math || global.Array !== Array) {
return self || window || global || function () {
return this;
}();
}
return global;
}
export default omis;
export { $, $v };
//# sourceMappingURL=omis.esm.js.map