Skip to content

Commit

Permalink
fix: close #63, close #63, add logger.js (#64)
Browse files Browse the repository at this point in the history
* fix: close #63, close #63, add logger.js

* chore: add editor config

* docs: fix issue number
  • Loading branch information
BuptStEve authored Nov 19, 2018
1 parent 23ba9ae commit a443af3
Show file tree
Hide file tree
Showing 15 changed files with 134 additions and 106 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
71 changes: 38 additions & 33 deletions packages/tua-mp/examples/basic/utils/tua-mp.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,30 @@ var __dep__ = '__dep__';
// 被框架占用的关键字,在 data 和 computed 中如果使用这些关键字,将会抛出错误
var reservedKeys = ['$data', '$emit', '$computed', __TUA_PATH__];

/**
* 统一的日志输出函数,在测试环境时不输出
* @param {String} type 输出类型 log|warn|error
* @param {any} out 具体的输出内容
*/
var logByType = function logByType(type) {
return function () {
var _console;

for (var _len = arguments.length, out = Array(_len), _key = 0; _key < _len; _key++) {
out[_key] = arguments[_key];
}

/* istanbul ignore next */
(_console = console)[type].apply(_console, ['[TUA-API]:'].concat(out));
};
};

var logger = {
log: logByType('log'),
warn: logByType('warn'),
error: logByType('error')
};

var isFn = function isFn(fn) {
return typeof fn === 'function';
};
Expand All @@ -142,6 +166,9 @@ var getPathByPrefix = function getPathByPrefix(prefix, key) {
return prefix === '' ? key : prefix + '.' + key;
};

var jsonParse = JSON.parse.bind(JSON);
var stringify = JSON.stringify.bind(JSON);

/**
* 将 source 上的属性代理到 target 上
* @param {Object} source 被代理对象
Expand Down Expand Up @@ -203,7 +230,7 @@ var setObjByPath = function setObjByPath(_ref) {
);
}, 'this');

error('Property "' + cur + '" is not found in "' + parentStr + '": ' + 'Make sure that this property has initialized in the data option.');
logger.error('Property "' + cur + '" is not found in "' + parentStr + '": ' + 'Make sure that this property has initialized in the data option.');
}

if (idx === arr.length - 1) {
Expand Down Expand Up @@ -258,28 +285,6 @@ var assertType = function assertType(value, type) {
return { valid: valid, expectedType: expectedType };
};

/**
* 统一的日志输出函数,在测试环境时不输出
* @param {String} type 输出类型 log|warn|error
* @param {any} out 输出的内容
*/
var logByType = function logByType(type) {
return function () {
var _console;

for (var _len = arguments.length, out = Array(_len), _key = 0; _key < _len; _key++) {
out[_key] = arguments[_key];
}

/* istanbul ignore next */
(_console = console)[type].apply(_console, ['[TUA-MP]:'].concat(out));
};
};

var log = logByType('log');
var warn = logByType('warn');
var error = logByType('error');

