diff --git a/README.md b/README.md index cc03631..cd3576a 100644 --- a/README.md +++ b/README.md @@ -36,14 +36,16 @@ $ vue-native init ## NOTE: ``` +'AlertIOS', +'AsyncStorage', +'ImageStore', +'ListView', +'MaskedViewIOS', 'NetInfo', - 'AsyncStorage', - 'AlertIOS', - 'WebView', - 'ViewPagerAndroid', - 'ListView', - 'SwipeableListView', - 'Slider' +'Slider', +'SwipeableListView', +'ViewPagerAndroid', +'WebView', ``` The above modules are set to be removed from future core react-native. Hence these modules can no longer be imported from vue-native. diff --git a/build/.eslintrc b/build/.eslintrc index 33fe593..f230b5a 100644 --- a/build/.eslintrc +++ b/build/.eslintrc @@ -1,5 +1,9 @@ + { + "env": { + "es6": true, + }, "rules": { - "camelcase": 0 - } + "camelcase": 0, + }, } diff --git a/build/build.js b/build/build.js index b9cb997..7efedf4 100644 --- a/build/build.js +++ b/build/build.js @@ -16,11 +16,6 @@ if (process.argv[2]) { builds = builds.filter(b => { return filters.some(f => b.dest.indexOf(f) > -1) }) -} else { - // filter out weex builds by default - builds = builds.filter(b => { - return b.dest.indexOf('weex') === -1 - }) } build(builds) @@ -42,24 +37,27 @@ function build (builds) { function buildEntry (config) { const isProd = /min\.js$/.test(config.dest) - return rollup.rollup(config).then(bundle => { - const code = bundle.generate(config).code - if (isProd) { - var minified = (config.banner ? config.banner + '\n' : '') + uglify.minify(code, { - fromString: true, - output: { - screw_ie8: true, - ascii_only: true - }, - compress: { - pure_funcs: ['makeMap'] - } - }).code - return write(config.dest, minified, true) - } else { - return write(config.dest, code) - } - }) + const output = config.output + const { file, banner } = output + return rollup.rollup(config) + .then(bundle => bundle.generate(output)) + .then(({ output: [{ code }] }) => { + if (isProd) { + const minified = (banner ? banner + '\n' : '') + uglify.minify(code, { + fromString: true, + output: { + screw_ie8: true, + ascii_only: true + }, + compress: { + pure_funcs: ['makeMap'] + } + }).code + return write(file, minified, true) + } else { + return write(file, code) + } + }) } function write (dest, code, zip) { diff --git a/build/config.js b/build/config.js index 90f99b4..1d34ebf 100644 --- a/build/config.js +++ b/build/config.js @@ -3,10 +3,9 @@ const buble = require("rollup-plugin-buble"); const alias = require("rollup-plugin-alias"); const replace = require("rollup-plugin-replace"); const flow = require("rollup-plugin-flow-no-whitespace"); -const version = process.env.VERSION || require("../package.json").version; -const weexVersion = - process.env.WEEX_VERSION || - require("../packages/weex-vue-framework/package.json").version; +const version = + process.env.VERSION + || require("../packages/vue-native-core/package.json").version; const banner = "/*!\n" + @@ -19,15 +18,6 @@ const banner = " * Released under the MIT License.\n" + " */"; -const weexFactoryPlugin = { - intro() { - return "module.exports = function weexFactory (exports, renderer) {"; - }, - outro() { - return "}"; - } -}; - const aliases = require("./alias"); const resolve = p => { const base = p.split("/")[0]; @@ -43,154 +33,52 @@ const builds = { entry: resolve("vue-native/index.js"), dest: resolve("packages/vue-native-core/build.js"), format: "cjs", - external: ["react"] + external: ["react"], }, "vue-native-helper": { entry: resolve("vue-native/runtime/helpers.js"), dest: resolve("packages/vue-native-helper/build.js"), format: "cjs", - external: ["react", "change-case", "he", "de-indent"] + }, + "vue-native-scripts": { + entry: resolve("vue-native/scripts/index.js"), + dest: resolve("packages/vue-native-scripts/build.js"), + format: "cjs", + external: [] + .concat(Object.keys(require("../packages/vue-native-scripts/package.json").dependencies)) + .concat(Object.keys(require("../packages/vue-native-scripts/package.json").peerDependencies)), }, "vue-native-template-compiler": { entry: resolve("vue-native/compiler.js"), dest: resolve("packages/vue-native-template-compiler/build.js"), format: "cjs", - external: ["change-case", "he", "de-indent"] + external: ["change-case", "he", "de-indent"], } - // Runtime only (CommonJS). Used by bundlers e.g. Webpack & Browserify - // 'web-runtime-cjs': { - // entry: resolve('web/runtime.js'), - // dest: resolve('dist/vue.runtime.common.js'), - // format: 'cjs', - // banner - // }, - // // Runtime+compiler CommonJS build (CommonJS) - // 'web-full-cjs': { - // entry: resolve('web/runtime-with-compiler.js'), - // dest: resolve('dist/vue.common.js'), - // format: 'cjs', - // alias: { he: './entity-decoder' }, - // banner - // }, - // // Runtime only (ES Modules). Used by bundlers that support ES Modules, - // // e.g. Rollup & Webpack 2 - // 'web-runtime-esm': { - // entry: resolve('web/runtime.js'), - // dest: resolve('dist/vue.runtime.esm.js'), - // format: 'es', - // banner - // }, - // // Runtime+compiler CommonJS build (ES Modules) - // 'web-full-esm': { - // entry: resolve('web/runtime-with-compiler.js'), - // dest: resolve('dist/vue.esm.js'), - // format: 'es', - // alias: { he: './entity-decoder' }, - // banner - // }, - // // runtime-only build (Browser) - // 'web-runtime-dev': { - // entry: resolve('web/runtime.js'), - // dest: resolve('dist/vue.runtime.js'), - // format: 'umd', - // env: 'development', - // banner - // }, - // // runtime-only production build (Browser) - // 'web-runtime-prod': { - // entry: resolve('web/runtime.js'), - // dest: resolve('dist/vue.runtime.min.js'), - // format: 'umd', - // env: 'production', - // banner - // }, - // // Runtime+compiler development build (Browser) - // 'web-full-dev': { - // entry: resolve('web/runtime-with-compiler.js'), - // dest: resolve('dist/vue.js'), - // format: 'umd', - // env: 'development', - // alias: { he: './entity-decoder' }, - // banner - // }, - // // Runtime+compiler production build (Browser) - // 'web-full-prod': { - // entry: resolve('web/runtime-with-compiler.js'), - // dest: resolve('dist/vue.min.js'), - // format: 'umd', - // env: 'production', - // alias: { he: './entity-decoder' }, - // banner - // }, - // // Web compiler (CommonJS). - // 'web-compiler': { - // entry: resolve('web/compiler.js'), - // dest: resolve('packages/vue-template-compiler/build.js'), - // format: 'cjs', - // external: Object.keys(require('../packages/vue-template-compiler/package.json').dependencies) - // }, - // // Web server renderer (CommonJS). - // 'web-server-renderer': { - // entry: resolve('web/server-renderer.js'), - // dest: resolve('packages/vue-server-renderer/build.js'), - // format: 'cjs', - // external: Object.keys(require('../packages/vue-server-renderer/package.json').dependencies) - // }, - // 'web-server-renderer-webpack-server-plugin': { - // entry: resolve('server/webpack-plugin/server.js'), - // dest: resolve('packages/vue-server-renderer/server-plugin.js'), - // format: 'cjs', - // external: Object.keys(require('../packages/vue-server-renderer/package.json').dependencies) - // }, - // 'web-server-renderer-webpack-client-plugin': { - // entry: resolve('server/webpack-plugin/client.js'), - // dest: resolve('packages/vue-server-renderer/client-plugin.js'), - // format: 'cjs', - // external: Object.keys(require('../packages/vue-server-renderer/package.json').dependencies) - // }, - // // Weex runtime factory - // 'weex-factory': { - // weex: true, - // entry: resolve('weex/runtime-factory.js'), - // dest: resolve('packages/weex-vue-framework/factory.js'), - // format: 'cjs', - // plugins: [weexFactoryPlugin] - // }, - // // Weex runtime framework (CommonJS). - // 'weex-framework': { - // weex: true, - // entry: resolve('weex/framework.js'), - // dest: resolve('packages/weex-vue-framework/index.js'), - // format: 'cjs' - // }, - // // Weex compiler (CommonJS). Used by Weex's Webpack loader. - // 'weex-compiler': { - // weex: true, - // entry: resolve('weex/compiler.js'), - // dest: resolve('packages/weex-template-compiler/build.js'), - // format: 'cjs', - // external: Object.keys(require('../packages/weex-template-compiler/package.json').dependencies) - // } }; function genConfig(opts) { const config = { - entry: opts.entry, - dest: opts.dest, + input: opts.entry, + output: { + file: opts.dest, + format: opts.format, + banner: opts.banner, + name: "Vue", + }, external: opts.external, - format: opts.format, - banner: opts.banner, - moduleName: "Vue", plugins: [ replace({ - __WEEX__: !!opts.weex, - __WEEX_VERSION__: weexVersion, __VERSION__: version }), flow(), buble(), alias(Object.assign({}, aliases, opts.alias)) - ].concat(opts.plugins || []) + ].concat(opts.plugins || []), + onwarn: (msg, warn) => { + if (!/Circular/.test(msg)) { + warn(msg) + } + }, }; if (opts.env) { diff --git a/build/release-weex.sh b/build/release-weex.sh deleted file mode 100644 index 77ce1d0..0000000 --- a/build/release-weex.sh +++ /dev/null @@ -1,37 +0,0 @@ -set -e -CUR_VERSION=`node build/get-weex-version.js -c` -NEXT_VERSION=`node build/get-weex-version.js` - -echo "Current: $CUR_VERSION" -read -p "Enter new version ($NEXT_VERSION): " -n 1 -r -if ! [[ -z $REPLY ]]; then - NEXT_VERSION=$REPLY -fi - -read -p "Releasing weex-vue-framework@$NEXT_VERSION - are you sure? (y/n) " -n 1 -r -echo -if [[ $REPLY =~ ^[Yy]$ ]]; then - echo "Releasing weex-vue-framework@$NEXT_VERSION ..." - npm run lint - npm run flow - npm run test:weex - - # build - WEEX_VERSION=$NEXT_VERSION npm run build:weex - - # update package - cd packages/weex-vue-framework - npm version $NEXT_VERSION - npm publish - cd - - - cd packages/weex-template-compiler - npm version $NEXT_VERSION - npm publish - cd - - - # commit - git add src/entries/weex* - git add packages/weex* - git commit -m "[release] weex-vue-framework@$NEXT_VERSION" -fi diff --git a/package.json b/package.json index dd95fb4..c17bb49 100644 --- a/package.json +++ b/package.json @@ -30,35 +30,17 @@ "types/*.d.ts" ], "scripts": { - "dev": "rollup -w -c build/config.js --environment TARGET:web-full-dev", - "dev:cjs": "rollup -w -c build/config.js --environment TARGET:web-runtime-cjs", - "dev:esm": "rollup -w -c build/config.js --environment TARGET:web-runtime-esm", - "dev:observer": "rollup -w -c build/config.js --environment TARGET:common-observer", - "dev:parser": "rollup -w -c build/config.js --environment TARGET:template-parser", - "dev:compiler": "rollup -w -c build/config.js --environment TARGET:react-vue-template-compiler", - "dev:helper": "rollup -w -c build/config.js --environment TARGET:react-vue-helper", - "dev:react": "rollup -w -c build/config.js --environment TARGET:react-vue", - "dev:test": "karma start build/karma.dev.config.js", - "dev:ssr": "rollup -w -c build/config.js --environment TARGET:web-server-renderer", - "dev:weex": "rollup -w -c build/config.js --environment TARGET:weex-framework ", - "dev:weex:compiler": "rollup -w -c build/config.js --environment TARGET:weex-compiler ", "build": "node build/build.js", - "build:ssr": "npm run build -- vue.runtime.common.js,vue-server-renderer", - "build:weex": "npm run build -- weex-vue-framework,weex-template-compiler", "test": "npm run lint && flow check && npm run test:types && npm run test:cover && npm run test:e2e -- --env phantomjs && npm run test:ssr && npm run test:weex", "test:unit": "karma start build/karma.unit.config.js", "test:cover": "karma start build/karma.cover.config.js", "test:e2e": "npm run build -- vue.min.js && node test/e2e/runner.js", - "test:weex": "npm run build:weex && jasmine JASMINE_CONFIG_PATH=test/weex/jasmine.json", - "test:ssr": "npm run build:ssr && jasmine JASMINE_CONFIG_PATH=test/ssr/jasmine.json", "test:sauce": "npm run sauce -- 0 && npm run sauce -- 1 && npm run sauce -- 2", "test:types": "tsc -p ./types/test/tsconfig.json", "lint": "eslint src build test", "flow": "flow check", "sauce": "karma start build/karma.sauce.config.js", - "bench:ssr": "npm run build:ssr && node benchmarks/ssr/renderToString.js && node benchmarks/ssr/renderToStream.js", "release": "bash build/release.sh", - "release:weex": "bash build/release-weex.sh", "install:hooks": "ln -fs ../../build/git-hooks/pre-commit .git/hooks/pre-commit", "run-vue": "cross-env NODE_ENV=development webpack-dev-server --open --hot", "postinstall": "opencollective-postinstall" @@ -78,7 +60,7 @@ "babel-preset-flow-vue": "^1.0.0", "babel-preset-latest": "^6.0.0", "babel-preset-react": "^6.24.1", - "buble": "^0.15.2", + "buble": "^0.19.8", "chalk": "^1.1.3", "change-case": "^3.0.1", "chromedriver": "^2.21.2", @@ -129,36 +111,26 @@ "pug": "^2.0.0-rc.1", "pug-loader": "^2.3.0", "resolve": "^1.2.0", - "rollup": "^0.41.4", - "rollup-plugin-alias": "^1.2.0", - "rollup-plugin-babel": "^2.4.0", - "rollup-plugin-buble": "^0.15.0", + "rollup": "^1.17.0", + "rollup-plugin-alias": "^1.5.2", + "rollup-plugin-buble": "^0.19.8", "rollup-plugin-flow-no-whitespace": "^1.0.0", - "rollup-plugin-replace": "^1.1.0", - "rollup-watch": "^3.2.2", + "rollup-plugin-replace": "^2.2.0", "sass-loader": "^6.0.5", "selenium-server": "^2.53.1", "serialize-javascript": "^1.3.0", "typescript": "^2.1.6", - "uglify-js": "^2.6.2", + "uglify-js": "^3.6.0", "vue-loader": "^12.0.4", - "vue-template-compiler": "^2.3.2", "webpack": "^2.4.1", "webpack-dev-middleware": "^1.10.2", - "webpack-dev-server": "^2.2.0", - "weex-js-runtime": "^0.17.0-alpha4", - "weex-vdom-tester": "^0.1.4" + "webpack-dev-server": "^2.2.0" }, "dependencies": { - "element-ui": "^1.3.4", + "opencollective": "^1.0.3", "opencollective-postinstall": "^2.0.0", - "prop-types": "^15.5.8", "react": "^15.5.4", - "react-dom": "^15.5.4", - "style-loader": "^0.17.0", - "vue": "2.3.3", - "vuex": "^2.3.1", - "opencollective": "^1.0.3" + "react-dom": "^15.5.4" }, "collective": { "type": "opencollective", diff --git a/packages/vue-native-core/build.js b/packages/vue-native-core/build.js index 2842217..edf3f57 100644 --- a/packages/vue-native-core/build.js +++ b/packages/vue-native-core/build.js @@ -46,17 +46,6 @@ function isPlainObject (obj) { return toString.call(obj) === OBJECT_STRING } -/** - * Convert a value to a string that is actually rendered. - */ - - -/** - * Convert a input value to a number for persistence. - * If the conversion fails, return original string. - */ - - /** * Make a map and return a function for checking if a key * is in that map. @@ -177,11 +166,6 @@ function extend (to, _from) { return to } -/** - * Merge an Array of Objects into a single Object. - */ - - /** * Perform no operation. */ @@ -197,19 +181,6 @@ var no = function () { return false; }; */ var identity = function (_) { return _; }; -/** - * Generate a static keys string from compiler modules. - */ - - -/** - * Check if two values are loosely equal - that is, - * if they are plain objects, do they have the same shape? - */ - - - - /** * Ensure a function is called only once. */ @@ -244,6 +215,8 @@ var LIFECYCLE_HOOKS = [ /* */ + + var config = ({ /** * Option merge strategies (used in core/util/options) @@ -475,18 +448,21 @@ function handleError (err, vm, info) { } /* */ -/* globals MutationObserver */ // can we use __proto__? -var hasProto = '__proto__' in {}; +var hasProto = "__proto__" in {}; // Browser environment sniffing -var inBrowser = typeof window !== 'undefined'; -var UA = inBrowser && window.navigator && window.navigator.userAgent && window.navigator.userAgent.toLowerCase(); +var inBrowser = typeof window !== "undefined"; +var UA = + inBrowser && + window.navigator && + window.navigator.userAgent && + window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); -var isIE9 = UA && UA.indexOf('msie 9.0') > 0; -var isEdge = UA && UA.indexOf('edge/') > 0; -var isAndroid = UA && UA.indexOf('android') > 0; +var isIE9 = UA && UA.indexOf("msie 9.0") > 0; +var isEdge = UA && UA.indexOf("edge/") > 0; +var isAndroid = UA && UA.indexOf("android") > 0; var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; @@ -494,13 +470,17 @@ var supportsPassive = false; if (inBrowser) { try { var opts = {}; - Object.defineProperty(opts, 'passive', ({ - get: function get () { - /* istanbul ignore next */ - supportsPassive = true; - } - } )); // https://github.com/facebook/flow/issues/285 - window.addEventListener('test-passive', null, opts); + Object.defineProperty( + opts, + "passive", + ({ + get: function get() { + /* istanbul ignore next */ + supportsPassive = true; + } + }) + ); // https://github.com/facebook/flow/issues/285 + window.addEventListener("test-passive", null, opts); } catch (e) {} } @@ -510,38 +490,40 @@ var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ - if (!inBrowser && typeof global !== 'undefined') { + if (!inBrowser && typeof global !== "undefined") { // detect presence of vue-server-renderer and avoid // Webpack shimming the process - _isServer = global['process'].env.VUE_ENV === 'server'; + _isServer = global["process"].env.VUE_ENV === "server"; } else { _isServer = false; } } - return _isServer + return _isServer; }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ -function isNative (Ctor) { - return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) +function isNative(Ctor) { + return typeof Ctor === "function" && /native code/.test(Ctor.toString()); } var hasSymbol = - typeof Symbol !== 'undefined' && isNative(Symbol) && - typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); + typeof Symbol !== "undefined" && + isNative(Symbol) && + typeof Reflect !== "undefined" && + isNative(Reflect.ownKeys); /** * Defer a task to execute it asynchronously. */ -var nextTick = (function () { +var nextTick = (function() { var callbacks = []; var pending = false; var timerFunc; - function nextTickHandler () { + function nextTickHandler() { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; @@ -557,9 +539,11 @@ var nextTick = (function () { // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore if */ - if (typeof Promise !== 'undefined' && isNative(Promise)) { + if (typeof Promise !== "undefined" && isNative(Promise)) { var p = Promise.resolve(); - var logError = function (err) { console.error(err); }; + var logError = function (err) { + console.error(err); + }; timerFunc = function () { p.then(nextTickHandler).catch(logError); // in problematic UIWebViews, Promise.then doesn't completely break, but @@ -569,11 +553,12 @@ var nextTick = (function () { // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; - } else if (typeof MutationObserver !== 'undefined' && ( - isNative(MutationObserver) || - // PhantomJS and iOS 7.x - MutationObserver.toString() === '[object MutationObserverConstructor]' - )) { + } else if ( + typeof MutationObserver !== "undefined" && + (isNative(MutationObserver) || + // PhantomJS and iOS 7.x + MutationObserver.toString() === "[object MutationObserverConstructor]") + ) { // use MutationObserver where native Promise is not available, // e.g. PhantomJS IE11, iOS7, Android 4.4 var counter = 1; @@ -592,24 +577,24 @@ var nextTick = (function () { timerFunc = function() { var p = Promise.resolve(); p.then(nextTickHandler).catch(logError); - } + }; } else { // fallback to setTimeout /* istanbul ignore next */ timerFunc = function() { setTimeout(nextTickHandler, 0); - } + }; } } - return function queueNextTick (cb, ctx) { + return function queueNextTick(cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { - handleError(e, ctx, 'nextTick'); + handleError(e, ctx, "nextTick"); } } else if (_resolve) { _resolve(ctx); @@ -619,27 +604,27 @@ var nextTick = (function () { pending = true; timerFunc(); } - if (!cb && typeof Promise !== 'undefined') { + if (!cb && typeof Promise !== "undefined") { return new Promise(function (resolve, reject) { _resolve = resolve; - }) + }); } - } + }; })(); var _Set; /* istanbul ignore if */ -if (typeof Set !== 'undefined' && isNative(Set)) { +if (typeof Set !== "undefined" && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. - _Set = (function () { - function Set () { + _Set = /*@__PURE__*/(function () { + function Set() { this.set = Object.create(null); } Set.prototype.has = function has (key) { - return this.set[key] === true + return this.set[key] === true; }; Set.prototype.add = function add (key) { this.set[key] = true; @@ -654,15 +639,14 @@ if (typeof Set !== 'undefined' && isNative(Set)) { /* */ - -var uid$1 = 0; +var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { - this.id = uid$1++; + this.id = uid++; this.subs = []; }; @@ -709,7 +693,12 @@ function popTarget () { */ var arrayProto = Array.prototype; -var arrayMethods = Object.create(arrayProto);[ +var arrayMethods = Object.create(arrayProto) + +/** + * Intercept mutating methods and emit events + */ +;[ 'push', 'pop', 'shift', @@ -797,7 +786,7 @@ var Observer = function Observer (value) { Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { - defineReactive$$1(obj, keys[i], obj[keys[i]]); + defineReactive(obj, keys[i], obj[keys[i]]); } }; @@ -864,7 +853,7 @@ function observe (value, asRootData) { /** * Define a reactive property on an Object. */ -function defineReactive$$1 ( +function defineReactive ( obj, key, val, @@ -946,7 +935,7 @@ function set (target, key, val) { target[key] = val; return val } - defineReactive$$1(ob.value, key, val); + defineReactive(ob.value, key, val); ob.dep.notify(); return val } @@ -1317,6 +1306,8 @@ function resolveAsset ( /* */ + + function validateProp ( key, propOptions, @@ -1607,7 +1598,7 @@ var VNode = function VNode ( this.isOnce = false; }; -var prototypeAccessors = { child: {} }; +var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ @@ -1628,23 +1619,18 @@ function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } -// optimized shallow clone -// used for static nodes and slot nodes because they may be reused across -// multiple renders, cloning them avoids errors when DOM manipulations rely -// on their elm reference. - /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; - var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first - name = once$$1 ? name.slice(1) : name; + var once = name.charAt(0) === '~'; // Prefixed last, checked first + name = once ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, - once: once$$1, + once: once, capture: capture, passive: passive } @@ -1672,7 +1658,7 @@ function updateListeners ( on, oldOn, add, - remove$$1, + remove, vm ) { var name, cur, old, event; @@ -1698,15 +1684,13 @@ function updateListeners ( for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); - remove$$1(event.name, oldOn[name], event.capture); + remove(event.name, oldOn[name], event.capture); } } } /* */ -/* */ - function extractPropsFromVNodeData ( data, Ctor, @@ -1963,8 +1947,6 @@ function getFirstComponentChild (children) { /* */ -/* */ - function initEvents (vm) { vm._events = Object.create(null); @@ -1986,8 +1968,8 @@ function initEvents (vm) { var target; -function add (event, fn, once$$1) { - if (once$$1) { +function add (event, fn, once) { + if (once) { target.$once(event, fn); } else { target.$on(event, fn); @@ -2010,12 +1992,10 @@ function updateComponentListeners ( function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { - var this$1 = this; - var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { - this$1.$on(event[i], fn); + this.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); @@ -2040,8 +2020,6 @@ function eventsMixin (Vue) { }; Vue.prototype.$off = function (event, fn) { - var this$1 = this; - var vm = this; // all if (!arguments.length) { @@ -2051,7 +2029,7 @@ function eventsMixin (Vue) { // array of events if (Array.isArray(event)) { for (var i$1 = 0, l = event.length; i$1 < l; i$1++) { - this$1.$off(event[i$1], fn); + this.$off(event[i$1], fn); } return vm } @@ -2133,10 +2111,6 @@ function initLifecycle (vm) { vm._isBeingDestroyed = false; } - - - - function updateChildComponent ( vm, propsData, @@ -2250,7 +2224,6 @@ function callHook (vm, hook) { /* */ - var MAX_UPDATE_COUNT = 100; var queue = []; @@ -2390,7 +2363,7 @@ function queueWatcher (watcher) { /* */ -var uid$2 = 0; +var uid$1 = 0; /** * A watcher parses an expression, collects dependencies, @@ -2415,7 +2388,7 @@ var Watcher = function Watcher ( this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; - this.id = ++uid$2; // uid for batching + this.id = ++uid$1; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; @@ -2489,13 +2462,11 @@ Watcher.prototype.addDep = function addDep (dep) { * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { - var this$1 = this; - var i = this.deps.length; while (i--) { - var dep = this$1.deps[i]; - if (!this$1.newDepIds.has(dep.id)) { - dep.removeSub(this$1); + var dep = this.deps[i]; + if (!this.newDepIds.has(dep.id)) { + dep.removeSub(this); } } var tmp = this.depIds; @@ -2567,11 +2538,9 @@ Watcher.prototype.evaluate = function evaluate () { * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { - var this$1 = this; - var i = this.deps.length; while (i--) { - this$1.deps[i].depend(); + this.deps[i].depend(); } }; @@ -2579,8 +2548,6 @@ Watcher.prototype.depend = function depend () { * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { - var this$1 = this; - if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it @@ -2590,7 +2557,7 @@ Watcher.prototype.teardown = function teardown () { } var i = this.deps.length; while (i--) { - this$1.deps[i].removeSub(this$1); + this.deps[i].removeSub(this); } this.active = false; } @@ -2692,7 +2659,7 @@ function initProps (vm, propsOptions) { /** * react-vue change */ - defineReactive$$1(props, key, value, function () { + defineReactive(props, key, value, function () { // if (vm.$parent && !observerState.isSettingProps) { // warn( // `Avoid mutating a prop directly since the value will be ` + @@ -2704,7 +2671,7 @@ function initProps (vm, propsOptions) { // } }); } else { - defineReactive$$1(props, key, value); + defineReactive(props, key, value); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at @@ -2932,7 +2899,7 @@ function initInjections (vm) { Object.keys(result).forEach(function (key) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { - defineReactive$$1(vm, key, result[key], function () { + defineReactive(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + @@ -2941,7 +2908,7 @@ function initInjections (vm) { ); }); } else { - defineReactive$$1(vm, key, result[key]); + defineReactive(vm, key, result[key]); } }); } @@ -3267,7 +3234,8 @@ function mergeHook$1 (one, two) { // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; - var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value; + var event = (options.model && options.model.event) || 'input' + ;(data.props || (data.props = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); if (isDef(on[event])) { on[event] = [data.model.callback].concat(on[event]); @@ -3385,48 +3353,6 @@ function applyNS (vnode, ns) { /* */ -/** - * Runtime helper for rendering v-for lists. - */ - -/* */ - -/** - * Runtime helper for rendering - */ - -/* */ - -/** - * Runtime helper for resolving filters - */ - -/* */ - -/** - * Runtime helper for checking keyCodes from config. - */ - -/* */ - -/** - * Runtime helper for merging v-bind="object" into a VNode's data. - */ - -/* */ - -/** - * Runtime helper for rendering static trees. - */ - - -/** - * Runtime helper for v-once. - * Effectively it means marking the node as static with a unique key. - */ - -/* */ - function initRender (vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; @@ -3449,13 +3375,13 @@ function initRender (vm) { /* */ -var uid = 0; +var uid$2 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid - vm._uid = uid++; + vm._uid = uid$2++; var startTag, endTag; /* istanbul ignore if */ @@ -3581,17 +3507,9 @@ function dedupe (latest, sealed) { } } -/** - * react-vue change - */ -// import { renderMixin } from './render' -/** - * react-vue change - */ -// import { lifecycleMixin } from './lifecycle' -function Vue$2 (options) { +function Vue (options) { if (process.env.NODE_ENV !== 'production' && - !(this instanceof Vue$2)) { + !(this instanceof Vue)) { warn('Vue is a constructor and should be called with the `new` keyword'); } /** @@ -3608,9 +3526,9 @@ function Vue$2 (options) { this._init(options); } -initMixin(Vue$2); -stateMixin(Vue$2); -eventsMixin(Vue$2); +initMixin(Vue); +stateMixin(Vue); +eventsMixin(Vue); /** * react-vue change @@ -3621,11 +3539,11 @@ eventsMixin(Vue$2); /** * react-vue change */ -Vue$2.prototype.$nextTick = function (fn) { +Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; -Vue$2.prototype.$destroy = function (fn) { +Vue.prototype.$destroy = function (fn) { // nothing }; @@ -3808,6 +3726,8 @@ function initAssetRegisters (Vue) { /* */ + + var patternTypes = [String, RegExp]; function getComponentName (opts) { @@ -3859,10 +3779,8 @@ var KeepAlive = { }, destroyed: function destroyed () { - var this$1 = this; - - for (var key in this$1.cache) { - pruneCacheEntry(this$1.cache[key]); + for (var key in this.cache) { + pruneCacheEntry(this.cache[key]); } }, @@ -3929,7 +3847,7 @@ function initGlobalAPI (Vue) { warn: warn, extend: extend, mergeOptions: mergeOptions, - defineReactive: defineReactive$$1 + defineReactive: defineReactive }; Vue.set = set; @@ -3953,13 +3871,13 @@ function initGlobalAPI (Vue) { initAssetRegisters(Vue); } -initGlobalAPI(Vue$2); +initGlobalAPI(Vue); -Object.defineProperty(Vue$2.prototype, '$isServer', { +Object.defineProperty(Vue.prototype, '$isServer', { get: isServerRendering }); -Vue$2.version = '2.2.6'; +Vue.version = '0.0.8'; /** * Reference to mobx https://github.com/mobxjs/mobx-react-vue/blob/master/src/observer.js @@ -3969,7 +3887,7 @@ function observer (componentClass) { if (typeof componentClass === 'function' && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !React.Component.isPrototypeOf(componentClass) ) { - var ObserverComponent = (function (superclass) { + var ObserverComponent = /*@__PURE__*/(function (superclass) { function ObserverComponent () { superclass.apply(this, arguments); } @@ -4001,7 +3919,7 @@ function observer (componentClass) { } function mixinLifecycleEvents (target) { - for (var key in lifecycleMixin$1) { + for (var key in lifecycleMixin) { if (key === 'shouldComponentUpdate' && typeof target.shouldComponentUpdate === 'function') { continue @@ -4010,8 +3928,8 @@ function mixinLifecycleEvents (target) { } } -var lifecycleMixin$1 = { - componentWillMount: function componentWillMount () { +var lifecycleMixin = { + UNSAFE_componentWillMount: function UNSAFE_componentWillMount () { var cb = this.forceUpdate.bind(this); var render = this.render.bind(this); var watcher = new Watcher({ _watchers: [] }, render, cb, { lazy: true }); @@ -4033,7 +3951,7 @@ var lifecycleMixin$1 = { function patch (target, funcName) { var base = target[funcName]; - var mixinFunc = lifecycleMixin$1[funcName]; + var mixinFunc = lifecycleMixin[funcName]; target[funcName] = !base ? function () { return mixinFunc.apply(this, arguments) } : function () { @@ -4062,6 +3980,6 @@ function isObjectShallowModified (prev, next) { /** */ -Vue$2.observer = observer; +Vue.observer = observer; -module.exports = Vue$2; +module.exports = Vue; diff --git a/packages/vue-native-helper/build.js b/packages/vue-native-helper/build.js index 13f0fb4..0b8ae69 100644 --- a/packages/vue-native-helper/build.js +++ b/packages/vue-native-helper/build.js @@ -6,22 +6,22 @@ Object.defineProperty(exports, '__esModule', { value: true }); // these helpers produces better vm code in JS engines due to their // explicitness and function inlining -function isUndef(v) { +function isUndef (v) { return v === undefined || v === null } -function isDef(v) { +function isDef (v) { return v !== undefined && v !== null } -function isTrue(v) { +function isTrue (v) { return v === true } /** * Check if value is primitive */ -function isPrimitive(value) { +function isPrimitive (value) { return typeof value === 'string' || typeof value === 'number' } @@ -30,7 +30,7 @@ function isPrimitive(value) { * Objects from primitive values when we know the value * is a JSON-compliant type. */ -function isObject(obj) { +function isObject (obj) { return obj !== null && typeof obj === 'object' } @@ -40,14 +40,14 @@ function isObject(obj) { */ var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; -function isPlainObject(obj) { +function isPlainObject (obj) { return toString.call(obj) === OBJECT_STRING } /** * Convert a value to a string that is actually rendered. */ -function _toString(val) { +function _toString (val) { return val == null ? '' : typeof val === 'object' @@ -59,7 +59,7 @@ function _toString(val) { * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ -function toNumber(val) { +function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } @@ -68,7 +68,7 @@ function toNumber(val) { * Make a map and return a function for checking if a key * is in that map. */ -function makeMap( +function makeMap ( str, expectsLowerCase ) { @@ -90,7 +90,7 @@ var isBuiltInTag = makeMap('slot,component', true); /** * Remove an item from an array */ -function remove(arr, item) { +function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { @@ -103,16 +103,16 @@ function remove(arr, item) { * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; -function hasOwn(obj, key) { +function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ -function cached(fn) { +function cached (fn) { var cache = Object.create(null); - return (function cachedFn(str) { + return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) @@ -147,8 +147,8 @@ var hyphenate = cached(function (str) { /** * Simple bind, faster than native */ -function bind(fn, ctx) { - function boundFn(a) { +function bind (fn, ctx) { + function boundFn (a) { var l = arguments.length; return l ? l > 1 @@ -164,7 +164,7 @@ function bind(fn, ctx) { /** * Convert an Array-like object to a real Array. */ -function toArray(list, start) { +function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); @@ -177,7 +177,7 @@ function toArray(list, start) { /** * Mix properties into target object. */ -function extend(to, _from) { +function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } @@ -187,7 +187,7 @@ function extend(to, _from) { /** * Merge an Array of Objects into a single Object. */ -function toObject(arr) { +function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { @@ -200,7 +200,7 @@ function toObject(arr) { /** * Perform no operation. */ -function noop() { } +function noop () {} /** * Always return false. @@ -215,7 +215,7 @@ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ -function genStaticKeys(modules) { +function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') @@ -225,7 +225,7 @@ function genStaticKeys(modules) { * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ -function looseEqual(a, b) { +function looseEqual (a, b) { var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { @@ -242,7 +242,7 @@ function looseEqual(a, b) { } } -function looseIndexOf(arr, val) { +function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } @@ -252,7 +252,7 @@ function looseIndexOf(arr, val) { /** * Ensure a function is called only once. */ -function once(fn) { +function once (fn) { var called = false; return function () { if (!called) { @@ -266,15 +266,10 @@ function once(fn) { var emptyObject = Object.freeze({}); -/** - * Check if a string starts with $ or _ - */ - - /** * Define a property. */ -function def(obj, key, val, enumerable) { +function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, @@ -286,21 +281,17 @@ function def(obj, key, val, enumerable) { /** * List of soon to be deprecated packages in react native v0.59 */ - - var deprecatedPackages = [ - 'NetInfo', - 'AsyncStorage', +var deprecatedPackages = [ 'AlertIOS', - 'WebView', - 'ViewPagerAndroid', + 'AsyncStorage', + 'ImageStore', 'ListView', + 'MaskedViewIOS', + 'NetInfo', + 'Slider', 'SwipeableListView', - 'Slider' - ]; - -/** - * Parse simple path. - */ + 'ViewPagerAndroid', + 'WebView' ]; var ASSET_TYPES = [ 'component', @@ -323,6 +314,8 @@ var LIFECYCLE_HOOKS = [ /* */ + + var config = ({ /** * Option merge strategies (used in core/util/options) @@ -405,17 +398,14 @@ var config = ({ }); var warn = noop; -var tip = noop; var formatComponentName; if (process.env.NODE_ENV !== 'production') { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; - var classify = function (str) { - return str - .replace(classifyRE, function (c) { return c.toUpperCase(); }) - .replace(/[-_]/g, ''); - }; + var classify = function (str) { return str + .replace(classifyRE, function (c) { return c.toUpperCase(); }) + .replace(/[-_]/g, ''); }; warn = function (msg, vm) { if (hasConsole && (!config.silent)) { @@ -425,14 +415,6 @@ if (process.env.NODE_ENV !== 'production') { } }; - tip = function (msg, vm) { - if (hasConsole && (!config.silent)) { - console.warn("[Vue tip]: " + msg + ( - vm ? generateComponentTrace(vm) : '' - )); - } - }; - formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '' @@ -487,11 +469,9 @@ if (process.env.NODE_ENV !== 'production') { vm = vm.$parent; } return '\n\nfound in\n\n' + tree - .map(function (vm, i) { - return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) + .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") - : formatComponentName(vm))); - }) + : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") @@ -499,10 +479,8 @@ if (process.env.NODE_ENV !== 'production') { }; } -function handleError(err, vm, info) { - if (config.errorHandler) { - config.errorHandler.call(null, err, vm, info); - } else { +function handleError (err, vm, info) { + { if (process.env.NODE_ENV !== 'production') { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } @@ -516,17 +494,21 @@ function handleError(err, vm, info) { } /* */ -/* globals MutationObserver */ -var hasProto = '__proto__' in {}; +// can we use __proto__? +var hasProto = "__proto__" in {}; // Browser environment sniffing -var inBrowser = typeof window !== 'undefined'; -var UA = inBrowser && window.navigator && window.navigator.userAgent && window.navigator.userAgent.toLowerCase(); +var inBrowser = typeof window !== "undefined"; +var UA = + inBrowser && + window.navigator && + window.navigator.userAgent && + window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); -var isIE9 = UA && UA.indexOf('msie 9.0') > 0; -var isEdge = UA && UA.indexOf('edge/') > 0; -var isAndroid = UA && UA.indexOf('android') > 0; +var isIE9 = UA && UA.indexOf("msie 9.0") > 0; +var isEdge = UA && UA.indexOf("edge/") > 0; +var isAndroid = UA && UA.indexOf("android") > 0; var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; @@ -534,14 +516,18 @@ var supportsPassive = false; if (inBrowser) { try { var opts = {}; - Object.defineProperty(opts, 'passive', ({ - get: function get() { - /* istanbul ignore next */ - supportsPassive = true; - } - })); // https://github.com/facebook/flow/issues/285 - window.addEventListener('test-passive', null, opts); - } catch (e) { } + Object.defineProperty( + opts, + "passive", + ({ + get: function get() { + /* istanbul ignore next */ + supportsPassive = true; + } + }) + ); // https://github.com/facebook/flow/issues/285 + window.addEventListener("test-passive", null, opts); + } catch (e) {} } // this needs to be lazy-evaled because vue may be required before @@ -550,33 +536,35 @@ var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ - if (!inBrowser && typeof global !== 'undefined') { + if (!inBrowser && typeof global !== "undefined") { // detect presence of vue-server-renderer and avoid // Webpack shimming the process - _isServer = global['process'].env.VUE_ENV === 'server'; + _isServer = global["process"].env.VUE_ENV === "server"; } else { _isServer = false; } } - return _isServer + return _isServer; }; // detect devtools - +var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative(Ctor) { - return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) + return typeof Ctor === "function" && /native code/.test(Ctor.toString()); } var hasSymbol = - typeof Symbol !== 'undefined' && isNative(Symbol) && - typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); + typeof Symbol !== "undefined" && + isNative(Symbol) && + typeof Reflect !== "undefined" && + isNative(Reflect.ownKeys); /** * Defer a task to execute it asynchronously. */ -var nextTick = (function () { +var nextTick = (function() { var callbacks = []; var pending = false; var timerFunc; @@ -597,9 +585,11 @@ var nextTick = (function () { // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore if */ - if (typeof Promise !== 'undefined' && isNative(Promise)) { + if (typeof Promise !== "undefined" && isNative(Promise)) { var p = Promise.resolve(); - var logError = function (err) { console.error(err); }; + var logError = function (err) { + console.error(err); + }; timerFunc = function () { p.then(nextTickHandler).catch(logError); // in problematic UIWebViews, Promise.then doesn't completely break, but @@ -609,11 +599,12 @@ var nextTick = (function () { // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; - } else if (typeof MutationObserver !== 'undefined' && ( - isNative(MutationObserver) || - // PhantomJS and iOS 7.x - MutationObserver.toString() === '[object MutationObserverConstructor]' - )) { + } else if ( + typeof MutationObserver !== "undefined" && + (isNative(MutationObserver) || + // PhantomJS and iOS 7.x + MutationObserver.toString() === "[object MutationObserverConstructor]") + ) { // use MutationObserver where native Promise is not available, // e.g. PhantomJS IE11, iOS7, Android 4.4 var counter = 1; @@ -627,11 +618,19 @@ var nextTick = (function () { textNode.data = String(counter); }; } else { - // fallback to setTimeout - /* istanbul ignore next */ - timerFunc = function () { - setTimeout(nextTickHandler, 0); - }; + if (Promise !== undefined) { + // If Promise is supported for android + timerFunc = function() { + var p = Promise.resolve(); + p.then(nextTickHandler).catch(logError); + }; + } else { + // fallback to setTimeout + /* istanbul ignore next */ + timerFunc = function() { + setTimeout(nextTickHandler, 0); + }; + } } return function queueNextTick(cb, ctx) { @@ -641,7 +640,7 @@ var nextTick = (function () { try { cb.call(ctx); } catch (e) { - handleError(e, ctx, 'nextTick'); + handleError(e, ctx, "nextTick"); } } else if (_resolve) { _resolve(ctx); @@ -651,68 +650,44 @@ var nextTick = (function () { pending = true; timerFunc(); } - if (!cb && typeof Promise !== 'undefined') { + if (!cb && typeof Promise !== "undefined") { return new Promise(function (resolve, reject) { _resolve = resolve; - }) + }); } - } + }; })(); - -var _Set; /* istanbul ignore if */ -if (typeof Set !== 'undefined' && isNative(Set)) { - // use native Set when available. - _Set = Set; -} else { - // a non-standard Set polyfill that only works with primitive keys. - _Set = (function () { - function Set() { - this.set = Object.create(null); - } - Set.prototype.has = function has(key) { - return this.set[key] === true - }; - Set.prototype.add = function add(key) { - this.set[key] = true; - }; - Set.prototype.clear = function clear() { - this.set = Object.create(null); - }; - - return Set; - }()); -} +if (typeof Set !== "undefined" && isNative(Set)) ; /* */ - var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ -var Dep = function Dep() { +var Dep = function Dep () { this.id = uid++; this.subs = []; }; -Dep.prototype.addSub = function addSub(sub) { +Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; -Dep.prototype.removeSub = function removeSub(sub) { +Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; -Dep.prototype.depend = function depend() { +Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; -Dep.prototype.notify = function notify() { +Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { @@ -720,6 +695,9 @@ Dep.prototype.notify = function notify() { } }; +// the current target watcher being evaluated. +// this is globally unique because there could be only one +// watcher being evaluated at any time. Dep.target = null; /* @@ -728,7 +706,12 @@ Dep.target = null; */ var arrayProto = Array.prototype; -var arrayMethods = Object.create(arrayProto);[ +var arrayMethods = Object.create(arrayProto) + +/** + * Intercept mutating methods and emit events + */ +;[ 'push', 'pop', 'shift', @@ -737,39 +720,39 @@ var arrayMethods = Object.create(arrayProto);[ 'sort', 'reverse' ] - .forEach(function (method) { - // cache original method - var original = arrayProto[method]; - def(arrayMethods, method, function mutator() { - var arguments$1 = arguments; - - // avoid leaking arguments: - // http://jsperf.com/closure-with-arguments - var i = arguments.length; - var args = new Array(i); - while (i--) { - args[i] = arguments$1[i]; - } - var result = original.apply(this, args); - var ob = this.__ob__; - var inserted; - switch (method) { - case 'push': - inserted = args; - break - case 'unshift': - inserted = args; - break - case 'splice': - inserted = args.slice(2); - break - } - if (inserted) { ob.observeArray(inserted); } - // notify change - ob.dep.notify(); - return result - }); +.forEach(function (method) { + // cache original method + var original = arrayProto[method]; + def(arrayMethods, method, function mutator () { + var arguments$1 = arguments; + + // avoid leaking arguments: + // http://jsperf.com/closure-with-arguments + var i = arguments.length; + var args = new Array(i); + while (i--) { + args[i] = arguments$1[i]; + } + var result = original.apply(this, args); + var ob = this.__ob__; + var inserted; + switch (method) { + case 'push': + inserted = args; + break + case 'unshift': + inserted = args; + break + case 'splice': + inserted = args.slice(2); + break + } + if (inserted) { ob.observeArray(inserted); } + // notify change + ob.dep.notify(); + return result }); +}); /* */ @@ -792,7 +775,7 @@ var observerState = { * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ -var Observer = function Observer(value) { +var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; @@ -813,17 +796,17 @@ var Observer = function Observer(value) { * getter/setters. This method should only be called when * value type is Object. */ -Observer.prototype.walk = function walk(obj) { +Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { - defineReactive$$1(obj, keys[i], obj[keys[i]]); + defineReactive(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ -Observer.prototype.observeArray = function observeArray(items) { +Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } @@ -835,7 +818,7 @@ Observer.prototype.observeArray = function observeArray(items) { * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ -function protoAugment(target, src) { +function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ @@ -846,7 +829,7 @@ function protoAugment(target, src) { * hidden properties. */ /* istanbul ignore next */ -function copyAugment(target, src, keys) { +function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); @@ -858,7 +841,7 @@ function copyAugment(target, src, keys) { * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ -function observe(value, asRootData) { +function observe (value, asRootData) { if (!isObject(value)) { return } @@ -883,7 +866,7 @@ function observe(value, asRootData) { /** * Define a reactive property on an Object. */ -function defineReactive$$1( +function defineReactive ( obj, key, val, @@ -904,7 +887,7 @@ function defineReactive$$1( Object.defineProperty(obj, key, { enumerable: true, configurable: true, - get: function reactiveGetter() { + get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); @@ -917,7 +900,7 @@ function defineReactive$$1( } return value }, - set: function reactiveSetter(newVal) { + set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { @@ -943,7 +926,7 @@ function defineReactive$$1( * triggers change notification if the property doesn't * already exist. */ -function set(target, key, val) { +function set (target, key, val) { if (Array.isArray(target) && typeof key === 'number') { target.length = Math.max(target.length, key); target.splice(key, 1, val); @@ -953,7 +936,7 @@ function set(target, key, val) { target[key] = val; return val } - var ob = (target).__ob__; + var ob = (target ).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + @@ -965,21 +948,16 @@ function set(target, key, val) { target[key] = val; return val } - defineReactive$$1(ob.value, key, val); + defineReactive(ob.value, key, val); ob.dep.notify(); return val } -/** - * Delete a property and trigger change if necessary. - */ - - /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ -function dependArray(value) { +function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); @@ -991,6 +969,11 @@ function dependArray(value) { /* */ +/** + * Option overwriting strategies are functions that handle + * how to merge a parent option value and a child option + * value into the final value. + */ var strats = config.optionMergeStrategies; /** @@ -1011,7 +994,7 @@ if (process.env.NODE_ENV !== 'production') { /** * Helper that recursively merges two data objects together. */ -function mergeData(to, from) { +function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); @@ -1058,14 +1041,14 @@ strats.data = function ( // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. - return function mergedDataFn() { + return function mergedDataFn () { return mergeData( childVal.call(this), parentVal.call(this) ) } } else if (parentVal || childVal) { - return function mergedInstanceDataFn() { + return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) @@ -1085,7 +1068,7 @@ strats.data = function ( /** * Hooks and props are merged as arrays. */ -function mergeHook( +function mergeHook ( parentVal, childVal ) { @@ -1109,7 +1092,7 @@ LIFECYCLE_HOOKS.forEach(function (hook) { * a three-way merge between constructor options, instance * options and parent options. */ -function mergeAssets(parentVal, childVal) { +function mergeAssets (parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, childVal) @@ -1149,15 +1132,15 @@ strats.watch = function (parentVal, childVal) { * Other object hashes. */ strats.props = - strats.methods = - strats.computed = function (parentVal, childVal) { - if (!childVal) { return Object.create(parentVal || null) } - if (!parentVal) { return childVal } - var ret = Object.create(null); - extend(ret, parentVal); - extend(ret, childVal); - return ret - }; +strats.methods = +strats.computed = function (parentVal, childVal) { + if (!childVal) { return Object.create(parentVal || null) } + if (!parentVal) { return childVal } + var ret = Object.create(null); + extend(ret, parentVal); + extend(ret, childVal); + return ret +}; /** * Default strategy. @@ -1168,17 +1151,12 @@ var defaultStrat = function (parentVal, childVal) { : childVal }; -/** - * Validate component names - */ - - /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ -function resolveAsset( +function resolveAsset ( options, type, id, @@ -1206,15 +1184,7 @@ function resolveAsset( return res } -/* */ - - - -/** - * Get the default value of a prop. - */ - -function setSelected(el, binding, vm) { +function setSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { @@ -1247,11 +1217,11 @@ function setSelected(el, binding, vm) { } } -function setCheckBox(el, binding) { +function setCheckBox (el, binding) { var value = binding.value; try { value = JSON.parse(value); - } catch (e) { } + } catch (e) {} if (value) { el.setAttribute('checked', value); } else { @@ -1260,7 +1230,7 @@ function setCheckBox(el, binding) { } var model = { - bind: function bind$$1(el, binding) { + bind: function bind (el, binding) { if (el.tagName) { var lowerTagName = el.tagName.toLowerCase(); if (lowerTagName === 'select') { @@ -1272,7 +1242,7 @@ var model = { } } }, - update: function update(el, binding) { + update: function update (el, binding) { if (el.tagName) { var lowerTagName = el.tagName.toLowerCase(); if (lowerTagName === 'select') { @@ -1292,7 +1262,10 @@ var index = { /* */ -function renderList( +/** + * Runtime helper for rendering v-for lists. + */ +function renderList ( val, render ) { @@ -1318,9 +1291,9 @@ function renderList( return ret } -var CREATE_ELEMENT = 'createElement'; -var COMPONENT = 'Component'; -var HELPER_HEADER = '__react__vue__'; +var CREATE_ELEMENT = "createElement"; +var COMPONENT = "Component"; +var HELPER_HEADER = "__react__vue__"; var COMMON = { 'createElement': { @@ -1441,7 +1414,7 @@ function renderSlot(names, children) { var hitSlot = {}; var defaultSlot = []; if (children == null) { - return function () { } + return function () {}; } if (!Array.isArray(children)) { children = [children]; @@ -1449,30 +1422,30 @@ function renderSlot(names, children) { children = children.filter(function (v) { return v != null; }); children.forEach(function (v) { if (v.type === COMMON.template.type) { - if (v['dataSlot'] === undefined) { + if (v["dataSlot"] === undefined) { defaultSlot.push(v.render); } - return + return; } - if (v.props === undefined || v.props['dataSlot'] === undefined) { + if (v.props === undefined || v.props["dataSlot"] === undefined) { defaultSlot.push(v); } }); names.forEach(function (v) { children.forEach(function (_v, _i) { - if (typeof _v === 'string' || typeof _v === 'number') { - return + if (typeof _v === "string" || typeof _v === "number") { + return; } if (_v.type === COMMON.template.type) { - if (v === _v['dataSlot']) { + if (v === _v["dataSlot"]) { hitSlot[v] = _v.render; } - return + return; } - if (v === _v.props['dataSlot']) { + if (v === _v.props["dataSlot"]) { hitSlot[v] = _v; } - return + return; }); }); function render(name, props) { @@ -1482,24 +1455,24 @@ function renderSlot(names, children) { } else { target = hitSlot[name]; } - if (typeof target === 'function') { - return target(props) + if (typeof target === "function") { + return target(props); } else if (Array.isArray(target)) { return target.map(function (v) { - if (typeof v === 'function') { - return v(props) + if (typeof v === "function") { + return v(props); } else { - return v + return v; } - }) + }); } else { - return target + return target; } } - return render + return render; } -function bindWebClass(c) { +function bindWebClass (c) { var type = Object.prototype.toString.call(c); if (type === '[object Object]') { return Object.keys(c).filter(function (k) { @@ -1513,7 +1486,7 @@ function bindWebClass(c) { return c } -function classBinding(c) { +function classBinding (c) { var type = Object.prototype.toString.call(c); if (type === '[object Object]') { return Object.keys(c).filter(function (k) { @@ -1529,19 +1502,19 @@ function classBinding(c) { return c } -function bindNativeClass(obj) { +function bindNativeClass (obj) { var this$1 = this; var arr = []; var style = []; if (obj.dynamicClass) { - // console.log('obj.dynamicClass', obj.dynamicClass); arr = arr.concat(classBinding(obj.dynamicClass)); } if (obj.staticClass) { arr = arr.concat(obj.staticClass.split(/\s+/)); } arr.forEach(function (v) { + // commit cf4d099 change moved here style.push(this$1.css[v]); }); if (obj.parentClass) { @@ -1568,7 +1541,7 @@ var normalize = cached(function (prop) { } }); -function bindWebStyle(styleBinding, staticStyle, showStyle) { +function bindWebStyle (styleBinding, staticStyle, showStyle) { if (styleBinding === undefined) { styleBinding = {}; } @@ -1588,7 +1561,7 @@ function bindWebStyle(styleBinding, staticStyle, showStyle) { } } -function bindNativeStyle(styleBinding, staticStyle, showStyle) { +function bindNativeStyle (styleBinding, staticStyle, showStyle) { if (styleBinding === undefined) { styleBinding = {}; } @@ -1607,7 +1580,7 @@ function bindNativeStyle(styleBinding, staticStyle, showStyle) { } function mergeNativeStyleAndNativeClass(nativeClass, nativeStyle) { - let resultant = []; + var resultant = []; if (nativeClass) { if (Object.prototype.toString.call(nativeClass) === '[object Array]') { nativeClass.forEach(function (classObj) { @@ -1625,11 +1598,13 @@ function mergeNativeStyleAndNativeClass(nativeClass, nativeStyle) { resultant.push(nativeStyle); } } - // console.log('resultant merged style props', resultant); return resultant; } /* */ +/** + * Runtime helper for checking keyCodes. + */ function checkKeyCodes( vm, eventKeyCode, @@ -1640,21 +1615,23 @@ function checkKeyCodes( try { configKeyCodes = vm.$options._base.config.keyCodes; } catch (e) { - warn('react-vue checkKeyCodes vm.$options._base.config.keyCodes catch error'); + warn( + "vue-native checkKeyCodes vm.$options._base.config.keyCodes catch error" + ); } var keyCodes = configKeyCodes[key] || builtInAlias; if (Array.isArray(keyCodes)) { - return keyCodes.indexOf(eventKeyCode) === -1 + return keyCodes.indexOf(eventKeyCode) === -1; } else { - return keyCodes !== eventKeyCode + return keyCodes !== eventKeyCode; } } -function template(props) { +function template (props) { return props.children } -function event(fn) { +function event (fn) { if (Array.isArray(fn)) { return function () { var arguments$1 = arguments; @@ -1667,7 +1644,7 @@ function event(fn) { } } -function mergeCssModule(computed, cssModules) { +function mergeCssModule (computed, cssModules) { var _computed = Object.create(computed || null); Object.keys(cssModules).forEach(function (key) { var module = cssModules[key]; @@ -1693,34 +1670,39 @@ function isObjectShallowModified(prev, next) { // } // return false if (prev.children !== undefined || next.children !== undefined) { - return true + return true; } for (var k in next) { - if (typeof next[k] !== 'object') { + if (typeof next[k] !== "object") { if (next[k] !== prev[k]) { - return true + return true; } } } - return false + return false; } var hasOwnProperty$1 = Object.prototype.hasOwnProperty; function hasOwn$1(obj, key) { - return hasOwnProperty$1.call(obj, key) + return hasOwnProperty$1.call(obj, key); } function mergeCssModule$1(computed, cssModules) { var _computed = Object.create(computed || null); - Object.keys(cssModules).forEach(function (key) { + Object.keys(cssModules).forEach(function(key) { var module = cssModules[key]; - _computed[key] = function () { return module }; + _computed[key] = function() { + return module; + }; }); - return _computed + return _computed; } function pascalCaseTag(tag) { - return tag.split('-').map(function (v) { return v.replace(/^[a-z]/, function (s) { return s.toUpperCase(); }); }).join('') + return tag + .split("-") + .map(function (v) { return v.replace(/^[a-z]/, function (s) { return s.toUpperCase(); }); }) + .join(""); } /** @@ -1738,15 +1720,15 @@ function handleComponents(components) { } } } - return components + return components; } function handleDirectives(directives) { var obj = {}; for (var k in directives) { - obj[k.toLowerCase().replace(/[^a-z]/g, '')] = directives[k]; + obj[k.toLowerCase().replace(/[^a-z]/g, "")] = directives[k]; } - return obj + return obj; } /** @@ -1756,21 +1738,22 @@ function handleDirectives(directives) { function getSlots(children) { var slots = {}; if (children == null) { - return slots + return slots; } if (!Array.isArray(children)) { children = [children]; } children = children.filter(function (v) { return v != null; }); children.forEach(function (v, _i) { - if (typeof v === 'string' || typeof v === 'number' || v === null) { + if (typeof v === "string" || typeof v === "number" || v === null) { slots.default = slots.default || []; slots.default.push(v); } else if (v.type === COMMON.template.type) { - slots[v['data-slot']] = slots[v['data-slot']] || []; - slots[v['data-slot']].push(v.render); + // data-slot renamed to dataSlot to fix named slot issue + slots[v["dataSlot"]] = slots[v["dataSlot"]] || []; + slots[v["dataSlot"]].push(v.render); } else if (v.props) { - var dataSlot = v.props['data-slot']; + var dataSlot = v.props["dataSlot"]; if (dataSlot == null) { slots.default = slots.default || []; slots.default.push(v); @@ -1780,21 +1763,23 @@ function getSlots(children) { } } }); - return slots + return slots; } function filterCustomEvent(props) { - return Object.keys(props).filter(function (v) { - return v.indexOf(COMMON.customEvent.name) === 0 - }).map(function (v) { - return { - name: v.replace(COMMON.customEvent.name, ''), - handle: props[v] - } - }) + return Object.keys(props) + .filter(function (v) { + return v.indexOf(COMMON.customEvent.name) === 0; + }) + .map(function (v) { + return { + name: v.replace(COMMON.customEvent.name, ""), + handle: props[v] + }; + }); } -function dynamicComponent(vm, name) { +function dynamicComponent (vm, name) { var componentName; if (typeof name === 'string') { componentName = vm.$options.components[pascalCaseTag(name)]; @@ -1806,7 +1791,10 @@ function dynamicComponent(vm, name) { /* */ -function resolveFilter(id) { +/** + * Runtime helper for resolving filters + */ +function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } @@ -2541,12 +2529,13 @@ Object.keys(reactProps).map(function (v) { /* */ +// these are reserved for web because they are directly compiled away +// during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select'); - var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( @@ -2560,50 +2549,48 @@ var isBooleanAttr = makeMap( /* */ - - var isUnaryTag = makeMap( - 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + - 'link,meta,param,source,track,wbr' + "area,base,br,col,embed,frame,hr,img,input,isindex,keygen," + + "link,meta,param,source,track,wbr" ); var isHTMLTag = makeMap( - 'html,body,base,head,link,meta,style,title,' + - 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + - 'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' + - 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + - 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + - 'embed,object,param,source,canvas,script,noscript,del,ins,' + - 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + - 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + - 'output,progress,select,textarea,' + - 'details,dialog,menu,menuitem,summary,' + - 'content,element,shadow,template' + "html,body,base,head,link,meta,style,title," + + "address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section," + + "div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul," + + "a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby," + + "s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video," + + "embed,object,param,source,canvas,script,noscript,del,ins," + + "caption,col,colgroup,table,thead,tbody,td,th,tr," + + "button,datalist,fieldset,form,input,label,legend,meter,optgroup,option," + + "output,progress,select,textarea," + + "details,dialog,menu,menuitem,summary," + + "content,element,shadow,template" ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( - 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + - 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + - 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', + "svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face," + + "foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern," + + "polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view", true ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( - 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' + "colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source" ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( - 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + - 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + - 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + - 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + - 'title,tr,track' + "address,article,aside,base,blockquote,body,caption,col,colgroup,dd," + + "details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form," + + "h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta," + + "optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead," + + "title,tr,track" ); var buildInTags = [ @@ -2615,20 +2602,22 @@ var buildInTags = [ WEB.inputComponent.component ]; -var isBuildInTag = makeMap(buildInTags.join(',')); - - +var isBuildInTag = makeMap(buildInTags.join(",")); var isReservedTag = function (tag) { - return isHTMLTag(tag) || isSVG(tag) + return isHTMLTag(tag) || isSVG(tag); }; function handleProps(props, tag) { var handledProps = {}; - if (typeof tag === 'string' && isReservedTag(tag)) { + if (typeof tag === "string" && isReservedTag(tag)) { for (var key in props) { var prop = propertyMap[key.toLowerCase()]; - if (prop && props[key] !== undefined && key.indexOf(HELPER_HEADER) !== 0) { + if ( + prop && + props[key] !== undefined && + key.indexOf(HELPER_HEADER) !== 0 + ) { handledProps[prop] = props[key]; } } @@ -2638,10 +2627,10 @@ function handleProps(props, tag) { if (isUnaryTag(tag)) { delete handledProps.children; } - return handledProps + return handledProps; } -function mergeProps() { +function mergeProps () { var this$1 = this; var args = Array.prototype.slice.call(arguments, 0).filter(function (v) { return v; }); @@ -2654,7 +2643,7 @@ function mergeProps() { obj[k].push(o[k]); }); }); - var loop = function (k) { + var loop = function ( k ) { var l = obj[k].length; if (l === 1) { obj[k] = obj[k][0]; @@ -2663,10 +2652,9 @@ function mergeProps() { if (typeof _p[0] === 'function') { obj[k] = function () { var arguments$1 = arguments; - var this$1 = this; for (var i = 0; i < l; i++) { - typeof _p[i] === 'function' && _p[i].apply(this$1, arguments$1); + typeof _p[i] === 'function' && _p[i].apply(this, arguments$1); } }.bind(this$1); } else { @@ -2675,15 +2663,11 @@ function mergeProps() { } }; - for (var k in obj) loop(k); + for (var k in obj) loop( k ); return obj } -/** - * - */ - -function buildComponent(render, options, config) { +function buildComponent (render, options, config) { var Component = config.Component; var PropTypes = config.PropTypes; var Vue = config.Vue; @@ -2691,8 +2675,8 @@ function buildComponent(render, options, config) { if (cssModules) { options.computed = mergeCssModule$1(options.computed, cssModules); } - var ReactVueComponent = (function (Component) { - function ReactVueComponent(props) { + var ReactVueComponent = /*@__PURE__*/(function (Component) { + function ReactVueComponent (props) { Component.call(this, props); this._ref = null; this.eventOnceUid = []; @@ -2706,14 +2690,14 @@ function buildComponent(render, options, config) { this.beforeDestroy = []; } - if (Component) ReactVueComponent.__proto__ = Component; - ReactVueComponent.prototype = Object.create(Component && Component.prototype); + if ( Component ) ReactVueComponent.__proto__ = Component; + ReactVueComponent.prototype = Object.create( Component && Component.prototype ); ReactVueComponent.prototype.constructor = ReactVueComponent; /** * children can access parent instance by 'this.context.owner' */ - ReactVueComponent.prototype.getChildContext = function getChildContext() { + ReactVueComponent.prototype.getChildContext = function getChildContext () { return { owner: this } @@ -2722,7 +2706,7 @@ function buildComponent(render, options, config) { /** * for event modifiers v-on:xxx.once */ - ReactVueComponent.prototype.setEventOnce = function setEventOnce(fn) { + ReactVueComponent.prototype.setEventOnce = function setEventOnce (fn) { var this$1 = this; var name = fn.name; @@ -2734,7 +2718,7 @@ function buildComponent(render, options, config) { } }; - ReactVueComponent.prototype.setRootRef = function setRootRef(ref) { + ReactVueComponent.prototype.setRootRef = function setRootRef (ref) { if (ref) { ref = ref._ref || ref; this._ref = ref; @@ -2742,7 +2726,7 @@ function buildComponent(render, options, config) { } }; - ReactVueComponent.prototype.setRef = function setRef(ref, text, inFor) { + ReactVueComponent.prototype.setRef = function setRef (ref, text, inFor) { if (ref) { // for buildin component, we set ref to his hold node directly // it means the buildin componet would be the end of $refs chain @@ -2759,7 +2743,7 @@ function buildComponent(render, options, config) { } }; - ReactVueComponent.prototype.buildVM = function buildVM(options) { + ReactVueComponent.prototype.buildVM = function buildVM (options) { // set this property to prevent runtime error in vue render._withStripped = true; @@ -2795,7 +2779,7 @@ function buildComponent(render, options, config) { return vm }; - ReactVueComponent.prototype.componentWillMount = function componentWillMount() { + ReactVueComponent.prototype.UNSAFE_componentWillMount = function UNSAFE_componentWillMount () { var this$1 = this; this.vm = this.buildVM(options); @@ -2809,34 +2793,34 @@ function buildComponent(render, options, config) { this.beforeMount.forEach(function (v) { return v.call(this$1.vm); }); }; - ReactVueComponent.prototype.componentDidMount = function componentDidMount() { + ReactVueComponent.prototype.componentDidMount = function componentDidMount () { var this$1 = this; this.vm.$nextTick(function () { return this$1.mounted.forEach(function (v) { return v.call(this$1.vm); }); }); }; - ReactVueComponent.prototype.componentWillUpdate = function componentWillUpdate() { + ReactVueComponent.prototype.UNSAFE_componentWillUpdate = function UNSAFE_componentWillUpdate () { var this$1 = this; this.beforeUpdate.forEach(function (v) { return v.call(this$1.vm); }); }; - ReactVueComponent.prototype.componentDidUpdate = function componentDidUpdate() { + ReactVueComponent.prototype.componentDidUpdate = function componentDidUpdate () { var this$1 = this; this.updated.forEach(function (v) { return v.call(this$1.vm); }); }; - ReactVueComponent.prototype.componentWillUnmount = function componentWillUnmount() { + ReactVueComponent.prototype.componentWillUnmount = function componentWillUnmount () { var this$1 = this; this.beforeDestroy.forEach(function (v) { return v.call(this$1.vm); }); }; - ReactVueComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + ReactVueComponent.prototype.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps (nextProps) { this.vm._props && Object.assign(this.vm._props, nextProps); this.vm.$slots = getSlots(nextProps.children); }; - ReactVueComponent.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { + ReactVueComponent.prototype.shouldComponentUpdate = function shouldComponentUpdate (nextProps) { return isObjectShallowModified(this.props, nextProps) }; - ReactVueComponent.prototype.render = function render$1() { + ReactVueComponent.prototype.render = function render$1 () { return render ? render.call(this, this.vm._renderProxy) : null }; @@ -2854,9 +2838,9 @@ function buildComponent(render, options, config) { return ReactVueComponent } -function buildMixin(Component) { - return (function (Component) { - function Mixin(props) { +function buildMixin (Component) { + return /*@__PURE__*/(function (Component) { + function Mixin (props) { Component.call(this, props); /** * for vue, every component should have a ref to represent node element @@ -2864,11 +2848,11 @@ function buildMixin(Component) { this._ref = null; } - if (Component) Mixin.__proto__ = Component; - Mixin.prototype = Object.create(Component && Component.prototype); + if ( Component ) Mixin.__proto__ = Component; + Mixin.prototype = Object.create( Component && Component.prototype ); Mixin.prototype.constructor = Mixin; - Mixin.prototype.setRef = function setRef(ref) { + Mixin.prototype.setRef = function setRef (ref) { if (ref) { if (ref._reactInternalInstance && ref.vm === undefined) { this._ref = ref._ref || ref; @@ -2878,7 +2862,7 @@ function buildMixin(Component) { } }; - Mixin.prototype.buildStateProps = function buildStateProps(props) { + Mixin.prototype.buildStateProps = function buildStateProps (props) { var this$1 = this; var stateProps = Object.assign({}, props); @@ -2913,10 +2897,11 @@ function triggerDirective(newData, oldData, vm, ref) { } if (!directive) { - return + return; } - if (newData && oldData) { // update + if (newData && oldData) { + // update binding = { name: newData.name, value: newData.value, @@ -2926,12 +2911,13 @@ function triggerDirective(newData, oldData, vm, ref) { modifiers: newData.modifiers }; args = [ref, binding, vnode]; - if (typeof directive === 'function') { + if (typeof directive === "function") { directive.apply(vm, args); - } else if (typeof directive.update === 'function') { + } else if (typeof directive.update === "function") { directive.update.apply(vm, args); } - } else if (newData && !oldData) { // bind + } else if (newData && !oldData) { + // bind binding = { name: newData.name, value: newData.value, @@ -2940,12 +2926,13 @@ function triggerDirective(newData, oldData, vm, ref) { modifiers: newData.modifiers }; args = [ref, binding, vnode]; - if (typeof directive === 'function') { + if (typeof directive === "function") { directive.apply(vm, args); - } else if (typeof directive.bind === 'function') { + } else if (typeof directive.bind === "function") { directive.bind.apply(vm, args); } - } else if (!newData && oldData) { // unbind + } else if (!newData && oldData) { + // unbind binding = { name: oldData.name, value: oldData.value, @@ -2954,14 +2941,14 @@ function triggerDirective(newData, oldData, vm, ref) { modifiers: oldData.modifiers }; args = [ref, binding, vnode]; - if (typeof directive.unbind === 'function') { + if (typeof directive.unbind === "function") { directive.unbind.apply(vm, args); } } } function buildDirective(Component, createElement) { - return (function (superclass) { + return /*@__PURE__*/(function (superclass) { function Directive(props) { superclass.call(this, props); // set vm from parent context that @@ -2971,10 +2958,10 @@ function buildDirective(Component, createElement) { }; } - if (superclass) Directive.__proto__ = superclass; - Directive.prototype = Object.create(superclass && superclass.prototype); + if ( superclass ) Directive.__proto__ = superclass; + Directive.prototype = Object.create( superclass && superclass.prototype ); Directive.prototype.constructor = Directive; - Directive.prototype.setDirectiveLifeCycle = function setDirectiveLifeCycle(newProps, oldProps) { + Directive.prototype.setDirectiveLifeCycle = function setDirectiveLifeCycle (newProps, oldProps) { var this$1 = this; var context; @@ -2996,64 +2983,76 @@ function buildDirective(Component, createElement) { if (newDirective.name === oldDirective.name) { newDirectivesClone.splice(newIndex, 1, undefined); oldDirectivesClone.splice(oldIndex, 1, undefined); - triggerDirective(newDirective, oldDirective, context.vm, this$1._ref); // update + triggerDirective( + newDirective, + oldDirective, + context.vm, + this$1._ref + ); // update } }); }); - newDirectivesClone.forEach(function (v) { // bind + newDirectivesClone.forEach(function (v) { + // bind v && triggerDirective(v, null, context.vm, this$1._ref); }); - oldDirectivesClone.forEach(function (v) { // unbind + oldDirectivesClone.forEach(function (v) { + // unbind v && triggerDirective(null, v, context.vm, this$1._ref); }); } }; - Directive.prototype.getDirectiveName = function getDirectiveName(props) { + Directive.prototype.getDirectiveName = function getDirectiveName (props) { if (props[COMMON.directive.name]) { - return props[COMMON.directive.name].map(function (v) { return v.name; }) + return props[COMMON.directive.name].map(function (v) { return v.name; }); } else { - return [] + return []; } }; - Directive.prototype.buildInHandle = function buildInHandle(props) { + Directive.prototype.buildInHandle = function buildInHandle (props) { var this$1 = this; var names = this.getDirectiveName(props); var stateProps = this.buildStateProps(props); - if (names.indexOf('model') !== -1) { - var onChangeFn = stateProps.onChange || stateProps.onInput || function () { }; + if (names.indexOf("model") !== -1) { + var onChangeFn = + stateProps.onChange || stateProps.onInput || function() {}; stateProps.onChange = function (event) { this$1.setState({ props: Object.assign({}, this$1.state.props, { value: event.target.value }) }); - return onChangeFn(event) + return onChangeFn(event); }; } this.setState({ props: handleProps(stateProps, props[COMMON.directive.tag]) }); }; - Directive.prototype.componentWillMount = function componentWillMount() { + Directive.prototype.UNSAFE_componentWillMount = function UNSAFE_componentWillMount () { this.buildInHandle(this.props); }; - Directive.prototype.componentDidMount = function componentDidMount() { + Directive.prototype.componentDidMount = function componentDidMount () { this.setDirectiveLifeCycle(this.props); }; - Directive.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + Directive.prototype.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps (nextProps) { this.buildInHandle(nextProps); this.setDirectiveLifeCycle(nextProps, this.props); }; - Directive.prototype.componentWillUnmount = function componentWillUnmount() { + Directive.prototype.componentWillUnmount = function componentWillUnmount () { this.setDirectiveLifeCycle(null, this.props); }; - Directive.prototype.render = function render() { - return createElement(this.props[COMMON.directive.tag], this.state.props, this.state.props.children) + Directive.prototype.render = function render () { + return createElement( + this.props[COMMON.directive.tag], + this.state.props, + this.state.props.children + ); }; return Directive; - }(buildMixin.apply(this, arguments))) + }(buildMixin.apply(this, arguments))); } /* */ @@ -3062,7 +3061,7 @@ function buildDirective(Component, createElement) { * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ -function addClass(el, cls) { +function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return @@ -3087,7 +3086,7 @@ function addClass(el, cls) { * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ -function removeClass(el, cls) { +function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return @@ -3112,20 +3111,20 @@ function removeClass(el, cls) { /* */ -function resolveTransition(def$$1) { - if (!def$$1) { +function resolveTransition (def) { + if (!def) { return } /* istanbul ignore else */ - if (typeof def$$1 === 'object') { + if (typeof def === 'object') { var res = {}; - if (def$$1.css !== false) { - extend(res, autoCssTransition(def$$1.name || 'v')); + if (def.css !== false) { + extend(res, autoCssTransition(def.name || 'v')); } - extend(res, def$$1); + extend(res, def); return res - } else if (typeof def$$1 === 'string') { - return autoCssTransition(def$$1) + } else if (typeof def === 'string') { + return autoCssTransition(def) } } @@ -3168,17 +3167,13 @@ var raf = inBrowser && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout; -function nextFrame(fn) { +function nextFrame (fn) { raf(function () { raf(fn); }); } - - - - -function whenTransitionEnds( +function whenTransitionEnds ( el, expectedType, cb @@ -3211,7 +3206,7 @@ function whenTransitionEnds( var transformRE = /\b(transform|all)(,|$)/; -function getTransitionInfo(el, expectedType) { +function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitionDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); @@ -3260,7 +3255,7 @@ function getTransitionInfo(el, expectedType) { } } -function getTimeout(delays, durations) { +function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); @@ -3271,13 +3266,13 @@ function getTimeout(delays, durations) { })) } -function toMs(s) { +function toMs (s) { return Number(s.slice(0, -1)) * 1000 } -function buildWebEmptyComponent(Component, createElement) { - return (function (Component) { - function EmptyComponent(props) { +function buildWebEmptyComponent (Component, createElement) { + return /*@__PURE__*/(function (Component) { + function EmptyComponent (props) { Component.call(this, props); this._ref = null; this.state = { @@ -3285,13 +3280,13 @@ function buildWebEmptyComponent(Component, createElement) { }; } - if (Component) EmptyComponent.__proto__ = Component; - EmptyComponent.prototype = Object.create(Component && Component.prototype); + if ( Component ) EmptyComponent.__proto__ = Component; + EmptyComponent.prototype = Object.create( Component && Component.prototype ); EmptyComponent.prototype.constructor = EmptyComponent; - EmptyComponent.prototype.setRef = function setRef(ref) { + EmptyComponent.prototype.setRef = function setRef (ref) { this._ref = ref; }; - EmptyComponent.prototype.buildStateProps = function buildStateProps(props) { + EmptyComponent.prototype.buildStateProps = function buildStateProps (props) { var this$1 = this; var stateProps = Object.assign({}, props); @@ -3306,17 +3301,17 @@ function buildWebEmptyComponent(Component, createElement) { }; return stateProps }; - EmptyComponent.prototype.componentWillMount = function componentWillMount() { + EmptyComponent.prototype.UNSAFE_componentWillMount = function UNSAFE_componentWillMount () { this.setState({ props: this.buildStateProps(this.props) }); }; - EmptyComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + EmptyComponent.prototype.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps (nextProps) { this.setState({ props: this.buildStateProps(nextProps) }); }; - EmptyComponent.prototype.unwrap = function unwrap(wrapper) { + EmptyComponent.prototype.unwrap = function unwrap (wrapper) { if (wrapper.parentNode) { var docFrag = document.createDocumentFragment(); while (wrapper.firstChild) { @@ -3326,13 +3321,13 @@ function buildWebEmptyComponent(Component, createElement) { wrapper.parentNode.replaceChild(docFrag, wrapper); } }; - EmptyComponent.prototype.componentDidMount = function componentDidMount() { + EmptyComponent.prototype.componentDidMount = function componentDidMount () { // this.unwrap(this._ref) }; - EmptyComponent.prototype.componentDidUpdate = function componentDidUpdate() { + EmptyComponent.prototype.componentDidUpdate = function componentDidUpdate () { // this.unwrap(this._ref) }; - EmptyComponent.prototype.render = function render() { + EmptyComponent.prototype.render = function render () { var ref = this.state.props; var tag = ref.tag; var children = ref.children; @@ -3343,17 +3338,21 @@ function buildWebEmptyComponent(Component, createElement) { }(Component)) } +// import { +// isObjectShallowModified +// } from './util' + function filterCollection(collection) { var result = []; collection.forEach(function (v) { - if (v.type === 'if') { + if (v.type === "if") { var _result = v.conditions.filter(function (_v) { return _v.exp; }).map(function (_v) { return { - type: 'if', + type: "if", index: _v.index, element: _v.element, exp: _v.exp - } + }; }); if (_result.length) { result.push(_result[0]); @@ -3363,9 +3362,11 @@ function filterCollection(collection) { } }); if (result.length > 1) { - console.warn(" can only be used on a single element. Use for lists."); + console.warn( + " can only be used on a single element. Use for lists." + ); } - return result + return result; } /** @@ -3376,45 +3377,43 @@ function filterCollection(collection) { */ function getHookArgumentsLength(fn) { if (isUndef(fn)) { - return false + return false; } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( - Array.isArray(invokerFns) - ? invokerFns[0] - : invokerFns - ) + Array.isArray(invokerFns) ? invokerFns[0] : invokerFns + ); } else { - return (fn._length || fn.length) > 1 + return (fn._length || fn.length) > 1; } } // only used in dev mode function checkDuration(val, name) { - if (typeof val !== 'number') { + if (typeof val !== "number") { warn( " explicit " + name + " duration is not a valid number - " + - "got " + (JSON.stringify(val)) + "." + "got " + (JSON.stringify(val)) + "." ); } else if (isNaN(val)) { warn( " explicit " + name + " duration is NaN - " + - 'the duration expression might be incorrect.' + "the duration expression might be incorrect." ); } } function isValidDuration(val) { - return typeof val === 'number' && !isNaN(val) + return typeof val === "number" && !isNaN(val); } -function addTransitionClass$$1(ref, className) { +function addTransitionClass(ref, className) { addClass(ref, className); } -function removeTransitionClass$$1(ref, className) { +function removeTransitionClass(ref, className) { removeClass(ref, className); } @@ -3474,79 +3473,70 @@ function enter(ref) { var isAppear = this.isAppear; if (isUndef(el)) { - return + return; } - if (isAppear && !appear && appear !== '') { - return + if (isAppear && !appear && appear !== "") { + return; } if (isDef(el._enterCb) || el.nodeType !== 1) { - return + return; } - var startClass = isAppear && appearClass - ? appearClass - : enterClass; - var activeClass = isAppear && appearActiveClass - ? appearActiveClass - : enterActiveClass; - var toClass = isAppear && appearToClass - ? appearToClass - : enterToClass; + var startClass = isAppear && appearClass ? appearClass : enterClass; + var activeClass = + isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; + var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear - ? (onBeforeAppear || onBeforeEnter) + ? onBeforeAppear || onBeforeEnter : onBeforeEnter; - var enterHook = isAppear - ? (onAppear || onEnter) - : onEnter; + var enterHook = isAppear ? onAppear || onEnter : onEnter; var afterEnterHook = isAppear - ? (onAfterAppear || onAfterEnter) + ? onAfterAppear || onAfterEnter : onAfterEnter; var enterCancelledHook = isAppear - ? (onAppearCancelled || onEnterCancelled) + ? onAppearCancelled || onEnterCancelled : onEnterCancelled; var explicitEnterDuration = toNumber( - isObject(duration) - ? duration.enter - : duration + isObject(duration) ? duration.enter : duration ); - if (process.env.NODE_ENV !== 'production' && explicitEnterDuration != null) { - checkDuration(explicitEnterDuration, 'enter'); + if (process.env.NODE_ENV !== "production" && explicitEnterDuration != null) { + checkDuration(explicitEnterDuration, "enter"); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); - var _cb = el._enterCb = once(function () { + var _cb = (el._enterCb = once(function () { if (expectsCSS) { - removeTransitionClass$$1(el, activeClass); - removeTransitionClass$$1(el, toClass); + removeTransitionClass(el, activeClass); + removeTransitionClass(el, toClass); } cb && cb(); if (_cb.cancelled) { if (expectsCSS) { - removeTransitionClass$$1(el, startClass); + removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; - }); + })); beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { - addTransitionClass$$1(el, startClass); - addTransitionClass$$1(el, activeClass); + addTransitionClass(el, startClass); + addTransitionClass(el, activeClass); nextFrame(function () { - removeTransitionClass$$1(el, startClass); - addTransitionClass$$1(el, toClass); + removeTransitionClass(el, startClass); + addTransitionClass(el, toClass); if (!_cb.cancelled && !userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(_cb, explicitEnterDuration); @@ -3581,51 +3571,49 @@ function leave(ref) { var duration = ref$1.duration; if (isUndef(el)) { - return + return; } if (isDef(el._leaveCb) || el.nodeType !== 1) { - return + return; } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(onLeave); var explicitLeaveDuration = toNumber( - isObject(duration) - ? duration.leave - : duration + isObject(duration) ? duration.leave : duration ); - if (process.env.NODE_ENV !== 'production' && explicitLeaveDuration != null) { - checkDuration(explicitLeaveDuration, 'leave'); + if (process.env.NODE_ENV !== "production" && explicitLeaveDuration != null) { + checkDuration(explicitLeaveDuration, "leave"); } - var _cb = el._leaveCb = once(function () { + var _cb = (el._leaveCb = once(function () { if (expectsCSS) { - removeTransitionClass$$1(el, leaveActiveClass); - removeTransitionClass$$1(el, leaveToClass); + removeTransitionClass(el, leaveActiveClass); + removeTransitionClass(el, leaveToClass); } cb && cb(); if (_cb.cancelled) { if (expectsCSS) { - removeTransitionClass$$1(el, leaveClass); + removeTransitionClass(el, leaveClass); } onLeaveCancelled && onLeaveCancelled(el); } else { onAfterLeave && onAfterLeave(el); } el._leaveCb = null; - }); + })); onBeforeLeave && onBeforeLeave(el); if (expectsCSS) { - addTransitionClass$$1(el, leaveClass); - addTransitionClass$$1(el, leaveActiveClass); + addTransitionClass(el, leaveClass); + addTransitionClass(el, leaveActiveClass); nextFrame(function () { - removeTransitionClass$$1(el, leaveClass); - addTransitionClass$$1(el, leaveToClass); + removeTransitionClass(el, leaveClass); + addTransitionClass(el, leaveToClass); if (!_cb.cancelled && !userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(_cb, explicitLeaveDuration); @@ -3643,7 +3631,7 @@ function leave(ref) { function buildWebTransition(Component, createElement) { var EmptyComponent = buildWebEmptyComponent(Component, createElement); - var Transition = (function (Component) { + var Transition = /*@__PURE__*/(function (Component) { function Transition(props) { Component.call(this, props); this._ref = null; @@ -3658,19 +3646,19 @@ function buildWebTransition(Component, createElement) { }; } - if (Component) Transition.__proto__ = Component; - Transition.prototype = Object.create(Component && Component.prototype); + if ( Component ) Transition.__proto__ = Component; + Transition.prototype = Object.create( Component && Component.prototype ); Transition.prototype.constructor = Transition; - Transition.prototype.setRef = function setRef(ref, key) { + Transition.prototype.setRef = function setRef (ref, key) { if (!ref) { - return + return; } this._ref = ref._ref || ref; this._refs[key] = this._ref; }; - Transition.prototype.resolveData = function resolveData(props, type) { + Transition.prototype.resolveData = function resolveData (props, type) { var this$1 = this; var target = filterCollection(props[WEB.transition.collection])[0]; @@ -3685,7 +3673,7 @@ function buildWebTransition(Component, createElement) { if (element.key != null) { key$1 = element.key + key$1; } - if (target.type === 'component') { + if (target.type === "component") { var targetExp = target.exp; var thisTarget = this.state.transObj[this.state.tagKey]; var thisExp = thisTarget && thisTarget.exp; @@ -3699,7 +3687,7 @@ function buildWebTransition(Component, createElement) { this$1.setRef(ref, _props.key); element.ref && element.ref(ref); }; - if (target.type === 'component') { + if (target.type === "component") { _props[COMMON.setRef.name] = setRef; } else { _props.ref = setRef; @@ -3713,8 +3701,8 @@ function buildWebTransition(Component, createElement) { transObj: transObj, animated: true, tagKey: _props.key - } - } else if (type === 'update') { + }; + } else if (type === "update") { var tagKey = this.state.tagKey; var transition = this.state.transObj[tagKey]; // someone want to hide and his prev state is show @@ -3727,34 +3715,36 @@ function buildWebTransition(Component, createElement) { animated: true, transObj: transObj$1, tagKey: tagKey - } + }; } } }; - Transition.prototype.componentWillMount = function componentWillMount() { + Transition.prototype.UNSAFE_componentWillMount = function UNSAFE_componentWillMount () { this.transitionResolved = resolveTransition(this.props); this.isAppear = true; var state = this.resolveData(this.props); state && this.setState(state); }; - Transition.prototype.componentDidMount = function componentDidMount() { + Transition.prototype.componentDidMount = function componentDidMount () { this.resolveEnterTransition({ el: this._refs[this.state.tagKey] }); }; - Transition.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + Transition.prototype.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps (nextProps) { var this$1 = this; this.transitionResolved = resolveTransition(nextProps); this.isAppear = false; - var nextState = this.resolveData(nextProps, 'update'); + var nextState = this.resolveData(nextProps, "update"); if (nextState) { - this._shouldComponentUpdateTransitionResult = - this._shouldComponentUpdateTransition(nextProps, nextState); + this._shouldComponentUpdateTransitionResult = this._shouldComponentUpdateTransition( + nextProps, + nextState + ); this.setState(nextState); } @@ -3773,47 +3763,52 @@ function buildWebTransition(Component, createElement) { } }; - Transition.prototype._shouldComponentUpdateTransition = function _shouldComponentUpdateTransition(nextProps, nextState) { - if (Object.keys(nextState.transObj).length !== - Object.keys(this.state.transObj).length) { - return true + Transition.prototype._shouldComponentUpdateTransition = function _shouldComponentUpdateTransition (nextProps, nextState) { + if ( + Object.keys(nextState.transObj).length !== + Object.keys(this.state.transObj).length + ) { + return true; } if (nextState.tagKey === this.state.tagKey) { var nextTransition = nextState.transObj[nextState.tagKey]; var transition = this.state.transObj[this.state.tagKey]; if (nextTransition && transition) { - return transition.exp !== nextTransition.exp + return transition.exp !== nextTransition.exp; } } - return true + return true; }; - Transition.prototype.resolveEnterTransition = function resolveEnterTransition(option) { + Transition.prototype.resolveEnterTransition = function resolveEnterTransition (option) { enter.call(this, option); }; - Transition.prototype.resolveLeaveTransition = function resolveLeaveTransition(option) { + Transition.prototype.resolveLeaveTransition = function resolveLeaveTransition (option) { leave.call(this, option); }; - Transition.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState) { + Transition.prototype.componentDidUpdate = function componentDidUpdate (prevProps, prevState) { var this$1 = this; - if (this.state.animated === false || - this._shouldComponentUpdateTransitionResult === false) { - return + if ( + this.state.animated === false || + this._shouldComponentUpdateTransitionResult === false + ) { + return; } - if (this.state.tagKey === prevState.tagKey) { // same element + if (this.state.tagKey === prevState.tagKey) { + // same element var ref = this._refs[this.state.tagKey]; var transition = this.state.transObj[this.state.tagKey]; if (ref && transition) { - if (transition.type === 'show') { - ref.style.display = ''; + if (transition.type === "show") { + ref.style.display = ""; if (transition.exp === false) { this.resolveLeaveTransition({ el: ref, cb: function () { - ref.style.display = 'none'; + ref.style.display = "none"; } }); } else if (transition.exp === true) { @@ -3821,7 +3816,7 @@ function buildWebTransition(Component, createElement) { el: ref }); } - } else if (transition.type === 'if') { + } else if (transition.type === "if") { if (transition.exp === false) { var transObj = Object.assign({}, this.state.transObj); delete transObj[prevState.tagKey]; @@ -3861,24 +3856,28 @@ function buildWebTransition(Component, createElement) { } }; - Transition.prototype.render = function render() { + Transition.prototype.render = function render () { var transObj = this.state.transObj; var tag = this.props.tag || EmptyComponent; - return createElement(tag, null, Object.keys(transObj).map(function (k) { - var type = transObj[k].element.type; - var props = transObj[k].props; - var children = props.children; - return createElement(type, props, children) - })) + return createElement( + tag, + null, + Object.keys(transObj).map(function (k) { + var type = transObj[k].element.type; + var props = transObj[k].props; + var children = props.children; + return createElement(type, props, children); + }) + ); }; return Transition; }(Component)); - return Transition + return Transition; } function buildInputComponent(Component, createElement) { - return (function (superclass) { + return /*@__PURE__*/(function (superclass) { function Input(props) { superclass.call(this, props); this.state = { @@ -3886,49 +3885,54 @@ function buildInputComponent(Component, createElement) { }; } - if (superclass) Input.__proto__ = superclass; - Input.prototype = Object.create(superclass && superclass.prototype); + if ( superclass ) Input.__proto__ = superclass; + Input.prototype = Object.create( superclass && superclass.prototype ); Input.prototype.constructor = Input; - Input.prototype.buildStateProps = function buildStateProps(props) { + Input.prototype.buildStateProps = function buildStateProps (props) { var this$1 = this; var stateProps = superclass.prototype.buildStateProps.call(this, props); - var onChangeFn = stateProps.onChange || stateProps.onInput || function () { }; + var onChangeFn = + stateProps.onChange || stateProps.onInput || function() {}; stateProps.onChange = function (event) { this$1.setState({ props: Object.assign({}, this$1.state.props, { value: event.target.value }) }); - return onChangeFn(event) + return onChangeFn(event); }; - return handleProps(stateProps, props[WEB.inputComponent.tag]) + return handleProps(stateProps, props[WEB.inputComponent.tag]); }; - Input.prototype.setStateProps = function setStateProps(props) { + Input.prototype.setStateProps = function setStateProps (props) { var stateProps = this.buildStateProps(props); this.setState({ props: stateProps }); }; - Input.prototype.componentWillMount = function componentWillMount() { + Input.prototype.UNSAFE_componentWillMount = function UNSAFE_componentWillMount () { this.setStateProps(this.props); }; - Input.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + Input.prototype.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps (nextProps) { this.setStateProps(nextProps); }; - Input.prototype.render = function render() { - return createElement(this.props[WEB.inputComponent.tag], this.state.props, this.state.props.children) + Input.prototype.render = function render () { + return createElement( + this.props[WEB.inputComponent.tag], + this.state.props, + this.state.props.children + ); }; return Input; - }(buildMixin.apply(this, arguments))) + }(buildMixin.apply(this, arguments))); } var buildWebInputComponent = buildInputComponent; -function buildNativeComponent(render, options, config) { +function buildNativeComponent (render, options, config) { var Component = config.Component; var PropTypes = config.PropTypes; var Vue = config.Vue; @@ -3940,12 +3944,12 @@ function buildNativeComponent(render, options, config) { if (/^[A-Z]/.test(k) && deprecatedPackages.indexOf(k) === -1) { try { Vue.component(k, ReactNative[k]); - } catch (e) { } + } catch (e) {} } }); } - var ReactVueComponent = (function (Component) { - function ReactVueComponent(props) { + var ReactVueComponent = /*@__PURE__*/(function (Component) { + function ReactVueComponent (props) { Component.call(this, props); this._ref = null; this.eventOnceUid = []; @@ -3960,14 +3964,14 @@ function buildNativeComponent(render, options, config) { this.css = ReactNative.StyleSheet.create(css); } - if (Component) ReactVueComponent.__proto__ = Component; - ReactVueComponent.prototype = Object.create(Component && Component.prototype); + if ( Component ) ReactVueComponent.__proto__ = Component; + ReactVueComponent.prototype = Object.create( Component && Component.prototype ); ReactVueComponent.prototype.constructor = ReactVueComponent; /** * children can access parent instance by 'this.context.owner' */ - ReactVueComponent.prototype.getChildContext = function getChildContext() { + ReactVueComponent.prototype.getChildContext = function getChildContext () { return { owner: this } @@ -3976,7 +3980,7 @@ function buildNativeComponent(render, options, config) { /** * for event modifiers v-on:xxx.once */ - ReactVueComponent.prototype.setEventOnce = function setEventOnce(fn) { + ReactVueComponent.prototype.setEventOnce = function setEventOnce (fn) { var this$1 = this; var name = fn.name; @@ -3988,7 +3992,7 @@ function buildNativeComponent(render, options, config) { } }; - ReactVueComponent.prototype.setRootRef = function setRootRef(ref) { + ReactVueComponent.prototype.setRootRef = function setRootRef (ref) { if (ref) { ref = ref._ref || ref; this._ref = ref; @@ -3996,7 +4000,7 @@ function buildNativeComponent(render, options, config) { } }; - ReactVueComponent.prototype.setRef = function setRef(ref, text, inFor) { + ReactVueComponent.prototype.setRef = function setRef (ref, text, inFor) { if (ref) { // for buildin component, we set ref to his hold node directly // it means the buildin componet would be the end of $refs chain @@ -4013,7 +4017,7 @@ function buildNativeComponent(render, options, config) { } }; - ReactVueComponent.prototype.buildVM = function buildVM(options) { + ReactVueComponent.prototype.buildVM = function buildVM (options) { // set this property to prevent runtime error in vue render._withStripped = true; @@ -4049,7 +4053,7 @@ function buildNativeComponent(render, options, config) { return vm }; - ReactVueComponent.prototype.componentWillMount = function componentWillMount() { + ReactVueComponent.prototype.UNSAFE_componentWillMount = function UNSAFE_componentWillMount () { var this$1 = this; this.vm = this.buildVM(options); @@ -4063,36 +4067,36 @@ function buildNativeComponent(render, options, config) { this.beforeMount.forEach(function (v) { return v.call(this$1.vm); }); }; - ReactVueComponent.prototype.componentDidMount = function componentDidMount() { + ReactVueComponent.prototype.componentDidMount = function componentDidMount () { var this$1 = this; setTimeout(function () { this$1.mounted.forEach(function (v) { return v.call(this$1.vm); }); }, 0); }; - ReactVueComponent.prototype.componentWillUpdate = function componentWillUpdate() { + ReactVueComponent.prototype.UNSAFE_componentWillUpdate = function UNSAFE_componentWillUpdate () { var this$1 = this; this.beforeUpdate.forEach(function (v) { return v.call(this$1.vm); }); }; - ReactVueComponent.prototype.componentDidUpdate = function componentDidUpdate() { + ReactVueComponent.prototype.componentDidUpdate = function componentDidUpdate () { var this$1 = this; this.updated.forEach(function (v) { return v.call(this$1.vm); }); }; - ReactVueComponent.prototype.componentWillUnmount = function componentWillUnmount() { + ReactVueComponent.prototype.componentWillUnmount = function componentWillUnmount () { var this$1 = this; this.beforeDestroy.forEach(function (v) { return v.call(this$1.vm); }); }; - ReactVueComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + ReactVueComponent.prototype.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps (nextProps) { this.vm._props && Object.assign(this.vm._props, nextProps); this.vm.$slots = getSlots(nextProps.children); }; - ReactVueComponent.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { + ReactVueComponent.prototype.shouldComponentUpdate = function shouldComponentUpdate (nextProps) { return isObjectShallowModified(this.props, nextProps) }; - ReactVueComponent.prototype.render = function render$1() { + ReactVueComponent.prototype.render = function render$1 () { return render ? render.call(this, this.vm._renderProxy) : null }; @@ -4110,52 +4114,52 @@ function buildNativeComponent(render, options, config) { return ReactVueComponent } -exports.platformDirectives = index; -exports.renderList = renderList; -exports.renderSlot = renderSlot; -exports.bindWebClass = bindWebClass; +exports._toString = _toString; +exports.bind = bind; exports.bindNativeClass = bindNativeClass; -exports.bindWebStyle = bindWebStyle; exports.bindNativeStyle = bindNativeStyle; -exports.mergeNativeStyleAndNativeClass = mergeNativeStyleAndNativeClass; +exports.bindWebClass = bindWebClass; +exports.bindWebStyle = bindWebStyle; +exports.buildComponent = buildComponent; +exports.buildDirective = buildDirective; +exports.buildNativeComponent = buildNativeComponent; +exports.buildWebEmptyComponent = buildWebEmptyComponent; +exports.buildWebInputComponent = buildWebInputComponent; +exports.buildWebTransition = buildWebTransition; +exports.cached = cached; +exports.camelize = camelize; +exports.capitalize = capitalize; exports.checkKeyCodes = checkKeyCodes; -exports.template = template; -exports.event = event; -exports.mergeCssModule = mergeCssModule; exports.dynamicComponent = dynamicComponent; -exports.resolveFilter = resolveFilter; +exports.event = event; +exports.extend = extend; +exports.genStaticKeys = genStaticKeys; exports.handleProps = handleProps; -exports.mergeProps = mergeProps; -exports.isUndef = isUndef; +exports.hasOwn = hasOwn; +exports.hyphenate = hyphenate; +exports.identity = identity; +exports.isBuiltInTag = isBuiltInTag; exports.isDef = isDef; -exports.isTrue = isTrue; -exports.isPrimitive = isPrimitive; exports.isObject = isObject; exports.isPlainObject = isPlainObject; -exports._toString = _toString; -exports.toNumber = toNumber; +exports.isPrimitive = isPrimitive; +exports.isTrue = isTrue; +exports.isUndef = isUndef; +exports.looseEqual = looseEqual; +exports.looseIndexOf = looseIndexOf; exports.makeMap = makeMap; -exports.isBuiltInTag = isBuiltInTag; +exports.mergeCssModule = mergeCssModule; +exports.mergeNativeStyleAndNativeClass = mergeNativeStyleAndNativeClass; +exports.mergeProps = mergeProps; +exports.no = no; +exports.noop = noop; +exports.once = once; +exports.platformDirectives = index; exports.remove = remove; -exports.hasOwn = hasOwn; -exports.cached = cached; -exports.camelize = camelize; -exports.capitalize = capitalize; -exports.hyphenate = hyphenate; -exports.bind = bind; +exports.renderList = renderList; +exports.renderSlot = renderSlot; +exports.resolveFilter = resolveFilter; +exports.template = template; exports.toArray = toArray; -exports.extend = extend; +exports.toNumber = toNumber; exports.toObject = toObject; -exports.noop = noop; -exports.no = no; -exports.identity = identity; -exports.genStaticKeys = genStaticKeys; -exports.looseEqual = looseEqual; -exports.looseIndexOf = looseIndexOf; -exports.once = once; -exports.buildComponent = buildComponent; -exports.buildDirective = buildDirective; -exports.buildWebTransition = buildWebTransition; -exports.buildWebEmptyComponent = buildWebEmptyComponent; -exports.buildWebInputComponent = buildWebInputComponent; -exports.buildNativeComponent = buildNativeComponent; diff --git a/packages/vue-native-helper/package.json b/packages/vue-native-helper/package.json index 554323c..ae40786 100644 --- a/packages/vue-native-helper/package.json +++ b/packages/vue-native-helper/package.json @@ -18,12 +18,6 @@ "url": "https://github.com/GeekyAnts/vue-native-core/issues" }, "homepage": "https://github.com/GeekyAnts/vue-native-core#readme", - "dependencies": { - "he": "^1.1.0", - "de-indent": "^1.0.2", - "change-case": "^3.0.1", - "prop-types": "^15.5.10" - }, "peerDependencies": { "react": "*" } diff --git a/packages/vue-native-scripts/.eslintrc b/packages/vue-native-scripts/.eslintrc deleted file mode 100644 index 6c86334..0000000 --- a/packages/vue-native-scripts/.eslintrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": ["eslint:recommended"], - "env": { - "es6": true, - "node": true - }, - "rules": { - "semi": 1, - "no-extra-semi": 1, - "no-console": 0, - "no-undef-init": 1, - "quotes": [2, "single"], - "strict": [2, "never"] - } -} \ No newline at end of file diff --git a/packages/vue-native-scripts/src/bin/vue-native-script.js b/packages/vue-native-scripts/bin/vue-native-script.js similarity index 100% rename from packages/vue-native-scripts/src/bin/vue-native-script.js rename to packages/vue-native-scripts/bin/vue-native-script.js diff --git a/packages/vue-native-scripts/build.js b/packages/vue-native-scripts/build.js new file mode 100644 index 0000000..275ff86 --- /dev/null +++ b/packages/vue-native-scripts/build.js @@ -0,0 +1,562 @@ +'use strict'; + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var compiler = require('vue-native-template-compiler'); +var cssParse = _interopDefault(require('css-parse')); +var jsBeautify = require('js-beautify'); +var sourceMap = require('source-map'); +var sourceMap__default = _interopDefault(sourceMap); +var hash$1 = _interopDefault(require('hash-sum')); +var path = _interopDefault(require('path')); +var lineNumber = _interopDefault(require('line-number')); +var parse5 = _interopDefault(require('parse5')); +var babelCore = require('babel-core'); +var semver = _interopDefault(require('semver')); +var traverse$1 = _interopDefault(require('babel-traverse')); +var package_json = require('react-native/package.json'); + +var HELPER_HEADER = '__react__vue__'; +var SCRIPT_OPTIONS = HELPER_HEADER + "options"; +var TEMPLATE_RENDER = HELPER_HEADER + "render"; +var REACT_NATIVE = HELPER_HEADER + "ReactNative"; +var BUILD_COMPONENT = HELPER_HEADER + "buildNativeComponent"; +var COMPONENT_BUILDED = HELPER_HEADER + "ComponentBuilded"; +var VUE = HELPER_HEADER + "Vue"; +var REACT = HELPER_HEADER + "React"; +var COMPONENT = HELPER_HEADER + "Component"; +var PROP_TYPE = HELPER_HEADER + "PropType"; +var OBSERVER = HELPER_HEADER + "observer"; +var CSS = HELPER_HEADER + "css"; + +var constants = { + HELPER_HEADER: HELPER_HEADER, + SCRIPT_OPTIONS: SCRIPT_OPTIONS, + TEMPLATE_RENDER: TEMPLATE_RENDER, + REACT_NATIVE: REACT_NATIVE, + BUILD_COMPONENT: BUILD_COMPONENT, + COMPONENT_BUILDED: COMPONENT_BUILDED, + VUE: VUE, + REACT: REACT, + COMPONENT: COMPONENT, + PROP_TYPE: PROP_TYPE, + OBSERVER: OBSERVER, + CSS: CSS +}; + +var names = 'Infinity,undefined,NaN,isFinite,isNaN,console,' + + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + + 'require,' + // for webpack + 'arguments'; // parsed as identifier but is a special keyword... + +var hash = Object.create(null); +names.split(',').forEach(function (name) { + hash[name] = true; +}); + +function addvm (code) { + var r = babelCore.transform(code, { + plugins: [function (ref) { + var t = ref.types; + + return { + visitor: { + Identifier: function (path) { + if (path.parent.type === 'ObjectProperty' && path.parent.key === path.node) { return; } + if (t.isDeclaration(path.parent.type) && path.parent.id === path.node) { return; } + if (t.isFunction(path.parent.type) && path.parent.params.indexOf(path.node) > -1) { return; } + if (path.parent.type === 'Property' && path.parent.key === path.node && !path.parent.computed) { return; } + if (path.parent.type === 'MemberExpression' && path.parent.property === path.node && !path.parent.computed) { return; } + if (path.parent.type === 'ArrayPattern') { return; } + if (path.parent.type === 'ImportSpecifier') { return; } + if (path.scope.hasBinding(path.node.name)) { return; } + if (hash[path.node.name]) { return; } + if (path.node.name.indexOf(constants.HELPER_HEADER) === 0) { return; } + path.node.name = "vm['" + (path.node.name) + "']"; + } + } + }; + }] + }); + return r.code; +} + +var TRANSFORM_TRANSLATE_REGEX = /translate\(([-+]?[\d]*\.?[\d]+)(px)?,[\s]+([-+]?[\d]*\.?[\d]+)(px)?\)/; +var TRANSFORM_TRANSLATE_X_REGEX = /translateX\(([-+]?[\d]*\.?[\d]+)(px)?\)/; +var TRANSFORM_TRANSLATE_Y_REGEX = /translateY\(([-+]?[\d]*\.?[\d]+)(px)?\)/; +var TRANSFORM_ROTATE_REGEX = /rotate\(([-+]?[\d]*\.?[\d]+)deg\)/; +var TRANSFORM_ROTATE_X_REGEX = /rotateX\(([-+]?[\d]*\.?[\d]+)deg\)/; +var TRANSFORM_ROTATE_Y_REGEX = /rotateY\(([-+]?[\d]*\.?[\d]+)deg\)/; +var TRANSFORM_ROTATE_Z_REGEX = /rotateZ\(([-+]?[\d]*\.?[\d]+)deg\)/; +var TRANSFORM_SCALE_REGEX = /scale\(([-+]?[\d]*\.?[\d]+)\)/; +var TRANSFORM_SCALE_X_REGEX = /scaleX\(([-+]?[\d]*\.?[\d]+)\)/; +var TRANSFORM_SCALE_Y_REGEX = /scaleY\(([-+]?[\d]*\.?[\d]+)\)/; +var TRANSFORM_SKEW_X_REGEX = /skewX\(([-+]?[\d]*\.?[\d]+)deg\)/; +var TRANSFORM_SKEW_Y_REGEX = /skewY\(([-+]?[\d]*\.?[\d]+)deg\)/; + +function parseTransform(value) { + var arr = []; + if (TRANSFORM_ROTATE_REGEX.test(value)) { + arr.push({ + rotate: ((value.match(TRANSFORM_ROTATE_REGEX)[1]) + "deg") + }); + } + if (TRANSFORM_ROTATE_X_REGEX.test(value)) { + arr.push({ + rotateX: ((value.match(TRANSFORM_ROTATE_X_REGEX)[1]) + "deg") + }); + } + if (TRANSFORM_ROTATE_Y_REGEX.test(value)) { + arr.push({ + rotateY: ((value.match(TRANSFORM_ROTATE_Y_REGEX)[1]) + "deg") + }); + } + if (TRANSFORM_ROTATE_Z_REGEX.test(value)) { + arr.push({ + rotateZ: ((value.match(TRANSFORM_ROTATE_Z_REGEX)[1]) + "deg") + }); + } + if (TRANSFORM_SKEW_X_REGEX.test(value)) { + arr.push({ + skewX: ((value.match(TRANSFORM_SKEW_X_REGEX)[1]) + "deg") + }); + } + if (TRANSFORM_SKEW_Y_REGEX.test(value)) { + arr.push({ + skewY: ((value.match(TRANSFORM_SKEW_Y_REGEX)[1]) + "deg") + }); + } + if (TRANSFORM_SCALE_REGEX.test(value)) { + var r = value.match(TRANSFORM_SCALE_REGEX)[1]; + if (isNaN(r) === false) { + r = parseFloat(r); + } + arr.push({ + scale: r + }); + } + if (TRANSFORM_SCALE_X_REGEX.test(value)) { + var r$1 = value.match(TRANSFORM_SCALE_X_REGEX)[1]; + if (isNaN(r$1) === false) { + r$1 = parseFloat(r$1); + } + arr.push({ + scaleX: r$1 + }); + } + if (TRANSFORM_SCALE_Y_REGEX.test(value)) { + var r$2 = value.match(TRANSFORM_SCALE_Y_REGEX)[1]; + if (isNaN(r$2) === false) { + r$2 = parseFloat(r$2); + } + arr.push({ + scaleY: r$2 + }); + } + if (TRANSFORM_TRANSLATE_REGEX.test(value)) { + var rs = value.match(TRANSFORM_TRANSLATE_REGEX); + var rx = rs[1]; + var ry = rs[2]; + if (isNaN(rx) === false) { + rx = parseFloat(rx); + } + if (isNaN(ry) === false) { + ry = parseFloat(ry); + } + arr.push({ + translateX: rx + }); + arr.push({ + translateY: ry + }); + } + if (TRANSFORM_TRANSLATE_X_REGEX.test(value)) { + var r$3 = value.match(TRANSFORM_TRANSLATE_X_REGEX)[1]; + if (isNaN(r$3) === false) { + r$3 = parseFloat(r$3); + } + arr.push({ + translateX: r$3 + }); + } + if (TRANSFORM_TRANSLATE_Y_REGEX.test(value)) { + var r$4 = value.match(TRANSFORM_TRANSLATE_Y_REGEX)[1]; + if (isNaN(r$4) === false) { + r$4 = parseFloat(r$4); + } + arr.push({ + translateY: r$4 + }); + } + return arr; +} + +var camelizeRE = /-(\w)/g; + +function camelize(str) { + return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) +} + +function parseDeclarations(declarations) { + var declarationObj = {}; + + // Comments and @media blocks don't have declarations at the top level. + if (declarations) { + declarations.forEach(function (declaration) { + if (declaration.type === 'declaration') { + var value = declaration.value; + if (/px$/.test(value)) { + value = parseFloat(value.replace(/px$/, '')); + } else if (declaration.property !== 'font-weight' && isNaN(value) === false){ + value = parseFloat(value); + } + if (declaration.property === 'transform') { + value = parseTransform(value); + } + declarationObj[camelize(declaration.property)] = value; + } + }); + } + + return declarationObj; +} + +function parseCss(ast) { + var obj = {}; + if (ast.type === 'stylesheet') { + ast.stylesheet.rules.forEach(function (rule) { + var declarationObj = parseDeclarations(rule.declarations); + if (rule.selectors) { + rule.selectors.forEach(function (selector) { + if (selector.indexOf('.') === 0) { + obj[selector.replace(/^\./, '')] = declarationObj; + } + }); + } + }); + } + return obj; +} + +// const fs = require('fs'); + +var filePath = 'test.js'; +var splitRE = /\r?\n/g; + +var DEFAULT_OUTPUT = { + template: { + import: ("import { Component as " + (constants.COMPONENT) + " } from 'react'"), + render: ("const " + (constants.TEMPLATE_RENDER) + " = () => null") + }, + script: ("const " + (constants.SCRIPT_OPTIONS) + " = {}") +}; + +function compileVueToRn(resource) { + var code = resource.toString(); + var cparsed = compiler.parseComponent(code, { pad: 'line' }); + + var output = ''; + var mappings = ''; + + // add react-vue import + output += "import " + (constants.VUE) + ", { observer as " + (constants.OBSERVER) + " } from 'vue-native-core'"; + output += '\n'; + + // // add react import + // output += `import ${constants.REACT} from 'react'` + // output += '\n'; + + // add react-native import + output += "import " + (constants.REACT_NATIVE) + " from 'react-native'"; + output += '\n'; + + // add prop-type import + output += "import " + (constants.PROP_TYPE) + " from 'prop-types'"; + output += '\n'; + + // add component builder import + output += "import { buildNativeComponent as " + (constants.BUILD_COMPONENT) + " } from 'vue-native-helper'"; + output += '\n'; + + // parse template + var template = cparsed.template; + + //Consider the start of template for debugging + // + var templateStartIndex = code.indexOf("<"); + var tempStringBeforeStart = code.substring(0, templateStartIndex); + var templateLineNumber = tempStringBeforeStart.split(splitRE).length - 1; + + // Get tags and location of tags from template + // + var nodes = []; + var templateFragments = parse5.parseFragment(cparsed.template.content, { sourceCodeLocationInfo: true }); + if (templateFragments.childNodes) { + traverse(templateFragments, nodes); + } + + + var templateParsed = DEFAULT_OUTPUT.template; + if (template) { + var templateContent = template.content.replace(/\/\/\n/g, '').trim(); + if (templateContent) { + templateParsed = parseTemplate(templateContent); + } + } + + // add render dep import + output += templateParsed.import; + output += '\n'; + + // parse script + var script = cparsed.script; + var scriptParsed = DEFAULT_OUTPUT.script; + if (script) { + var scriptContent = script.content.replace(/\/\/\n/g, '').trim(); + scriptParsed = parseScript(scriptContent); + mappings = generateSourceMap(code); + } + + if (mappings) { + // Start of the script content + // + var beforeLines = output.split(splitRE).length; + // Start of the script content of the original code + // + var scriptLine = code.slice(0, cparsed.script.start).split(splitRE).length + 1; + var exportDefaultIndex = code.indexOf('export default'); + var tempString = code.substring(0, exportDefaultIndex); + var exportDefaultLineNumber = tempString.split('\n').length; + } + + // add vue options + output += scriptParsed; + output += '\n\n'; + + var endLines = output.split(splitRE).length - 1; + for (; scriptLine < endLines; scriptLine++) { + //Skip export default line + if (scriptLine !== exportDefaultLineNumber) { + mappings.addMapping({ + source: mappings._hashedFilename, + generated: { + line: beforeLines, + column: 0 + }, + original: { + line: scriptLine, + column: 0 + } + }); + } + beforeLines++; + } + + // add render funtion + var beautifiedRender = jsBeautify.js_beautify(addvm(templateParsed.render)); + output += beautifiedRender; + output += '\n\n'; + + // Get last line of render code + // + var renderEndLine = beautifiedRender.split(splitRE).length - 1; + + // Search Elements and postion based on render function + // + var reactVueElementRegex = /__react__vue__createElement/; + var foundLines = lineNumber(beautifiedRender, reactVueElementRegex); + if (mappings) { + foundLines.forEach(function (line, index) { + var renderJsLine = endLines + line.number; + if (foundLines[index + 1]) { + for (var i = line.number; i < foundLines[index + 1].number; i++) { + // Add Mapping + if (nodes[index]) { + mappings.addMapping({ + source: mappings._hashedFilename, + generated: { + line: renderJsLine++, + column: 0 + }, + original: { + line: nodes[index].startTag.startLine + templateLineNumber, + column: 0 + } + }); + } + } + } else if (nodes[index] && nodes[index].startTag) { + // Last Line + for (var i$1 = line.number; i$1 < renderEndLine; i$1++) { + // Add Mapping + mappings.addMapping({ + source: mappings._hashedFilename, + generated: { + line: renderJsLine++, + column: 0 + }, + original: { + line: nodes[index].startTag.startLine + templateLineNumber, + column: 0 + } + }); + } + } + }); + } + + // parse css + var styles = cparsed.styles; + var cssParsed = {}; + styles.forEach(function (v) { + var cssAst = cssParse(v.content); + cssParsed = Object.assign({}, cssParsed, parseCss(cssAst)); + }); + + // add css obj + output += "const " + (constants.CSS) + " = " + (JSON.stringify(cssParsed)); + output += '\n\n'; + + // add builder + output += "const " + (constants.COMPONENT_BUILDED) + " = " + (constants.BUILD_COMPONENT) + "(" + (constants.TEMPLATE_RENDER) + ", " + (constants.SCRIPT_OPTIONS) + ", {Component: " + (constants.COMPONENT) + ", PropTypes: " + (constants.PROP_TYPE) + ", Vue: " + (constants.VUE) + ", ReactNative: " + (constants.REACT_NATIVE) + ", css: " + (constants.CSS) + "})"; + output += '\n\n'; + + // export default + output += "export default " + (constants.OBSERVER) + "(" + (constants.COMPONENT_BUILDED) + ")"; + + // beautiful + // output = beautify(output, { indent_size: 2 }); + return { output: output, mappings: mappings ? mappings.toJSON() : null }; +} + +// function remove(name) { +// fs.unlink(name.replace(FILTER, '.js'), function(err) { +// if (err) { +// throw err; +// } +// }); +// } + +function parseTemplate(code) { + var obj = compiler.nativeCompiler(code); + return { + import: obj.importCode, + render: ("const " + (constants.TEMPLATE_RENDER) + " = " + (obj.renderCode)) + }; +} + +function generateSourceMap(content) { + // hot-reload source map busting + var hashedFilename = path.basename(filePath) + '?' + hash$1(filePath + content); + var map = new sourceMap__default.SourceMapGenerator(); + map.setSourceContent(hashedFilename, content); + map._hashedFilename = hashedFilename; + return map; +} + +function parseScript(code) { + var s = "const " + (constants.SCRIPT_OPTIONS) + " = "; + code = code + .replace(/[\s;]*module.exports[\s]*=/, ("\n" + s)) + .replace(/[\s;]*export[\s]+default[\s]*\{/, ("\n" + s + " {")); + return code; +} + +function traverse(ast, nodes) { + if ( nodes === void 0 ) nodes = []; + + if (ast.tagName) { + nodes.push(ast.sourceCodeLocation); + } + if (ast.childNodes) { + ast.childNodes.forEach(function (child) { + traverse(child, nodes); + }); + } +} + +// const reactNativeVersionString = require('react-native/package.json').version; +var reactNativeMinorVersion = semver(package_json.version).minor; + +var upstreamTransformer = null; +if (reactNativeMinorVersion >= 59) { + upstreamTransformer = require("metro-react-native-babel-transformer"); +} else if (reactNativeMinorVersion >= 56) { + upstreamTransformer = require('metro/src/reactNativeTransformer'); +} else if (reactNativeMinorVersion >= 52) { + upstreamTransformer = require('metro/src/transformer'); +} else if (reactNativeMinorVersion >= 47) { + upstreamTransformer = require('metro-bundler/src/transformer'); +} else if (reactNativeMinorVersion === 46) { + upstreamTransformer = require('metro-bundler/build/transformer'); +} else { + // handle RN <= 0.45 + var oldUpstreamTransformer = require('react-native/packager/transformer'); + upstreamTransformer = { + transform: function transform(ref) { + var src = ref.src; + var filename = ref.filename; + var options = ref.options; + + return oldUpstreamTransformer.transform(src, filename, options); + } + }; +} + +function sourceMapAstInPlace(tsMap, babelAst) { + var tsConsumer = new sourceMap.SourceMapConsumer(tsMap); + traverse$1.cheap(babelAst, function (node) { + if (node.loc) { + var originalStart = tsConsumer.originalPositionFor(node.loc.start); + if (originalStart.line) { + node.loc.start.line = originalStart.line; + node.loc.start.column = originalStart.column; + } + var originalEnd = tsConsumer.originalPositionFor(node.loc.end); + if (originalEnd.line) { + node.loc.end.line = originalEnd.line; + node.loc.end.column = originalEnd.column; + } + } + }); +} + +function transform(ref) { + var assign; + + var src = ref.src; + var filename = ref.filename; + var options = ref.options; + if (typeof src === 'object') { + // handle RN >= 0.46 + ((assign = src, src = assign.src, filename = assign.filename, options = assign.options)); + } + var outputFile = compileVueToRn(src); + + if (!outputFile.output) { + return upstreamTransformer.transform({ + src: outputFile, + filename: filename, + options: options + }); + } else { + // Source Map support + var babelCompileResult = upstreamTransformer.transform({ + src: outputFile.output, + filename: filename, + options: options + }); + if (outputFile.mappings) { + sourceMapAstInPlace(outputFile.mappings, babelCompileResult.ast); + } + return babelCompileResult; + } +} + +var index = { + compileVueToRn: compileVueToRn, + transform: transform, +}; + +module.exports = index; diff --git a/packages/vue-native-scripts/index.js b/packages/vue-native-scripts/index.js index 45a97f6..45b74df 100644 --- a/packages/vue-native-scripts/index.js +++ b/packages/vue-native-scripts/index.js @@ -1,3 +1 @@ -// module.exports = require('./src/bin/vue-native-script.js'); -module.exports.compileVueToRn = require('./src/scripts/compiler.js'); -module.exports.transform = require('./src/scripts/transformerPlugin.js'); +module.exports = require('./build.js') \ No newline at end of file diff --git a/packages/vue-native-scripts/package.json b/packages/vue-native-scripts/package.json index 90f659e..2d569d0 100644 --- a/packages/vue-native-scripts/package.json +++ b/packages/vue-native-scripts/package.json @@ -14,17 +14,20 @@ "babel-traverse": "^6.26.0", "cross-spawn": "^5.1.0", "css-parse": "^2.0.0", - "fs-extra": "^3.0.1", "hash-sum": "^1.0.2", "js-beautify": "^1.6.14", "line-number": "^0.1.0", - "node-watch": "^0.5.4", "parse5": "^5.0.0", - "vue-native-template-compiler": "^0.0.13", - "walk": "^2.3.9" + "path": "^0.12.7", + "semver": "^6.2.0", + "source-map": "^0.7.3", + "vue-native-template-compiler": "^0.0.13" }, - "devDependencies": { - "eslint": "^4.0.0" + "peerDependencies": { + "react-native": "*", + "metro": "*", + "metro-bundler": "*", + "metro-react-native-babel-transformer": "*" }, "bugs": { "url": "https://github.com/GeekyAnts/vue-native-core/issues" diff --git a/packages/vue-native-scripts/src/util/walk.js b/packages/vue-native-scripts/src/util/walk.js deleted file mode 100644 index a06b70e..0000000 --- a/packages/vue-native-scripts/src/util/walk.js +++ /dev/null @@ -1,42 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -function _walk (dir, options, cb) { - if (fs.existsSync(dir)) { - if (fs.statSync(dir).isDirectory()) { - fs.readdir(dir, function(err, all) { - if (err) { - // don't throw permission errors. - if (!/^(EPERM|EACCES)$/.test(err.code)) { - throw err; - } else { - console.warn('Warning: Cannot access %s.', dir); - } - } else if (Array.isArray(all)) { - all.forEach(function(f) { - var sdir = path.join(dir, f); - if (fs.existsSync(sdir) && f !== 'node_modules') { - if (fs.statSync(sdir).isDirectory()) { - _walk(sdir, options, cb); - } else if (options.filter.test(sdir)){ - cb(sdir); - } - } - }); - } - }); - } else if (options.filter.test(dir)){ - cb(dir); - } - } -} - -module.exports = function walk (dir, options, cb) { - if (typeof options === 'function') { - cb = options; - options = { - filter: /./ - }; - } - return _walk(dir, options, cb); -}; diff --git a/packages/vue-native-scripts/src/util/watch/has-native-recursive.js b/packages/vue-native-scripts/src/util/watch/has-native-recursive.js deleted file mode 100644 index 08c3467..0000000 --- a/packages/vue-native-scripts/src/util/watch/has-native-recursive.js +++ /dev/null @@ -1,100 +0,0 @@ -var fs = require('fs'); -var os = require('os'); -var path = require('path'); -var is = require('./is'); - -var IS_SUPPORT; -var TEMP_DIR = os.tmpdir && os.tmpdir() - || process.env.TMPDIR - || process.env.TEMP - || process.cwd(); - -function TempStack() { - this.stack = []; -} - -TempStack.prototype = { - create: function(type, base) { - var name = path.join(base, - 'node-watch-' + Math.random().toString(16).substr(2) - ); - this.stack.push({ name: name, type: type }); - return name; - }, - write: function(/* file */) { - for (var i = 0; i < arguments.length; ++i) { - fs.writeFileSync(arguments[i], ' '); - } - }, - mkdir: function(/* dirs */) { - for (var i = 0; i < arguments.length; ++i) { - fs.mkdirSync(arguments[i]); - } - }, - cleanup: function(fn) { - try { - var temp; - while (temp = this.stack.pop()) { - var type = temp.type; - var name = temp.name; - if (type == 'file' && is.file(name)) { - fs.unlinkSync(name); - } - else if (type == 'dir' && is.directory(name)) { - fs.rmdirSync(name); - } - } - } - finally { - if (is.func(fn)) fn(); - } - } -}; - -var pending = false; - -module.exports = function hasNativeRecursive(fn) { - if (!is.func(fn)) { - return false; - } - if (IS_SUPPORT !== undefined) { - return fn(IS_SUPPORT); - } - - if (!pending) { - pending = true; - } - // check again later - else { - return setTimeout(function() { - hasNativeRecursive(fn); - }, 300); - } - - var stack = new TempStack(); - var parent = stack.create('dir', TEMP_DIR); - var child = stack.create('dir', parent); - var file = stack.create('file', child); - - stack.mkdir(parent, child); - - var options = { recursive: true }; - var watcher = fs.watch(parent, options); - var timer = setTimeout(function() { - watcher.close(); - stack.cleanup(function() { - fn(IS_SUPPORT = false); - }); - }, 200); - - watcher.on('change', function(evt, name) { - if (path.basename(file) == path.basename(name)) { - watcher.close(); - clearTimeout(timer); - stack.cleanup(function() { - fn(IS_SUPPORT = true); - }); - } - }); - stack.write(file); -} diff --git a/packages/vue-native-scripts/src/util/watch/index.js b/packages/vue-native-scripts/src/util/watch/index.js deleted file mode 100644 index 0cecdac..0000000 --- a/packages/vue-native-scripts/src/util/watch/index.js +++ /dev/null @@ -1,360 +0,0 @@ -var fs = require('fs'); -var path = require('path'); -var os = require('os'); -var util = require('util'); -var events = require('events'); - -var hasNativeRecursive = require('./has-native-recursive'); -var is = require('./is'); - -var EVENT_UPDATE = 'update'; -var EVENT_REMOVE = 'remove'; - -function makeArray(arr, offset) { - return is.array(arr) - ? arr : [].slice.call(arr, offset || 0); -} - -function hasDup(arr) { - return makeArray(arr).some(function(v, i, self) { - return self.indexOf(v) !== i; - }); -} - -function unique(arr) { - return makeArray(arr).filter(function(v, i, self) { - return self.indexOf(v) === i; - }); -} - -function assign(obj/*, props */) { - if (Object.assign) { - return Object.assign.apply(Object, arguments); - } - return makeArray(arguments, 1) - .reduce(function(mix, prop) { - for (var name in prop) { - if (prop.hasOwnProperty(name)) { - mix[name] = prop[name]; - } - } - return mix; - }, obj); -} - -function guard(fn) { - return function(arg, action) { - if (is.func(fn)) { - if (fn(arg)) action(); - } - else if (is.regExp(fn)) { - if (fn.test(arg)) action(); - } - else { - action(); - } - } -} - -function composeMessage(names) { - return makeArray(names).map(function(n) { - if (!is.exists(n)) return [EVENT_REMOVE, n]; - else return [EVENT_UPDATE, n]; - }); -} - -function getMessages(cache) { - var dup = hasDup(cache.map(function(c) { - return c.replace(/^[~#]+|[~#]+$/, ''); - })); - - // saving file from an editor maybe? - if (dup) { - var filtered = cache.filter(function(m) { - return is.exists(m) - }); - return composeMessage(unique(filtered)); - } - else { - return composeMessage(cache); - } -} - -function debounce(fn, delay) { - var timer, cache = []; - var info = fn.info; - function handle() { - getMessages(cache).forEach(function(msg) { - if (info.options.encoding == 'buffer') { - msg[1] = new Buffer(msg[1]); - } - fn.apply(null, msg); - }); - timer = null; - cache = []; - } - return function(evt, name) { - if (is.buffer(name)) { - name = name.toString() - } - if (is.nil(name)) { - name = ''; - } - cache.push( - path.join(info.fpath, name) - ); - if (!timer) { - timer = setTimeout(handle, delay || 200); - } - } -} - -function getSubDirectories(dir, fn) { - if (is.directory(dir)) { - fs.readdir(dir, function(err, all) { - if (err) { - // don't throw permission errors. - if (!/^(EPERM|EACCES)$/.test(err.code)) throw err; - else console.warn('Warning: Cannot access %s.', dir); - } - else if (is.array(all)) { - all.forEach(function(f) { - var sdir = path.join(dir, f); - if (is.directory(sdir)) fn(sdir); - }); - } - }); - } -} - -var deprecationWarning = util.deprecate( - function() {}, - '(node-watch) First param in callback function\ - is replaced with event name since 0.5.0, use\ - `(evt, filename) => {}` if you want to get the filename' -); - -function Watcher() { - events.EventEmitter.call(this); - this.watchers = {}; -} - -util.inherits(Watcher, events.EventEmitter); - -Watcher.prototype.expose = function() { - var self = this; - var methods = [ - 'on', 'emit', 'close', 'isClosed', 'listeners', 'once', - 'setMaxListeners', 'getMaxListeners' - ]; - return methods.reduce(function(expose, name) { - expose[name] = function() { - return self[name].apply(self, arguments); - } - return expose; - }, {}); -} - -Watcher.prototype.isClosed = function() { - return !Object.keys(this.watchers).length -} - -Watcher.prototype.close = function(fullPath) { - var self = this; - if (fullPath) { - var watcher = this.watchers[fullPath]; - if (watcher && watcher.close) { - watcher.close(); - delete self.watchers[fullPath]; - } - getSubDirectories(fullPath, function(fpath) { - self.close(fpath); - }); - } else { - var self = this; - Object.keys(self.watchers).forEach(function(fpath) { - var watcher = self.watchers[fpath]; - if (watcher && watcher.close) { - watcher.close(); - } - }); - this.watchers = {}; - } -}; - -Watcher.prototype.add = function(watcher, info) { - var self = this; - info = info || {}; - var fullPath = path.resolve(info.fpath); - this.watchers[fullPath] = watcher; - - var callback = function(evt, name) { - if (info.options.recursive) { - hasNativeRecursive(function(has) { - if (!has) { - var fullPath = path.resolve(name); - // remove watcher on removal - if (evt == EVENT_REMOVE) { - self.close(fullPath); - } - // watch new created directory - else if (is.directory(name) && !self.watchers[fullPath]) { - var filterGuard = guard(info.options.filter); - filterGuard(name, function() { - self.watchDirectory(name, info.options); - }); - } - } - }); - } - - // watch single file - if (info.compareName) { - if (info.compareName(name)) { - self.emit('change', evt, name); - } - } - // watch directory - else { - var filterGuard = guard(info.options.filter); - filterGuard(name, function() { - if (self.flag) self.flag = ''; - else self.emit('change', evt, name); - }); - } - }; - - callback.info = info; - - watcher.on('error', function(err) { - if (os.platform() == 'win32' && err.code == 'EPERM') { - watcher.emit('change', EVENT_REMOVE, info.fpath && ''); - self.flag = 'windows-error'; - self.close(fullPath); - } else { - self.emit('error', err); - } - }); - - watcher.on('change', debounce(callback)); -} - -Watcher.prototype.watchFile = function(file, options, fn) { - var parent = path.join(file, '../'); - var opts = assign({}, options, { - recursive: false, - filter: null - }); - - var watcher = fs.watch(parent, opts); - this.add(watcher, { - type: 'file', - fpath: parent, - options: opts, - compareName: function(n) { - return is.sameFile(n, file); - } - }); - - if (is.func(fn)) { - if (fn.length == 1) deprecationWarning(); - this.on('change', fn); - } -} - -Watcher.prototype.watchDirectory = function(dir, options, fn) { - var self = this; - hasNativeRecursive(function(has) { - options.recursive = !!options.recursive; - var opts = assign({}, options); - if (!has) { - opts = assign(opts, { recursive: false }); - } - var watcher = fs.watch(dir, opts); - - self.add(watcher, { - type: 'dir', - fpath: dir, - options: options - }); - - if (is.func(fn)) { - if (fn.length == 1) deprecationWarning(); - self.on('change', fn); - } - - if (options.recursive && !has) { - getSubDirectories(dir, function(d) { - var filterGuard = guard(options.filter); - filterGuard(d, function() { - self.watchDirectory(d, options); - }); - }); - } - }); -} - -function composeWatcher(watchers) { - var watcher = new Watcher(); - watchers.forEach(function(w) { - w.on('change', function(evt, name) { - watcher.emit('change', evt, name); - }); - w.on('error', function(err) { - watcher.emit('error', err); - }); - }); - watcher.close = function() { - watchers.forEach(function(w) { - w.close(); - }); - } - return watcher.expose(); -} - -function watch(fpath, options, fn) { - var watcher = new Watcher(); - - if (is.buffer(fpath)) { - fpath = fpath.toString(); - } - - if (is.array(fpath)) { - return composeWatcher(unique(fpath).map(function(f) { - return watch(f, options, fn); - })); - }; - - if (!is.exists(fpath)) { - watcher.emit('error', - new Error(fpath + ' does not exist.') - ); - } - - if (is.string(options)) { - options = { - encoding: options - } - } - - if (is.func(options)) { - fn = options; - options = {}; - } - - if (arguments.length < 2) { - options = {}; - } - - if (is.file(fpath)) { - watcher.watchFile(fpath, options, fn); - } - - else if (is.directory(fpath)) { - watcher.watchDirectory(fpath, options, fn); - } - - return watcher.expose(); -} - -module.exports = watch; diff --git a/packages/vue-native-scripts/src/util/watch/is.js b/packages/vue-native-scripts/src/util/watch/is.js deleted file mode 100644 index ab2aef2..0000000 --- a/packages/vue-native-scripts/src/util/watch/is.js +++ /dev/null @@ -1,43 +0,0 @@ -var fs = require('fs'); -var path = require('path'); - -var is = { - nil: function(item) { - return (item === null) || (item === undefined); - }, - array: function(item) { - return Array.isArray(item); - }, - buffer: function(item) { - return Buffer.isBuffer(item); - }, - regExp: function(item) { - return Object.prototype.toString.call(item) == '[object RegExp]'; - }, - string: function(item) { - return typeof item === 'string'; - }, - func: function(item) { - return typeof item === 'function'; - }, - exists: function(name) { - return fs.existsSync(name); - }, - file: function(name) { - return is.exists(name) - ? fs.statSync(name).isFile() : false; - }, - sameFile: function(a, b) { - return path.resolve(a) == path.resolve(b); - }, - directory: function(name) { - return is.exists(name) - ? fs.statSync(name).isDirectory() : false; - }, - symbolicLink: function(name) { - return is.exists(name) - ? fs.lstatSync(name).isSymbolicLink() : false; - } -}; - -module.exports = is; diff --git a/packages/vue-native-template-compiler/build.js b/packages/vue-native-template-compiler/build.js index 166f762..1d832f5 100644 --- a/packages/vue-native-template-compiler/build.js +++ b/packages/vue-native-template-compiler/build.js @@ -1,86 +1,47 @@ -"use strict"; +'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); -function _interopDefault(ex) { - return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex; -} +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var deindent = _interopDefault(require("de-indent")); -var he = require("he"); -var changeCase = _interopDefault(require("change-case")); -var _ = require('lodash'); +var deindent = _interopDefault(require('de-indent')); +var he = require('he'); +var changeCase = _interopDefault(require('change-case')); /* */ -// these helpers produces better vm code in JS engines due to their -// explicitness and function inlining - -/** - * Check if value is primitive - */ - -/** - * Quick object check - this is primarily used to tell - * Objects from primitive values when we know the value - * is a JSON-compliant type. - */ - -/** - * Strict object type check. Only returns true - * for plain JavaScript objects. - */ - -/** - * Convert a value to a string that is actually rendered. - */ - -/** - * Convert a input value to a number for persistence. - * If the conversion fails, return original string. - */ - /** * Make a map and return a function for checking if a key * is in that map. */ -function makeMap(str, expectsLowerCase) { +function makeMap ( + str, + expectsLowerCase +) { var map = Object.create(null); - var list = str.split(","); + var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase - ? function (val) { - return map[val.toLowerCase()]; - } - : function (val) { - return map[val]; - }; + ? function (val) { return map[val.toLowerCase()]; } + : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ -var isBuiltInTag = makeMap("slot,component", true); - -/** - * Remove an item from an array - */ - -/** - * Check whether the object has the property. - */ +var isBuiltInTag = makeMap('slot,component', true); /** * Create a cached version of a pure function. */ -function cached(fn) { +function cached (fn) { var cache = Object.create(null); - return function cachedFn(str) { + return (function cachedFn (str) { var hit = cache[str]; - return hit || (cache[str] = fn(str)); - }; + return hit || (cache[str] = fn(str)) + }) } /** @@ -88,104 +49,59 @@ function cached(fn) { */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { - return str.replace(camelizeRE, function (_, c) { - return c ? c.toUpperCase() : ""; - }); + return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { - return str.charAt(0).toUpperCase() + str.slice(1); + return str.charAt(0).toUpperCase() + str.slice(1) }); -/** - * Hyphenate a camelCase string. - */ - -/** - * Simple bind, faster than native - */ - -/** - * Convert an Array-like object to a real Array. - */ - -/** - * Mix properties into target object. - */ - -/** - * Merge an Array of Objects into a single Object. - */ - /** * Perform no operation. */ -function noop() { } +function noop () {} /** * Always return false. */ -var no = function () { - return false; -}; +var no = function () { return false; }; /** * Return same value */ -var identity = function (_) { - return _; -}; - -/** - * Generate a static keys string from compiler modules. - */ - -/** - * Check if two values are loosely equal - that is, - * if they are plain objects, do they have the same shape? - */ - -/** - * Ensure a function is called only once. - */ +var identity = function (_) { return _; }; /* */ var isUnaryTag = makeMap( - "area,base,br,col,embed,frame,hr,img,input,isindex,keygen," + - "link,meta,param,source,track,wbr" + 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( - "colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source" + 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( - "address,article,aside,base,blockquote,body,caption,col,colgroup,dd," + - "details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form," + - "h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta," + - "optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead," + - "title,tr,track" + 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ -/*! - * HTML Parser By John Resig (ejohn.org) - * Modified by Juriy "kangax" Zaytsev - * Original code by Erik Arvidsson, Mozilla Public License - * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js - */ - +// Regular Expressions for parsing tags and attributes var singleAttrIdentifier = /([^\s"'<>/=]+)/; var singleAttrAssign = /(?:=)/; var singleAttrValues = [ @@ -197,83 +113,76 @@ var singleAttrValues = [ /([^\s"'=<>`]+)/.source ]; var attribute = new RegExp( - "^\\s*" + - singleAttrIdentifier.source + - "(?:\\s*(" + - singleAttrAssign.source + - ")" + - "\\s*(?:" + - singleAttrValues.join("|") + - "))?" + '^\\s*' + singleAttrIdentifier.source + + '(?:\\s*(' + singleAttrAssign.source + ')' + + '\\s*(?:' + singleAttrValues.join('|') + '))?' ); // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset -var ncname = "[a-zA-Z_][\\w\\-\\.]*"; -var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; -var startTagOpen = new RegExp("^<" + qnameCapture); +var ncname = '[a-zA-Z_][\\w\\-\\.]*'; +var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')'; +var startTagOpen = new RegExp('^<' + qnameCapture); var startTagClose = /^\s*(\/?)>/; -var endTag = new RegExp("^<\\/" + qnameCapture + "[^>]*>"); +var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>'); var doctype = /^]+>/i; var comment = /^"); + var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { advance(commentEnd + 3); - continue; + continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { - var conditionalEnd = html.indexOf("]>"); + var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); - continue; + continue } } @@ -281,7 +190,7 @@ function parseHTML(html, options) { var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); - continue; + continue } // End tag: @@ -290,20 +199,18 @@ function parseHTML(html, options) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); - continue; + continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); - continue; + continue } } - var text = void 0, - rest$1 = void 0, - next = void 0; + var text = (void 0), rest$1 = (void 0), next = (void 0); if (textEnd >= 0) { rest$1 = html.slice(textEnd); while ( @@ -313,10 +220,8 @@ function parseHTML(html, options) { !conditionalComment.test(rest$1) ) { // < in plain text, be forgiving and treat it as text - next = rest$1.indexOf("<", 1); - if (next < 0) { - break; - } + next = rest$1.indexOf('<', 1); + if (next < 0) { break } textEnd += next; rest$1 = html.slice(textEnd); } @@ -326,7 +231,7 @@ function parseHTML(html, options) { if (textEnd < 0) { text = html; - html = ""; + html = ''; } if (options.chars && text) { @@ -334,24 +239,19 @@ function parseHTML(html, options) { } } else { var stackedTag = lastTag.toLowerCase(); - var reStackedTag = - reCache[stackedTag] || - (reCache[stackedTag] = new RegExp( - "([\\s\\S]*?)(]*>)", - "i" - )); + var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(]*>)', 'i')); var endTagLength = 0; var rest = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; - if (!isPlainTextElement(stackedTag) && stackedTag !== "noscript") { + if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text - .replace(//g, "$1") - .replace(//g, "$1"); + .replace(//g, '$1') + .replace(//g, '$1'); } if (options.chars) { options.chars(text); } - return ""; + return '' }); index += html.length - rest.length; html = rest; @@ -360,26 +260,22 @@ function parseHTML(html, options) { if (html === last) { options.chars && options.chars(html); - if ( - process.env.NODE_ENV !== "production" && - !stack.length && - options.warn - ) { - options.warn('Mal-formatted tag at end of template: "' + html + '"'); + if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) { + options.warn(("Mal-formatted tag at end of template: \"" + html + "\"")); } - break; + break } } // Clean up any remaining tags parseEndTag(); - function advance(n) { + function advance (n) { index += n; html = html.substring(n); } - function parseStartTag() { + function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { @@ -389,10 +285,7 @@ function parseHTML(html, options) { }; advance(start[0].length); var end, attr; - while ( - !(end = html.match(startTagClose)) && - (attr = html.match(attribute)) - ) { + while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } @@ -400,28 +293,25 @@ function parseHTML(html, options) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; - return match; + return match } } } - function handleStartTag(match) { + function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { - if (lastTag === "p" && isNonPhrasingTag(tagName)) { + if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } - if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { + if (canBeLeftOpenTag(tagName) && lastTag === tagName) { parseEndTag(tagName); } } - var unary = - isUnaryTag$$1(tagName) || - (tagName === "html" && lastTag === "head") || - !!unarySlash; + var unary = isUnaryTag(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); @@ -429,39 +319,32 @@ function parseHTML(html, options) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { - if (args[3] === "") { - delete args[3]; - } - if (args[4] === "") { - delete args[4]; - } - if (args[5] === "") { - delete args[5]; - } + if (args[3] === '') { delete args[3]; } + if (args[4] === '') { delete args[4]; } + if (args[5] === '') { delete args[5]; } } - var value = args[3] || args[4] || args[5] || ""; + var value = args[3] || args[4] || args[5] || ''; var name = args[1]; /** * react-vue change *
* {name: "autorun", value: """"} => {name: "autorun", value: "true"} */ - if (args[1].indexOf("v-") === -1 && args[2] === undefined) { - value = "true"; - name = ":" + name; + if (args[1].indexOf('v-') === -1 && args[2] === undefined) { + value = 'true'; + name = ':' + name; } attrs[i] = { name: name, - value: decodeAttr(value, options.shouldDecodeNewlines) + value: decodeAttr( + value, + options.shouldDecodeNewlines + ) }; } if (!unary) { - stack.push({ - tag: tagName, - lowerCasedTag: tagName.toLowerCase(), - attrs: attrs - }); + stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs }); lastTag = tagName; } @@ -470,14 +353,10 @@ function parseHTML(html, options) { } } - function parseEndTag(tagName, start, end) { + function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; - if (start == null) { - start = index; - } - if (end == null) { - end = index; - } + if (start == null) { start = index; } + if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); @@ -487,7 +366,7 @@ function parseHTML(html, options) { if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { - break; + break } } } else { @@ -498,12 +377,12 @@ function parseHTML(html, options) { if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { - if ( - process.env.NODE_ENV !== "production" && - (i > pos || !tagName) && - options.warn - ) { - options.warn("tag <" + stack[i].tag + "> has no matching end tag."); + if (process.env.NODE_ENV !== 'production' && + (i > pos || !tagName) && + options.warn) { + options.warn( + ("tag <" + (stack[i].tag) + "> has no matching end tag.") + ); } if (options.end) { options.end(stack[i].tag, start, end); @@ -513,11 +392,11 @@ function parseHTML(html, options) { // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; - } else if (lowerCasedTagName === "br") { + } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } - } else if (lowerCasedTagName === "p") { + } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } @@ -532,13 +411,18 @@ function parseHTML(html, options) { var splitRE = /\r?\n/g; var replaceRE = /./g; -var isSpecialTag = makeMap("script,style,template", true); +var isSpecialTag = makeMap('script,style,template', true); + + /** * Parse a single-file component (*.vue) file into an SFC Descriptor Object. */ -function parseComponent(content, options) { - if (options === void 0) options = {}; +function parseComponent ( + content, + options + ) { + if ( options === void 0 ) options = {}; var sfc = { template: null, @@ -549,29 +433,34 @@ function parseComponent(content, options) { var depth = 0; var currentBlock = null; - function start(tag, attrs, unary, start, end) { + function start ( + tag, + attrs, + unary, + start, + end + ) { if (depth === 0) { currentBlock = { type: tag, - content: "", + content: '', start: end, attrs: attrs.reduce(function (cumulated, ref) { var name = ref.name; var value = ref.value; cumulated[name] = value || true; - return cumulated; + return cumulated }, Object.create(null)) }; if (isSpecialTag(tag)) { checkAttrs(currentBlock, attrs); - if (tag === "style") { + if (tag === 'style') { sfc.styles.push(currentBlock); } else { sfc[tag] = currentBlock; } - } else { - // custom blocks + } else { // custom blocks sfc.customBlocks.push(currentBlock); } } @@ -580,31 +469,31 @@ function parseComponent(content, options) { } } - function checkAttrs(block, attrs) { + function checkAttrs (block, attrs) { for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; - if (attr.name === "lang") { + if (attr.name === 'lang') { block.lang = attr.value; } - if (attr.name === "scoped") { + if (attr.name === 'scoped') { block.scoped = true; } - if (attr.name === "module") { + if (attr.name === 'module') { block.module = attr.value || true; } - if (attr.name === "src") { + if (attr.name === 'src') { block.src = attr.value; } } } - function end(tag, start, end) { + function end (tag, start, end) { if (depth === 1 && currentBlock) { currentBlock.end = start; var text = deindent(content.slice(currentBlock.start, currentBlock.end)); // pad content so that linters and pre-processors can output correct // line numbers in errors and warnings - if (currentBlock.type !== "template" && options.pad) { + if (currentBlock.type !== 'template' && options.pad) { text = padContent(currentBlock, options.pad) + text; } currentBlock.content = text; @@ -613,13 +502,15 @@ function parseComponent(content, options) { depth--; } - function padContent(block, pad) { - if (pad === "space") { - return content.slice(0, block.start).replace(replaceRE, " "); + function padContent (block, pad) { + if (pad === 'space') { + return content.slice(0, block.start).replace(replaceRE, ' ') } else { var offset = content.slice(0, block.start).split(splitRE).length; - var padChar = block.type === "script" && !block.lang ? "//\n" : "\n"; - return Array(offset).join(padChar); + var padChar = block.type === 'script' && !block.lang + ? '//\n' + : '\n'; + return Array(offset).join(padChar) } } @@ -628,14 +519,14 @@ function parseComponent(content, options) { end: end }); - return sfc; + return sfc } /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; -function parseFilters(exp) { +function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; @@ -650,28 +541,18 @@ function parseFilters(exp) { prev = c; c = exp.charCodeAt(i); if (inSingle) { - if (c === 0x27 && prev !== 0x5c) { - inSingle = false; - } + if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { - if (c === 0x22 && prev !== 0x5c) { - inDouble = false; - } + if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { - if (c === 0x60 && prev !== 0x5c) { - inTemplateString = false; - } + if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { - if (c === 0x2f && prev !== 0x5c) { - inRegex = false; - } + if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( - c === 0x7c && // pipe - exp.charCodeAt(i + 1) !== 0x7c && - exp.charCodeAt(i - 1) !== 0x7c && - !curly && - !square && - !paren + c === 0x7C && // pipe + exp.charCodeAt(i + 1) !== 0x7C && + exp.charCodeAt(i - 1) !== 0x7C && + !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression @@ -682,44 +563,23 @@ function parseFilters(exp) { } } else { switch (c) { - case 0x22: - inDouble = true; - break; // " - case 0x27: - inSingle = true; - break; // ' - case 0x60: - inTemplateString = true; - break; // ` - case 0x28: - paren++; - break; // ( - case 0x29: - paren--; - break; // ) - case 0x5b: - square++; - break; // [ - case 0x5d: - square--; - break; // ] - case 0x7b: - curly++; - break; // { - case 0x7d: - curly--; - break; // } + case 0x22: inDouble = true; break // " + case 0x27: inSingle = true; break // ' + case 0x60: inTemplateString = true; break // ` + case 0x28: paren++; break // ( + case 0x29: paren--; break // ) + case 0x5B: square++; break // [ + case 0x5D: square--; break // ] + case 0x7B: curly++; break // { + case 0x7D: curly--; break // } } - if (c === 0x2f) { - // / + if (c === 0x2f) { // / var j = i - 1; - var p = void 0; + var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); - if (p !== " ") { - break; - } + if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; @@ -734,7 +594,7 @@ function parseFilters(exp) { pushFilter(); } - function pushFilter() { + function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } @@ -745,18 +605,18 @@ function parseFilters(exp) { } } - return expression; + return expression } -function wrapFilter(exp, filter) { - var i = filter.indexOf("("); +function wrapFilter (exp, filter) { + var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter - return '_f("' + filter + '")(' + exp + ")"; + return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); - return '_f("' + name + '")(' + exp + "," + args; + return ("_f(\"" + name + "\")(" + exp + "," + args) } } @@ -766,18 +626,21 @@ var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { - var open = delimiters[0].replace(regexEscapeRE, "\\$&"); - var close = delimiters[1].replace(regexEscapeRE, "\\$&"); - return new RegExp(open + "((?:.|\\n)+?)" + close, "g"); + var open = delimiters[0].replace(regexEscapeRE, '\\$&'); + var close = delimiters[1].replace(regexEscapeRE, '\\$&'); + return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); -function parseText(text, delimiters) { +function parseText ( + text, + delimiters +) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { - return; + return } var tokens = []; - var lastIndex = (tagRE.lastIndex = 0); + var lastIndex = tagRE.lastIndex = 0; var match, index; while ((match = tagRE.exec(text))) { index = match.index; @@ -787,44 +650,32 @@ function parseText(text, delimiters) { } // tag token var exp = parseFilters(match[1].trim()); - tokens.push("_s(" + exp + ")"); + tokens.push(("_s(" + exp + ")")); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push(JSON.stringify(text.slice(lastIndex))); } - return tokens.join("+"); + return tokens.join('+') } /* */ -/** - * Cross-platform code generation for component v-model - */ - /** * Cross-platform codegen helper for generating v-model value assignment code. */ -function genAssignmentCode(value, assignment) { +function genAssignmentCode ( + value, + assignment +) { var modelRs = parseModel(value); if (modelRs.idx === null) { - return value + "=" + assignment; + return (value + "=" + assignment) } else { - return ( - "var $$exp = " + - modelRs.exp + - ", $$idx = " + - modelRs.idx + - ";" + + return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" + "if (!Array.isArray($$exp)){" + - value + - "=" + - assignment + - "}" + - "else{$$exp.splice($$idx, 1, " + - assignment + - ")}" - ); + value + "=" + assignment + "}" + + "else{$$exp.splice($$idx, 1, " + assignment + ")}" } } @@ -842,23 +693,18 @@ function genAssignmentCode(value, assignment) { * */ -var len; -var str; -var chr; -var index; -var expressionPos; -var expressionEndPos; +var len, str, chr, index, expressionPos, expressionEndPos; -function parseModel(val) { +function parseModel (val) { str = val; len = str.length; index = expressionPos = expressionEndPos = 0; - if (val.indexOf("[") < 0 || val.lastIndexOf("]") < len - 1) { + if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { return { exp: val, idx: null - }; + } } while (!eof()) { @@ -866,7 +712,7 @@ function parseModel(val) { /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); - } else if (chr === 0x5b) { + } else if (chr === 0x5B) { parseBracket(chr); } } @@ -874,69 +720,67 @@ function parseModel(val) { return { exp: val.substring(0, expressionPos), idx: val.substring(expressionPos + 1, expressionEndPos) - }; + } } -function next() { - return str.charCodeAt(++index); +function next () { + return str.charCodeAt(++index) } -function eof() { - return index >= len; +function eof () { + return index >= len } -function isStringStart(chr) { - return chr === 0x22 || chr === 0x27; +function isStringStart (chr) { + return chr === 0x22 || chr === 0x27 } -function parseBracket(chr) { +function parseBracket (chr) { var inBracket = 1; expressionPos = index; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); - continue; - } - if (chr === 0x5b) { - inBracket++; - } - if (chr === 0x5d) { - inBracket--; + continue } + if (chr === 0x5B) { inBracket++; } + if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index; - break; + break } } } -function parseString(chr) { +function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { - break; + break } } } var LIFECYCLE_HOOKS = [ - "beforeCreate", - "created", - "beforeMount", - "mounted", - "beforeUpdate", - "updated", - "beforeDestroy", - "destroyed", - "activated", - "deactivated" + 'beforeCreate', + 'created', + 'beforeMount', + 'mounted', + 'beforeUpdate', + 'updated', + 'beforeDestroy', + 'destroyed', + 'activated', + 'deactivated' ]; /* */ -var config = { + + +var config = ({ /** * Option merge strategies (used in core/util/options) */ @@ -950,12 +794,12 @@ var config = { /** * Show production mode tip message on boot? */ - productionTip: process.env.NODE_ENV !== "production", + productionTip: process.env.NODE_ENV !== 'production', /** * Whether to enable devtools */ - devtools: process.env.NODE_ENV !== "production", + devtools: process.env.NODE_ENV !== 'production', /** * Whether to record perf @@ -1015,51 +859,37 @@ var config = { * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS -}; +}); -var warn$1 = noop; -var tip = noop; +var warn = noop; var formatComponentName; -if (process.env.NODE_ENV !== "production") { - var hasConsole = typeof console !== "undefined"; +if (process.env.NODE_ENV !== 'production') { + var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; - var classify = function (str) { - return str - .replace(classifyRE, function (c) { - return c.toUpperCase(); - }) - .replace(/[-_]/g, ""); - }; - - warn$1 = function (msg, vm) { - if (hasConsole && !config.silent) { - console.error( - "[Vue warn]: " + msg + (vm ? generateComponentTrace(vm) : "") - ); - } - }; + var classify = function (str) { return str + .replace(classifyRE, function (c) { return c.toUpperCase(); }) + .replace(/[-_]/g, ''); }; - tip = function (msg, vm) { - if (hasConsole && !config.silent) { - console.warn( - "[Vue tip]: " + msg + (vm ? generateComponentTrace(vm) : "") - ); + warn = function (msg, vm) { + if (hasConsole && (!config.silent)) { + console.error("[Vue warn]: " + msg + ( + vm ? generateComponentTrace(vm) : '' + )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { - return ""; + return '' } - var name = - typeof vm === "string" - ? vm - : typeof vm === "function" && vm.options - ? vm.options.name - : vm._isVue - ? vm.$options.name || vm.$options._componentTag - : vm.name; + var name = typeof vm === 'string' + ? vm + : typeof vm === 'function' && vm.options + ? vm.options.name + : vm._isVue + ? vm.$options.name || vm.$options._componentTag + : vm.name; var file = vm._isVue && vm.$options.__file; if (!name && file) { @@ -1068,23 +898,19 @@ if (process.env.NODE_ENV !== "production") { } return ( - (name ? "<" + classify(name) + ">" : "") + - (file && includeFile !== false ? " at " + file : "") - ); + (name ? ("<" + (classify(name)) + ">") : "") + + (file && includeFile !== false ? (" at " + file) : '') + ) }; var repeat = function (str, n) { - var res = ""; + var res = ''; while (n) { - if (n % 2 === 1) { - res += str; - } - if (n > 1) { - str += str; - } + if (n % 2 === 1) { res += str; } + if (n > 1) { str += str; } n >>= 1; } - return res; + return res }; var generateComponentTrace = function (vm) { @@ -1097,7 +923,7 @@ if (process.env.NODE_ENV !== "production") { if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; - continue; + continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; @@ -1106,47 +932,32 @@ if (process.env.NODE_ENV !== "production") { tree.push(vm); vm = vm.$parent; } - return ( - "\n\nfound in\n\n" + - tree - .map(function (vm, i) { - return ( - "" + - (i === 0 ? "---> " : repeat(" ", 5 + i * 2)) + - (Array.isArray(vm) - ? formatComponentName(vm[0]) + - "... (" + - vm[1] + - " recursive calls)" - : formatComponentName(vm)) - ); - }) - .join("\n") - ); + return '\n\nfound in\n\n' + tree + .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) + ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") + : formatComponentName(vm))); }) + .join('\n') } else { - return "\n\n(found in " + formatComponentName(vm) + ")"; + return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } -function handleError(err, vm, info) { - if (config.errorHandler) { - config.errorHandler.call(null, err, vm, info); - } else { - if (process.env.NODE_ENV !== "production") { - warn$1("Error in " + info + ': "' + err.toString() + '"', vm); +function handleError (err, vm, info) { + { + if (process.env.NODE_ENV !== 'production') { + warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ - if (inBrowser && typeof console !== "undefined") { + if (inBrowser && typeof console !== 'undefined') { console.error(err); } else { - throw err; + throw err } } } /* */ -/* globals MutationObserver */ // Browser environment sniffing var inBrowser = typeof window !== "undefined"; @@ -1166,14 +977,18 @@ var supportsPassive = false; if (inBrowser) { try { var opts = {}; - Object.defineProperty(opts, "passive", { - get: function get() { - /* istanbul ignore next */ - supportsPassive = true; - } - }); // https://github.com/facebook/flow/issues/285 + Object.defineProperty( + opts, + "passive", + ({ + get: function get() { + /* istanbul ignore next */ + supportsPassive = true; + } + }) + ); // https://github.com/facebook/flow/issues/285 window.addEventListener("test-passive", null, opts); - } catch (e) { } + } catch (e) {} } // this needs to be lazy-evaled because vue may be required before @@ -1194,6 +1009,7 @@ var isServerRendering = function () { }; // detect devtools +var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative(Ctor) { @@ -1209,7 +1025,7 @@ var hasSymbol = /** * Defer a task to execute it asynchronously. */ -var nextTick = (function () { +var nextTick = (function() { var callbacks = []; var pending = false; var timerFunc; @@ -1242,9 +1058,7 @@ var nextTick = (function () { // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. - if (isIOS) { - setTimeout(noop); - } + if (isIOS) { setTimeout(noop); } }; } else if ( typeof MutationObserver !== "undefined" && @@ -1265,11 +1079,19 @@ var nextTick = (function () { textNode.data = String(counter); }; } else { - // fallback to setTimeout - /* istanbul ignore next */ - timerFunc = function () { - setTimeout(nextTickHandler, 0); - }; + if (Promise !== undefined) { + // If Promise is supported for android + timerFunc = function() { + var p = Promise.resolve(); + p.then(nextTickHandler).catch(logError); + }; + } else { + // fallback to setTimeout + /* istanbul ignore next */ + timerFunc = function() { + setTimeout(nextTickHandler, 0); + }; + } } return function queueNextTick(cb, ctx) { @@ -1296,96 +1118,75 @@ var nextTick = (function () { } }; })(); - -var _Set; /* istanbul ignore if */ -if (typeof Set !== "undefined" && isNative(Set)) { - // use native Set when available. - _Set = Set; -} else { - // a non-standard Set polyfill that only works with primitive keys. - _Set = (function () { - function Set() { - this.set = Object.create(null); - } - Set.prototype.has = function has(key) { - return this.set[key] === true; - }; - Set.prototype.add = function add(key) { - this.set[key] = true; - }; - Set.prototype.clear = function clear() { - this.set = Object.create(null); - }; - - return Set; - })(); -} +if (typeof Set !== "undefined" && isNative(Set)) ; /* */ -function baseWarn(msg) { - console.error("[Vue compiler]: " + msg); +function baseWarn (msg) { + console.error(("[Vue compiler]: " + msg)); } -function pluckModuleFunction(modules, key) { +function pluckModuleFunction ( + modules, + key +) { return modules - ? modules - .map(function (m) { - return m[key]; - }) - .filter(function (_) { - return _; - }) - : []; + ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) + : [] } -function addProp(el, name, value) { +function addProp (el, name, value) { (el.props || (el.props = [])).push({ name: name, value: value }); } -function addAttr(el, name, value) { +function addAttr (el, name, value) { (el.attrs || (el.attrs = [])).push({ name: name, value: value }); } -function addDirective(el, name, rawName, value, arg, modifiers) { - (el.directives || (el.directives = [])).push({ - name: name, - rawName: rawName, - value: value, - arg: arg, - modifiers: modifiers - }); +function addDirective ( + el, + name, + rawName, + value, + arg, + modifiers +) { + (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers }); } -function addHandler(el, name, value, modifiers, important, warn) { +function addHandler ( + el, + name, + value, + modifiers, + important, + warn +) { // warn prevent and passive modifier /* istanbul ignore if */ if ( - process.env.NODE_ENV !== "production" && - warn && - modifiers && - modifiers.prevent && - modifiers.passive + process.env.NODE_ENV !== 'production' && warn && + modifiers && modifiers.prevent && modifiers.passive ) { warn( - "passive and prevent can't be used together. " + - "Passive handler can't prevent default event." + 'passive and prevent can\'t be used together. ' + + 'Passive handler can\'t prevent default event.' ); } // check capture modifier if (modifiers && modifiers.capture) { delete modifiers.capture; - name = "!" + name; // mark the event as captured + name = '!' + name; // mark the event as captured } if (modifiers && modifiers.once) { delete modifiers.once; - name = "~" + name; // mark the event as once + name = '~' + name; // mark the event as once } /* istanbul ignore if */ if (modifiers && modifiers.passive) { delete modifiers.passive; - name = "&" + name; // mark the event as passive + name = '&' + name; // mark the event as passive } var events; if (modifiers && modifiers.native) { @@ -1406,31 +1207,36 @@ function addHandler(el, name, value, modifiers, important, warn) { } } -function getBindingAttr(el, name, getStatic) { +function getBindingAttr ( + el, + name, + getStatic +) { var dynamicValue = - getAndRemoveAttr(el, ":" + name) || getAndRemoveAttr(el, "v-bind:" + name); + getAndRemoveAttr(el, ':' + name) || + getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { - return parseFilters(dynamicValue); + return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { - return JSON.stringify(staticValue); + return JSON.stringify(staticValue) } } } -function getAndRemoveAttr(el, name) { +function getAndRemoveAttr (el, name) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); - break; + break } } } - return val; + return val } /* */ @@ -1443,11 +1249,12 @@ var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/; var argRE = /:(.*)$/; var bindRE = /^:|^v-bind:/; var modifierRE = /\.[^.]+/g; +var splitRE$1 = /\r?\n/g; var decodeHTMLCached = cached(he.decode); // configurable state -var warn; +var warn$1; var delimiters; var transforms; var preTransforms; @@ -1459,14 +1266,17 @@ var platformGetTagNamespace; /** * Convert HTML string to AST. */ -function parse(template, options) { - warn = options.warn || baseWarn; +function parse ( + template, + options +) { + warn$1 = options.warn || baseWarn; platformGetTagNamespace = options.getTagNamespace || no; platformMustUseProp = options.mustUseProp || no; platformIsPreTag = options.isPreTag || no; - preTransforms = pluckModuleFunction(options.modules, "preTransformNode"); - transforms = pluckModuleFunction(options.modules, "transformNode"); - postTransforms = pluckModuleFunction(options.modules, "postTransformNode"); + preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); + transforms = pluckModuleFunction(options.modules, 'transformNode'); + postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; @@ -1477,14 +1287,14 @@ function parse(template, options) { var inPre = false; var warned = false; - function warnOnce(msg) { + function warnOnce (msg) { if (!warned) { warned = true; - warn(msg); + warn$1(msg); } } - function endPre(element) { + function endPre (element) { // check pre state if (element.pre) { inVPre = false; @@ -1495,20 +1305,19 @@ function parse(template, options) { } parseHTML(template, { - warn: warn, + warn: warn$1, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, - start: function start(tag, attrs, unary) { + start: function start (tag, attrs, unary) { // check namespace. // inherit parent ns if there is one - var ns = - (currentParent && currentParent.ns) || platformGetTagNamespace(tag); + var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ - if (isIE && ns === "svg") { + if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } @@ -1526,15 +1335,11 @@ function parse(template, options) { if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; - process.env.NODE_ENV !== "production" && - warn( - "Templates should only be responsible for mapping the state to the " + - "UI. Avoid placing tags with side-effects in your templates, such as " + - "<" + - tag + - ">" + - ", as they will not be parsed." - ); + process.env.NODE_ENV !== 'production' && warn$1( + 'Templates should only be responsible for mapping the state to the ' + + 'UI. Avoid placing tags with side-effects in your templates, such as ' + + "<" + tag + ">" + ', as they will not be parsed.' + ); } // apply pre-transforms @@ -1572,20 +1377,18 @@ function parse(template, options) { processAttrs(element); } - function checkRootConstraints(el) { - if (process.env.NODE_ENV !== "production") { - if (el.tag === "slot" || el.tag === "template") { + function checkRootConstraints (el) { + if (process.env.NODE_ENV !== 'production') { + if (el.tag === 'slot' || el.tag === 'template') { warnOnce( - "Cannot use <" + - el.tag + - "> as component root element because it may " + - "contain multiple nodes." + "Cannot use <" + (el.tag) + "> as component root element because it may " + + 'contain multiple nodes.' ); } - if (el.attrsMap.hasOwnProperty("v-for")) { + if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( - "Cannot use v-for on stateful component root element because " + - "it renders multiple elements." + 'Cannot use v-for on stateful component root element because ' + + 'it renders multiple elements.' ); } } @@ -1603,7 +1406,7 @@ function parse(template, options) { exp: element.elseif, block: element }); - } else if (process.env.NODE_ENV !== "production") { + } else if (process.env.NODE_ENV !== 'production') { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + @@ -1614,13 +1417,10 @@ function parse(template, options) { if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); - } else if (element.slotScope) { - // scoped slot + } else if (element.slotScope) { // scoped slot currentParent.plain = false; - var name = element.slotTarget || '"default"'; - (currentParent.scopedSlots || (currentParent.scopedSlots = {}))[ - name - ] = element; + var name = element.slotTarget || '"default"' + ;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; @@ -1638,11 +1438,11 @@ function parse(template, options) { } }, - end: function end() { + end: function end () { // remove trailing whitespace var element = stack[stack.length - 1]; var lastNode = element.children[element.children.length - 1]; - if (lastNode && lastNode.type === 3 && lastNode.text === " " && !inPre) { + if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) { element.children.pop(); } // pop stack @@ -1651,55 +1451,42 @@ function parse(template, options) { endPre(element); }, - chars: function chars(text) { + chars: function chars (text) { if (!currentParent) { - if (process.env.NODE_ENV !== "production") { + if (process.env.NODE_ENV !== 'production') { if (text === template) { warnOnce( - "Component template requires a root element, rather than just text." + 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( - 'text "' + text + '" outside root element will be ignored.' + ("text \"" + text + "\" outside root element will be ignored.") ); } } - return; + return } // IE textarea placeholder bug /* istanbul ignore if */ - if ( - isIE && - currentParent.tag === "textarea" && - currentParent.attrsMap.placeholder === text - ) { - return; + if (isIE && + currentParent.tag === 'textarea' && + currentParent.attrsMap.placeholder === text) { + return } var children = currentParent.children; - text = - inPre || text.trim() - ? decodeHTMLCached(text) - : // only preserve whitespace if its not right after a starting tag - preserveWhitespace && children.length - ? " " - : ""; + text = inPre || text.trim() + ? decodeHTMLCached(text) + // only preserve whitespace if its not right after a starting tag + : preserveWhitespace && children.length ? ' ' : ''; if (text) { var expression; - if ( - !inVPre && - text !== " " && - (expression = parseText(text, delimiters)) - ) { + if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) { children.push({ type: 2, expression: expression, text: text }); - } else if ( - text !== " " || - !children.length || - children[children.length - 1].text !== " " - ) { + } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { children.push({ type: 3, text: text @@ -1708,19 +1495,19 @@ function parse(template, options) { } } }); - return root; + return root } -function processPre(el) { - if (getAndRemoveAttr(el, "v-pre") != null) { +function processPre (el) { + if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } -function processRawAttrs(el) { +function processRawAttrs (el) { var l = el.attrsList.length; if (l) { - var attrs = (el.attrs = new Array(l)); + var attrs = el.attrs = new Array(l); for (var i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, @@ -1733,34 +1520,33 @@ function processRawAttrs(el) { } } -function processKey(el) { - var exp = getBindingAttr(el, "key"); +function processKey (el) { + var exp = getBindingAttr(el, 'key'); if (exp) { - if (process.env.NODE_ENV !== "production" && el.tag === "template") { - warn( - "