// reserved keys
var isReservedKeys = function isReservedKeys(str) {
return reservedKeys.indexOf(str) !== -1;
Expand Down Expand Up @@ -358,7 +363,7 @@ var assertProp = function assertProp(_ref) {
}

if (!valid) {
warn('Invalid prop: type check failed for prop "' + name + '".' + (' Expected ' + expectedTypes.join(', ')) + (', got ' + toRawType(value) + '.'));
logger.warn('Invalid prop: type check failed for prop "' + name + '".' + (' Expected ' + expectedTypes.join(', ')) + (', got ' + toRawType(value) + '.'));
}

return valid;
Expand All @@ -373,19 +378,15 @@ var assertProp = function assertProp(_ref) {
var getObserver = function getObserver(name) {
return function (prop) {
return function observer(value) {
var _this = this;

// 触发 setter
Promise.resolve().then(function () {
_this[name] = value;
});
this[name] = value;

var valid = assertProp({ prop: prop, name: name, value: value });
var validator = prop.validator;


if (validator && !validator(value)) {
warn('Invalid prop: custom validator check failed for prop "' + name + '".');
logger.warn('Invalid prop: custom validator check failed for prop "' + name + '".');
return false;
}

Expand Down Expand Up @@ -491,7 +492,7 @@ var hackSetData = function hackSetData(vm) {
});
};

var version = "0.8.1";
var version = "0.8.2";

/**
* 根据 vm 生成 key
Expand Down Expand Up @@ -620,6 +621,10 @@ var VmStatus = function () {
// 更新数据
vm.updated ? setData.call(vm, newState, vm.updated) : setData.call(vm, newState);

// 干掉原生 setData 触发的 setter,不然会死循环
delete _this.newStateByVM[vmKey];
delete _this.oldStateByVM[vmKey];

// 触发 watch
Object.keys(newState).map(function (key) {
var newVal = newState[key];
Expand Down Expand Up @@ -1051,7 +1056,7 @@ var bindComputed = function bindComputed(vm, computed, asyncSetData) {
},
set: function set$$1() {
if (typeof computed[key].set === 'undefined') {
warn('Computed property "' + key + '" was assigned to but it has no setter.');
logger.warn('Computed property "' + key + '" was assigned to but it has no setter.');
} else {
var setVal = computed[key].set.bind(vm);
setVal.apply(undefined, arguments);
Expand Down Expand Up @@ -1264,6 +1269,6 @@ var TuaPage = function TuaPage(_ref) {
}));
};

log('Version ' + version);
logger.log('Version ' + version);

export { TuaComp, TuaPage };
2 changes: 1 addition & 1 deletion packages/tua-mp/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tua-mp",
"version": "0.8.1",
"version": "0.8.2",
"description": "A progressive miniprogram framework for coding like Vue",
"main": "examples/basic/utils/tua-mp.js",
"files": [
Expand Down
7 changes: 7 additions & 0 deletions packages/tua-mp/src/TuaComp.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ export const TuaComp = ({
created (...options) {
rest.beforeCreate && rest.beforeCreate.apply(this, options)
rest.created && rest.created.apply(this, options)

if (process.env.NODE_ENV === 'test') {
this.$props = {
...properties,
...getPropertiesFromProps(props),
}
}
},
attached (...options) {
rest.beforeMount && rest.beforeMount.apply(this, options)
Expand Down
4 changes: 4 additions & 0 deletions packages/tua-mp/src/VmStatus.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ export default class VmStatus {
? setData.call(vm, newState, vm.updated)
: setData.call(vm, newState)

// 干掉原生 setData 触发的 setter,不然会死循环
delete this.newStateByVM[vmKey]
delete this.oldStateByVM[vmKey]

// 触发 watch
Object.keys(newState)
.map((key) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/tua-mp/src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { log } from './utils/index'
import { logger } from './utils/index'
import { version } from '../package.json'

log(`Version ${version}`)
logger.log(`Version ${version}`)

export * from './TuaComp'
export * from './TuaPage'
8 changes: 3 additions & 5 deletions packages/tua-mp/src/init.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import {
isFn,
warn,
logger,
proxyData,
getValByPath,
} from './utils/index'
import {
COMMON_PROP,
} from './constants'
import Dep from './observer/dep'
import { COMMON_PROP } from './constants'

/**
* 遍历观察 vm.data 中的所有属性,并将其直接挂到 vm 上
Expand Down Expand Up @@ -82,7 +80,7 @@ export const bindComputed = (vm, computed, asyncSetData) => {
},
set (...options) {
if (typeof computed[key].set === 'undefined') {
warn(`Computed property "${key}" was assigned to but it has no setter.`)
logger.warn(`Computed property "${key}" was assigned to but it has no setter.`)
} else {
const setVal = computed[key].set.bind(vm)
setVal(...options)
Expand Down
28 changes: 8 additions & 20 deletions packages/tua-mp/src/utils/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
reservedKeys,
__TUA_PATH__,
} from '../constants'
import { logger } from './logger'

export const isFn = fn => typeof fn === 'function'

Expand All @@ -19,8 +20,12 @@ export const isPlainObject = value =>
_toString.call(value) === '[object Object]'

// 根据路径前缀和 key 得到当前路径
export const getPathByPrefix = (prefix, key) =>
prefix === '' ? key : `${prefix}.${key}`
export const getPathByPrefix = (prefix, key) => prefix === ''
? key
: `${prefix}.${key}`

export const jsonParse = JSON.parse.bind(JSON)
export const stringify = JSON.stringify.bind(JSON)

/**
* 将 source 上的属性代理到 target 上
Expand Down Expand Up @@ -79,7 +84,7 @@ export const setObjByPath = ({ obj, path, val, isCheckDef = false }) => pathStr2
'this'
)

error(
logger.error(
`Property "${cur}" is not found in "${parentStr}": ` +
`Make sure that this property has initialized in the data option.`
)
Expand Down Expand Up @@ -138,23 +143,6 @@ export const assertType = (value, type) => {
return { valid, expectedType }
}

/**
* 统一的日志输出函数,在测试环境时不输出
* @param {String} type 输出类型 log|warn|error
* @param {any} out 输出的内容
*/
const logByType = (type) => (...out) => {
/* istanbul ignore else */
if (process.env.NODE_ENV === 'test') return

/* istanbul ignore next */
console[type](`[TUA-MP]:`, ...out)
}

export const log = logByType('log')
export const warn = logByType('warn')
export const error = logByType('error')

// reserved keys
const isReservedKeys = str => reservedKeys.indexOf(str) !== -1
const getObjHasReservedKeys = obj => Object.keys(obj).filter(isReservedKeys)
Expand Down
1 change: 1 addition & 0 deletions packages/tua-mp/src/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './comp'
export * from './basic'
export * from './props'
export * from './logger'
export * from './hackSetData'
18 changes: 18 additions & 0 deletions packages/tua-mp/src/utils/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* 统一的日志输出函数,在测试环境时不输出
* @param {String} type 输出类型 log|warn|error
* @param {any} out 具体的输出内容
*/
const logByType = (type) => (...out) => {
/* istanbul ignore else */
if (process.env.NODE_ENV === 'test') return

/* istanbul ignore next */
console[type](`[TUA-API]:`, ...out)
}

export const logger = {
log: logByType('log'),
warn: logByType('warn'),
error: logByType('error'),
}
10 changes: 4 additions & 6 deletions packages/tua-mp/src/utils/props.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
isFn,
warn,
toRawType,
assertType,
} from './basic'
import { logger } from './logger'
import { TYPES } from '../constants'

/**
Expand Down Expand Up @@ -39,7 +39,7 @@ export const assertProp = ({ prop, name, value }) => {
}

if (!valid) {
warn(
logger.warn(
`Invalid prop: type check failed for prop "${name}".` +
` Expected ${expectedTypes.join(', ')}` +
`, got ${toRawType(value)}.`
Expand All @@ -58,15 +58,13 @@ export const assertProp = ({ prop, name, value }) => {
export const getObserver = (name) => (prop) => {
return function observer (value) {
// 触发 setter
Promise.resolve().then(() => {
this[name] = value
})
this[name] = value

const valid = assertProp({ prop, name, value })
const { validator } = prop

if (validator && !validator(value)) {
warn(`Invalid prop: custom validator check failed for prop "${name}".`)
logger.warn(`Invalid prop: custom validator check failed for prop "${name}".`)
return false
}

Expand Down
Loading

0 comments on commit a443af3

Please sign in to comment.