Commit 185d9d4f authored by rockyl's avatar rockyl

Merge branch 'auto_align_qx' into designtime

# Conflicts:
#	debug/engine.js
#	debug/engine.js.map
#	manifest.json
#	src/2d/display/Container.ts
#	src/2d/display/Sprite.ts
#	src/2d/display/Stage.ts
#	src/2d/text/TextField.ts
#	src/zeroing/game-warpper/GameStage.ts
#	src/zeroing/game-warpper/StackContainer.ts
#	src/zeroing/game-warpper/assets-manager.ts
#	src/zeroing/launcher.ts
#	src/zeroing/utils/utils.ts
parents 551e93a9 dc88a857
File added
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="TsLint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="FLOW" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/zeroing-engine.iml" filepath="$PROJECT_DIR$/.idea/zeroing-engine.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<changelist name="Uncommitted_changes_before_Checkout_at_2020_5_15,_2_12_下午_[Default_Changelist]" date="1589523138013" recycled="false" toDelete="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Checkout_at_2020_5_15,_2_12_下午_[Default_Changelist]/shelved.patch" />
<option name="DESCRIPTION" value="Uncommitted changes before Checkout at 2020/5/15, 2:12 下午 [Default Changelist]" />
</changelist>
\ No newline at end of file
<changelist name="Uncommitted_changes_before_Update_at_2020_5_14,_2_47_下午_[Default_Changelist]" date="1589438835098" recycled="false" toDelete="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Update_at_2020_5_14,_2_47_下午_[Default_Changelist]/shelved.patch" />
<option name="DESCRIPTION" value="Uncommitted changes before Update at 2020/5/14, 2:47 下午 [Default Changelist]" />
</changelist>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
{"id":"engine","url":"engine.a0a1c11664d9ed4ac76999a01ceb9a729e1b27c1.js"} {"id":"engine","url":"engine.dee8bb73f7c234c7fe2527549add0fab7ca3d3fc.js"}
\ No newline at end of file \ No newline at end of file
...@@ -12,7 +12,7 @@ const fs = require('fs'); ...@@ -12,7 +12,7 @@ const fs = require('fs');
const tslibWrapper = 'var tslib = {__extends: __extends,__assign: __assign,__rest: __rest,__decorate: __decorate,__param: __param,__metadata: __metadata,__awaiter: __awaiter,__generator: __generator,__exportStar: __exportStar,__values: __values,__read: __read,__spread: __spread,__spreadArrays: __spreadArrays,__await: __await,__asyncGenerator: __asyncGenerator,__asyncDelegator: __asyncDelegator,__asyncValues: __asyncValues,__makeTemplateObject: __makeTemplateObject,__importStar: __importStar,__importDefault: __importDefault};' const tslibWrapper = 'var tslib = {__extends: __extends,__assign: __assign,__rest: __rest,__decorate: __decorate,__param: __param,__metadata: __metadata,__awaiter: __awaiter,__generator: __generator,__exportStar: __exportStar,__values: __values,__read: __read,__spread: __spread,__spreadArrays: __spreadArrays,__await: __await,__asyncGenerator: __asyncGenerator,__asyncDelegator: __asyncDelegator,__asyncValues: __asyncValues,__makeTemplateObject: __makeTemplateObject,__importStar: __importStar,__importDefault: __importDefault};'
const tslibCode = fs.readFileSync(__dirname + '/scripts/tslib.min.js'); const tslibCode = fs.readFileSync(__dirname + '/scripts/tslib.min.js');
const options = { export default {
input: 'src/index.ts', input: 'src/index.ts',
output: [ output: [
{ {
...@@ -23,21 +23,16 @@ const options = { ...@@ -23,21 +23,16 @@ const options = {
tslib: 'tslib' tslib: 'tslib'
}, },
banner: tslibCode + '\n' + tslibWrapper, banner: tslibCode + '\n' + tslibWrapper,
} },
], ],
plugins: [ plugins: [
progress(), // progress(),
resolve({}), resolve({}),
typescript({ typescript({
//useTsconfigDeclarationDir: true, // useTsconfigDeclarationDir: true,
}), }),
commonjs(), commonjs(),
process.env.BUILD === 'production' && uglify({})
], ],
external: ['tslib'], external: ['tslib'],
}; };
if(process.env.BUILD === 'production'){
options.plugins.push(uglify({}));
}
export default options;
...@@ -518,7 +518,10 @@ export default class Container extends DisplayObject { ...@@ -518,7 +518,10 @@ export default class Container extends DisplayObject {
matrix.transformPoint(rect.x + rect.width, rect.y + rect.height, DisplayObject._p3); matrix.transformPoint(rect.x + rect.width, rect.y + rect.height, DisplayObject._p3);
matrix.transformPoint(rect.x, rect.y + rect.height, DisplayObject._p4); matrix.transformPoint(rect.x, rect.y + rect.height, DisplayObject._p4);
Rectangle.createFromPoints(this._bounds, DisplayObject._p1, DisplayObject._p2, DisplayObject._p3, DisplayObject._p4); Rectangle.createFromPoints(this._bounds, DisplayObject._p1, DisplayObject._p2, DisplayObject._p3, DisplayObject._p4);
return true;
} }
return false;
} }
/** /**
...@@ -529,7 +532,7 @@ export default class Container extends DisplayObject { ...@@ -529,7 +532,7 @@ export default class Container extends DisplayObject {
//如果不可见 //如果不可见
if (!this.visible) return null if (!this.visible) return null
//如果禁止子级的鼠标事件 //如果禁止子级的鼠标事件
if (isMouseEvent && !this.mouseChildren) { if (isMouseEvent && !this.mouseChildren){
return this.hitTestSelf(globalPoint); return this.hitTestSelf(globalPoint);
} }
var children = this.children; var children = this.children;
...@@ -748,6 +751,13 @@ export default class Container extends DisplayObject { ...@@ -748,6 +751,13 @@ export default class Container extends DisplayObject {
//if (this.stage) this.stage.layoutInvalid = true; //if (this.stage) this.stage.layoutInvalid = true;
} }
this.dispatchEvent(Event.RESIZE); this.dispatchEvent(Event.RESIZE);
this.dispatchEvent(Event.MAYBE_ALIGN);
// 如果它设置了 percentWidth 或同时设置了 left 和 right 则表示他的宽度是相对的,则对于父级来说它的宽度永远是 0
this.__width = (toBoolean(this.percentWidth) || (toBoolean(this.left) && toBoolean(this.right)))
? 0
: value;
} }
} }
...@@ -777,7 +787,38 @@ export default class Container extends DisplayObject { ...@@ -777,7 +787,38 @@ export default class Container extends DisplayObject {
//if (this.stage) this.stage.layoutInvalid = true; //if (this.stage) this.stage.layoutInvalid = true;
} }
this.dispatchEvent(Event.RESIZE); this.dispatchEvent(Event.RESIZE);
this.dispatchEvent(Event.MAYBE_ALIGN);
// 如果它设置了 percentHeight 或同时设置了 top 和 bottom 则表示他的高度是相对的,则对于父级来说它的高度永远是 0
this.__height = (toBoolean(this.percentHeight) || (toBoolean(this.top) && toBoolean(this.bottom)))
? 0
: value;
}
} }
protected __width = 0; // 忽略 相对宽度 的 宽度,在父级计算自动宽度的时候用到
protected __height = 0; // 忽略 相对高度 的 高度,在父级计算自动高度的时候用到
get x(): number {
return this.position.x;
}
set x(value: number) {
if (value == this.transform.position.x) return;
this.transform.position.x = value;
this.dispatchEvent(Event.MAYBE_ALIGN);
}
get y(): number {
return this.position.y;
}
set y(value: number) {
if (value == this.transform.position.y) return;
this.transform.position.y = value;
this.dispatchEvent(Event.MAYBE_ALIGN);
} }
clone(withEvents = false, withScripts = false) { clone(withEvents = false, withScripts = false) {
......
...@@ -401,11 +401,19 @@ export default class Sprite extends Container { ...@@ -401,11 +401,19 @@ export default class Sprite extends Container {
this.scale.x = 1; this.scale.x = 1;
this._width = undefined; this._width = undefined;
} else { } else {
value = abs(value);
const s = sign(this.scale.y) || 1; const s = sign(this.scale.y) || 1;
this.scale.x = s * value / this._texture.orig.width; this.scale.x = s * value / this._texture.orig.width;
this._width = value; this._width = value;
} }
this.dispatchEvent(Event.RESIZE); this.dispatchEvent(Event.RESIZE);
this.dispatchEvent(Event.MAYBE_ALIGN);
if (isNaN(this.percentWidth) || this.percentWidth === null) {
this.__width = value;
} else {
this.__width = 0;
}
} }
} }
...@@ -424,11 +432,19 @@ export default class Sprite extends Container { ...@@ -424,11 +432,19 @@ export default class Sprite extends Container {
this.scale.y = 1; this.scale.y = 1;
this._height = undefined; this._height = undefined;
} else { } else {
value = abs(value);
const s = sign(this.scale.y) || 1; const s = sign(this.scale.y) || 1;
this.scale.y = s * value / this._texture.orig.height; this.scale.y = s * value / this._texture.orig.height;
this._height = value; this._height = value;
} }
this.dispatchEvent(Event.RESIZE); this.dispatchEvent(Event.RESIZE);
this.dispatchEvent(Event.MAYBE_ALIGN);
if (isNaN(this.percentHeight) || this.percentHeight === null) {
this.__height = value;
} else {
this.__height = 0;
}
} }
} }
......
...@@ -349,7 +349,6 @@ export class Stage extends Container { ...@@ -349,7 +349,6 @@ export class Stage extends Container {
* @param {number} renderType 渲染类型2canvas * @param {number} renderType 渲染类型2canvas
* @param {boolean} transparent 透明否,默认透明true,此时bgColor无效 * @param {boolean} transparent 透明否,默认透明true,此时bgColor无效
* @param {number} bgColor 背景颜色十六进制 * @param {number} bgColor 背景颜色十六进制
* @param autoResize 是否自动重置尺寸
* @public * @public
* @since 1.0.0 * @since 1.0.0
*/ */
...@@ -361,8 +360,7 @@ export class Stage extends Container { ...@@ -361,8 +360,7 @@ export class Stage extends Container {
scaleMode: string = StageScaleMode.FIXED_WIDTH, scaleMode: string = StageScaleMode.FIXED_WIDTH,
renderType: RENDERER_TYPE = RENDERER_TYPE.WEBGL, renderType: RENDERER_TYPE = RENDERER_TYPE.WEBGL,
transparent: boolean = true, transparent: boolean = true,
bgColor: number = 0x000000, bgColor: number = 0x000000
autoResize: boolean = false,
) { ) {
super(); super();
let s: Stage = this; let s: Stage = this;
...@@ -378,7 +376,6 @@ export class Stage extends Container { ...@@ -378,7 +376,6 @@ export class Stage extends Container {
s.rootDiv = div; s.rootDiv = div;
s.setFrameRate(frameRate); s.setFrameRate(frameRate);
s._scaleMode = scaleMode; s._scaleMode = scaleMode;
s.autoResize = autoResize;
//s.anchorX = desW >> 1; //s.anchorX = desW >> 1;
//s.anchorY = desH >> 1; //s.anchorY = desH >> 1;
...@@ -559,7 +556,9 @@ export class Stage extends Container { ...@@ -559,7 +556,9 @@ export class Stage extends Container {
* @return {{w: number, h: number}} * @return {{w: number, h: number}}
*/ */
public getRootDivWH(div: HTMLDivElement) { public getRootDivWH(div: HTMLDivElement) {
/*let iw = document.body.clientWidth; /*let sw = div.style.width;
let sh = div.style.height;
let iw = document.body.clientWidth;
// let ih = document.body.clientHeight-40; // let ih = document.body.clientHeight-40;
let ih = document.body.clientHeight; let ih = document.body.clientHeight;
let vW = parseInt(sw); let vW = parseInt(sw);
......
...@@ -9,8 +9,9 @@ import {HashObject} from "../HashObject"; ...@@ -9,8 +9,9 @@ import {HashObject} from "../HashObject";
*/ */
export class Event extends HashObject { export class Event extends HashObject {
// public static IMAGE_LOADED: string = "onImageLoaded" public static MAYBE_ALIGN: string = "maybeAlign";
// public static IMAGE_LOADED: string = "onImageLoaded"
/** /**
* 舞台尺寸发生变化时触发 * 舞台尺寸发生变化时触发
* @Event * @Event
......
...@@ -1344,6 +1344,8 @@ export default class Graphics extends Container { ...@@ -1344,6 +1344,8 @@ export default class Graphics extends Container {
} else { } else {
this._texture.baseTexture.update(); this._texture.baseTexture.update();
} }
//@ts-ignore
this._texture.onBaseTextureUpdated({target:this._texture.baseTexture})
//可能需要更改_texture,this._texture.baseTexture尺寸 //可能需要更改_texture,this._texture.baseTexture尺寸
this.offsetX = bounds.x; this.offsetX = bounds.x;
......
import {SCALE_MODES, TEXT_ALIGN, TEXT_lINETYPE, VERTICAL_ALIGN} from "../const"; import {SCALE_MODES, TEXT_ALIGN, TEXT_lINETYPE, VERTICAL_ALIGN} from "../const";
import Texture from "../texture/Texture"; import Texture from "../texture/Texture";
import {getRGBA, hex2string} from "../utils/index"; import {getRGBA, hex2string} from "../utils/index";
import {Rectangle} from "../math/index"; import {ObservablePoint, Rectangle} from "../math/index";
import Sprite from "../display/Sprite"; import Sprite from "../display/Sprite";
import {Event} from "../events/index"; import {Event} from "../events/index";
//文本canvas上xy的偏移量 //文本canvas上xy的偏移量
const padding = 10; const padding = 50;
const styleFields = { const styleFields = {
color: 'fillStyle', color: 'fillStyle',
...@@ -602,7 +602,7 @@ export class TextField extends Sprite { ...@@ -602,7 +602,7 @@ export class TextField extends Sprite {
if (!text) { if (!text) {
s.canvas.width = 0; s.canvas.width = 0;
s.canvas.height = 0; s.canvas.height = 0;
if (!this._width && !this._height) { if(!this._width && !this._height){
s._localBoundsSelf.clear(); s._localBoundsSelf.clear();
} }
this.anchorTexture = {x: 0, y: 0}; this.anchorTexture = {x: 0, y: 0};
...@@ -625,7 +625,7 @@ export class TextField extends Sprite { ...@@ -625,7 +625,7 @@ export class TextField extends Sprite {
s.realLines = realLines; s.realLines = realLines;
s._prepContext(ctx); s._prepContext(ctx);
let textWidth = !s._width && s._width != 0 ? 0 : s._width; let textWidth = s._width;
// let lineH = s._lineSpacing + s.size; // let lineH = s._lineSpacing + s.size;
//单行文本时 //单行文本时
if (isPureText && text.indexOf("\n") < 0 && s.lineType == TEXT_lINETYPE.SINGLE) { if (isPureText && text.indexOf("\n") < 0 && s.lineType == TEXT_lINETYPE.SINGLE) {
......
import { ALIGN_MODE, AUTO_SIZE_MODE } from "./auto-adjust";
import { toBoolean } from "../utils/utils";
import { Container } from "../../2d/display/index";
/**
* 自适应管理器
* @constructor
*/
class AlignManager {
// 这个列表里的对象会在渲染前被自动调整
private alignList = [];
constructor() {
}
/**
* flash (渲染前)
*/
public flush() {
const list = this.alignList;
list.forEach((v: Container) => {
this.autoSize(v); // 去调整大小
this.align(v); // 去自动对齐
});
// 要在这里单独检查,因为对齐一次后可能遇到其父节点需要对齐导致其再对齐一次
list.forEach((v) => {
if (v.alignMode === ALIGN_MODE.ONCE) { // 如果是单次对齐则一次运算之后就关闭它
v.alignEnabled = false;
}
});
// 干掉列表
list.length = 0;
}
/**
* align
* @param that
*/
private align(that) {
if (!that.alignEnabled) return; // 如果的自动对齐关闭里则啥也不干
// if(that.alignMode === ALIGN_MODE.ONCE) { // 如果是单次对齐则一次运算之后就关闭它
// that.alignEnabled = false;
// }
const {
percentWidth, percentHeight,
top, bottom, left, right,
percentTop, percentBottom, percentLeft, percentRight,
horizonCenter, verticalCenter
} = that;
let {_width: tW_Z = 0, _height: tH_Z = 0} = that;
const {_width: pW_Z = 0, _height: pH_Z = 0} = (that.parent || {});
/// TODO null / 100 == 0 ?????? wtf!!!! 我裂开了
// percentWidth /= 100;
// percentHeight /= 100;
// percentTop /= 100;
// percentBottom /= 100;
// percentLeft /= 100;
// percentRight /= 100;
const judgePL = toBoolean(percentLeft)
, judgePR = toBoolean(percentRight)
, judgePT = toBoolean(percentTop)
, judgePB = toBoolean(percentBottom);
// 先转化一下
const _left = judgePL ? percentLeft / 100 * pW_Z : left
, _right = judgePR ? percentRight / 100 * pW_Z : right
, _top = judgePT ? percentTop / 100 * pH_Z : top
, _bottom = judgePB ? percentBottom / 100 * pH_Z : bottom;
/**
* 计算 width 和 x 值
*/
if (toBoolean(_left) && toBoolean(_right)) { // _left _right 都有则直接拉伸或缩小
that.x = _left;
that.width = pW_Z - _left - _right;
} else {
// 先设置下自己的 width
toBoolean(percentWidth) && (tW_Z = that.width = pW_Z * percentWidth / 100);
// 先考虑 horizonCenter 属性
if (toBoolean(horizonCenter)) {
// x 值 = 父节点的中间值 - 自己宽度的一半 - 居中差值
that.x = pW_Z / 2 - tW_Z / 2 + horizonCenter;
} else if (toBoolean(_left)) { // 假如有 _left
that.x = _left;
} else if (toBoolean(_right)) { // 假如有 _right
that.x = pW_Z - _right - tW_Z;
}
}
/**
* 计算 height 和 y 值
*/
if (toBoolean(_top) && toBoolean(_bottom)) { // _top _bottom 都有则直接拉伸或缩小
that.y = _top;
that.height = pH_Z - _top - _bottom;
} else {
// 先设置下自己的 height
toBoolean(percentHeight) && (tH_Z = that.height = pH_Z * percentHeight / 100);
// 先考虑 horizonCenter 属性
if (toBoolean(verticalCenter)) {
// x 值 = 父节点的中间值 - 自己高度的一半 - 居中差值
that.y = pH_Z / 2 - tH_Z / 2 + verticalCenter;
} else if (toBoolean(_top)) { // 假如有 _top
that.y = _top;
} else if (toBoolean(_bottom)) { // 假如有 _bottom
that.y = pH_Z - _bottom - tH_Z;
}
}
that.children.forEach(v => this.align(v));
}
/**
* 自动大小
* @param that
*/
private autoSize(that) {
const len = that.children.length
if (len > 0) {
// 检测本身的是否是可以自动宽
// if (that.autoWidth
if (that.autoSizeMode === AUTO_SIZE_MODE.ALL
|| that.autoSizeMode === AUTO_SIZE_MODE.WIDTH
// && !toBoolean(that.right) /// TODO 我把它注释了 注释这行可以让容器设置了 right 后反向撑开,保持 right 边距不变
&& !toBoolean(that.percentWidth)) {
/// TODO 下面这段注释的代码可以实现让其左边撑开,不过还有未知bug
// 找出子节点最小x
// let minX = 0;
// for(let i = 0; i < len; i++) {
// if(that.children[i].x < minX) {
// minX = that.children[i].x;
// }
// }
// if(minX < 0) {
// that.children.forEach(v => v.x -= minX);
// that.x += minX;
// that.width -= minX;
// }
// 找出最右值
let maxR = 0;
for (let i = 0; i < len; i++) {
if (toBoolean(that.children[i].right)) continue; /// TODO 开启这个,忽略带 right 值的子节点
let _x = that.children[i].x || 0;
let _w = that.children[i].__width || 0;
(_x + _w > maxR) ? maxR = _x + _w : 0;
}
that.width = maxR;
}
// 检测本身的是否是可以自动高
if (that.autoSizeMode === AUTO_SIZE_MODE.ALL
|| that.autoSizeMode === AUTO_SIZE_MODE.HEIGHT
// && !toBoolean(that.bottom) /// TODO 我把它注释了 注释这行可以让容器设置了 bottom 后反向撑开,保持 bottom 边距不变
&& !toBoolean(that.percentHeight)) {
/// TODO 下面这段注释的代码可以实现让其上边撑开,不过还有未知bug
// 找出子节点最小y
// let minY = 0;
// for(let i = 1; i < len; i++) {
// if(that.children[i].y < minY) {
// minY = that.children[i].y;
// }
// }
// if(minY < 0) {
// that.children.forEach(v => v.y -= minY);
// that.y += minY;
// that.height -= minY;
// }
// 找出最下值
let maxB = 0;
for (let i = 0; i < len; i++) {
if (toBoolean(that.children[i].bottom)) continue; /// TODO 开启这个,忽略带 bottom 值的子节点
let _y = that.children[i].y || 0;
let _h = that.children[i].__height || 0;
(_y + _h > maxB) ? maxB = _y + _h : 0;
}
that.height = maxB;
}
}
}
/**
* 添加一个变脏的对象
* @param obj
*/
public addAlign(obj) {
const list = this.alignList;
if (list.indexOf(obj) < 0) {
list.push(obj);
}
}
}
function tt(...v) {
for (let i = 0; i < v.length; i++) {
if (!toBoolean(v[i])) return false;
}
return true;
}
export let alignMgr = new AlignManager();
This diff is collapsed.
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
*/ */
import {Event, EventDispatcher, MouseEvent} from "../../2d/events"; import {Event, EventDispatcher, MouseEvent} from "../../2d/events/index";
import {HashObject} from "../../2d/HashObject"; import {HashObject} from "../../2d/HashObject";
import {executeBehavior} from "../behavior-runtime"; import {executeBehavior} from "../behavior-runtime";
import {injectProp} from "../utils"; import {injectProp} from "../utils";
......
...@@ -2,21 +2,24 @@ ...@@ -2,21 +2,24 @@
* Created by rockyl on 2019-11-05. * Created by rockyl on 2019-11-05.
*/ */
import {Stage} from "../../2d/display/index"; import { Stage } from "../../2d/display/index";
import {StackContainer} from "./StackContainer"; import { StackContainer } from "./StackContainer";
import {loadAssets} from "./assets-manager"; import { checkAssetGroupLoaded, loadAssetsGroup, loadAssets, loadAssetsGroups } from "./assets-manager";
import {instantiate} from "./view-interpreter"; import { instantiate } from "./view-interpreter";
import {dataCenter, DataCenter} from "./data-center"; import { dataCenter, DataCenter } from "./data-center";
import {setProcessMetaLibs} from "../behavior-runtime/index"; import { setProcessMetaLibs } from "../behavior-runtime/index";
import {Tween} from "../../2d/tween/index"; import { Tween } from "../../2d/tween/index";
import {Rect} from "./nodes/index"; import { Rect } from "./nodes/index";
import {injectEnv} from "./enviroment"; import { injectEnv } from "./enviroment";
import {Toast} from "./Toast"; import { Toast } from "./Toast";
import {arrayFind} from "../utils/index"; import { arrayFind } from "../utils/index";
import {Node} from "./nodes/Node"; import { Node } from "./nodes/Node";
import {bind, createStore} from "./mvvm/index"; import { bind, createStore } from "./mvvm/index";
import {registerCustomModules} from "./custom-module"; import { registerCustomModules } from "./custom-module";
import {dealPageRemainTime, dealPxEnv} from "../px-logics"; import { dealPageRemainTime, dealPxEnv } from "../px-logics";
import Container from "../../2d/display/Container";
import { Event } from "../../2d/events/Event";
import { alignMgr } from "../decorators/AlignManager";
/** /**
* 游戏舞台 * 游戏舞台
...@@ -98,35 +101,12 @@ export class GameStage extends Node { ...@@ -98,35 +101,12 @@ export class GameStage extends Node {
/** /**
* 启动游戏 * 启动游戏
* @param config * @param config
* @param onAssetsProgress * @param onPreloadAssetsProgress 预加载素材进度
* @param onAssetsComplete * @param onPreloadAssetsComplete 预加载素材完成
* @param onStart * @param onStart
*/ */
async launch(config, onAssetsProgress?, onAssetsComplete?, onStart?) { async launch(config, onPreloadAssetsProgress?, onPreloadAssetsComplete?, onStart?) {
this._config = config; this._config = config;
const {assets, customs} = config;
let loaded = 0;
let total = assets.length;
if (customs) {
for (let custom of customs) {
if (custom.assets) {
total += custom.assets.length;
}
}
}
await loadAssets(assets, p).catch(e => {
console.log(e);
});
if (customs) {
for (let custom of customs) {
if (custom.assets) {
await loadAssets(custom.assets, p).catch(e => {
console.log(e);
});
}
}
}
this.start(); this.start();
......
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
import {DisplayObject} from "../../2d/display/index"; import {DisplayObject} from "../../2d/display/index";
import {Node} from "./nodes/Node"; import {Node} from "./nodes/Node";
import {Event} from "../../2d/events/Event";
import {playViewEffect} from "./view-effects";
/** /**
* 栈式视图容器 * 栈式视图容器
...@@ -11,77 +13,214 @@ import {Node} from "./nodes/Node"; ...@@ -11,77 +13,214 @@ import {Node} from "./nodes/Node";
export class StackContainer extends Node { export class StackContainer extends Node {
private _mutex: boolean; private _mutex: boolean;
private _stack = []; private _stack = [];
private _inserted = 0;
constructor(mutex = true) { private _playing = false;
private _actionQueue = [];
constructor(mutex = true, inserted = 0) {
super(); super();
this._mutex = mutex; this._mutex = mutex;
this._inserted = inserted;
this.percentWidth = 100; this.percentWidth = 100;
this.percentHeight = 100; this.percentHeight = 100;
this.mouseEnabled = false; this.mouseEnabled = false;
this.addEventListener(Event.START, () => {
this.mouseChildren = false;
});
this.addEventListener(Event.COMPLETE, () => {
this.mouseChildren = true;
});
}
get childNum() {
let len = this.children.length;
return len > 0 ? len - this._inserted : 0;
} }
/** /**
* 推入视图 * 推入视图
* @param view * @param view
* @param options * @param options
* @param dispatch * @param playEffect
*/ */
push(view: DisplayObject, options?, dispatch = true) { push(view: DisplayObject, options?, playEffect = true) {
if (this._mutex && this.children.length > 0) { this._actionQueue.push({action: 'push', args: arguments});
this._stack.push(this.removeChildAt(0)); this._playNextAction();
} }
this.addChild(view);
if (dispatch) { /**
this.dispatchEvent('change', {action: 'push', view, options}); * 撤出视图
} * @param options
* @param playEffect
*/
pop(options?, playEffect = true) {
this._actionQueue.push({action: 'pop', args: arguments});
this._playNextAction();
} }
/** /**
* 替换顶层视图 * 替换顶层视图
* @param view * @param view
* @param options * @param options
* @param playEffect
*/ */
replace(view: DisplayObject, options?) { replace(view: DisplayObject, options?, playEffect = true) {
if (this.pop(false)) { this._actionQueue.push({action: 'replace', args: arguments});
this.push(view, options, false); this._playNextAction();
this.dispatchEvent('change', {action: 'replace', view, options});
}
} }
/** /**
* 撤出视图 * 撤出全部视图
* @param view
* @param options
* @param playEffect
*/ */
pop(dispatch = true) { popAll(view?: DisplayObject, options?, playEffect = true) {
let len = this.children.length; this._actionQueue.push({action: 'popAll', args: arguments});
this._playNextAction();
}
private _playNextAction = () => {
if (this._playing || this._actionQueue.length === 0) {
return;
}
let actionItem = this._actionQueue.shift();
let args = [];
for (let i = 0, li = actionItem.args.length; i < li; i++) {
const argument = actionItem.args[i];
args.push(argument);
}
this._playing = true;
this['_' + actionItem.action].apply(this, args)
.then(()=>{
this._playing = false;
setTimeout(this._playNextAction, 1);
});
};
private _push(view: DisplayObject, options?, playEffect = true) {
return new Promise(resolve => {
const action = 'push';
let lastView;
if (this._mutex && this.childNum > 0) {
lastView = this.getChildAt(0);
this._stack.push(lastView);
}
view.visible = false;
this.addChild(view);
let data = {action, view, lastView, options, hasView: true};
this.dispatchEvent(Event.START, data);
playViewEffect(
playEffect ? options ? options.effect : null : null,
options ? options.effectParams : {},
this._mutex, lastView, view, this,
() => {
this.dispatchEvent(Event.COMPLETE, data);
resolve();
}
)
})
}
private _pop(options?, playEffect = true) {
return new Promise(resolve => {
const action = 'pop';
let len = this.childNum;
if (len <= 0) { if (len <= 0) {
return false; return false;
} }
this.removeChildAt(len - 1); let lastView = this.getChildAt(this.children.length - 1);
let view;
if (this._mutex) { if (this._mutex) {
this.addChild(this._stack.pop()); view = this._stack.pop();
view.visible = false;
this.addChild(view);
} }
if (dispatch) {
this.dispatchEvent('change', {action: 'pop'}); let data = {action, view, lastView, options, hasView: len > 1};
this.dispatchEvent(Event.START, data);
playViewEffect(
playEffect ? options ? options.effect : null : null,
options ? options.effectParams : {},
this._mutex, lastView, view, this,
() => {
this.dispatchEvent(Event.COMPLETE, data);
resolve();
} }
return true; )
})
} }
/** private _replace(view: DisplayObject, options?, playEffect = true) {
* 撤出全部视图 return new Promise(resolve => {
* @param view const action = 'replace';
* @param options
*/ let len = this.childNum;
popAll(view?: DisplayObject, options?) { if (len <= 0) {
this.removeChildren(); return false;
}
let lastView = this.getChildAt(len - 1);
view.visible = false;
this.addChild(view);
let data = {action, view, lastView, options, hasView: len > 1};
this.dispatchEvent(Event.START, data);
playViewEffect(
playEffect ? options ? options.effect : null : null,
options ? options.effectParams : {},
this._mutex, lastView, view, this,
() => {
this.dispatchEvent(Event.COMPLETE, data);
resolve();
}
)
})
}
private _popAll(view?: DisplayObject, options?, playEffect = true) {
return new Promise(resolve => {
const action = 'popAll';
let len = this.childNum;
if(len == 0){
resolve();
return;
}
let lastView = this.getChildAt(len);
while (this.children.length > 2) {
this.removeChildAt(0);
}
if (this._mutex) { if (this._mutex) {
this._stack.splice(0); this._stack.splice(0);
} }
if (view) { if (view) {
this.push(view, options, false); view.visible = false;
this.addChild(view);
}
let data = {action, view, lastView, options, hasView: false};
this.dispatchEvent(Event.START, data);
playViewEffect(
playEffect ? options ? options.effect : null : null,
options ? options.effectParams : {},
this._mutex, lastView, view, this,
() => {
this.dispatchEvent(Event.COMPLETE, data);
resolve();
} }
this.dispatchEvent('change', {action: 'popAll', view, options}); )
})
} }
} }
...@@ -23,23 +23,24 @@ export class Toast extends Node { ...@@ -23,23 +23,24 @@ export class Toast extends Node {
this.verticalCenter = 0; this.verticalCenter = 0;
} }
show(props: any = {}) { async show(props: any = {}) {
if (!props.text) { if (!props.text) {
return; return;
} }
let contentView = this.getContent(props.viewName); let contentView = await this.getContent(props.viewName, props);
let lab = contentView.getChildByName('lab'); let lab = contentView.getChildByName('lab');
if (!lab) { if (!lab) {
console.warn('[lab] child no exists on toast view'); console.warn('[lab] child no exists on toast view');
return; return;
} }
const {text, padding = 10, duration = 1000, showDuration = 300, hideDuration = 200} = props; const {text, padding = 10, paddingH, paddingV, duration = 1000, showDuration = 300, hideDuration = 200} = props;
lab.text = text; lab.text = text;
lab.x = lab.y = padding; lab.x = paddingH || padding;
this.width = contentView.width = lab.width + padding * 2; lab.y = paddingV || padding;
this.height = contentView.height = lab.height + padding * 2; this.width = contentView.width = lab.width + (paddingH || padding) * 2;
this.height = contentView.height = lab.height + (paddingV || padding) * 2;
if (!contentView.visible) { if (!contentView.visible) {
contentView.visible = true; contentView.visible = true;
...@@ -55,11 +56,11 @@ export class Toast extends Node { ...@@ -55,11 +56,11 @@ export class Toast extends Node {
hide(animation = true, hideDuration = 200) { hide(animation = true, hideDuration = 200) {
if (this._content) { if (this._content) {
const contentView = this._content; const contentView = this._content;
if(animation){ if (animation) {
Tween.get(contentView, null, null, true) Tween.get(contentView, null, null, true)
.to({alpha: 0}, hideDuration) .to({alpha: 0}, hideDuration)
.call(this.removeContentView, this) .call(this.removeContentView, this)
}else{ } else {
Tween.removeTweens(contentView); Tween.removeTweens(contentView);
this.removeContentView(); this.removeContentView();
} }
...@@ -72,27 +73,29 @@ export class Toast extends Node { ...@@ -72,27 +73,29 @@ export class Toast extends Node {
this._content = null; this._content = null;
} }
private getContent(viewName) { private async getContent(viewName, props) {
let view; let view;
if (this.children.length == 0) { if (this.children.length == 0) {
if (viewName) { if (viewName) {
view = this._gameStage.instantiateView(viewName); view = await this._gameStage.instantiateView(viewName);
} }
if (!view) { if (!view) {
if (!this._contentSample) { if (!this._contentSample) {
const {borderRadius = 10, labColor = 'white', labSize = 30, bgColor = 'black', bgAlpha = 0.7} = props;
this._contentSample = new Node(); this._contentSample = new Node();
let bg = new Rect(); let bg = new Rect();
bg.borderRadius = 10; bg.borderRadius = borderRadius;
bg.percentWidth = 100; bg.percentWidth = 100;
bg.percentHeight = 100; bg.percentHeight = 100;
bg.fillColor = 'black'; bg.fillColor = bgColor;
bg.alpha = 0.7; bg.alpha = bgAlpha;
this._contentSample.addChild(bg); this._contentSample.addChild(bg);
let lab = new Label(); let lab = new Label();
lab.name = 'lab'; lab.name = 'lab';
lab.fillColor = 'white'; lab.fillColor = labColor;
lab.size = 30; lab.size = labSize;
this._contentSample.addChild(lab); this._contentSample.addChild(lab);
} }
view = this._contentSample; view = this._contentSample;
......
...@@ -3,8 +3,9 @@ ...@@ -3,8 +3,9 @@
*/ */
import {globalLoader} from "../../2d/loader/Loader"; import {globalLoader} from "../../2d/loader/Loader";
import {arrayFind, linkScheme} from "../utils"; import {arrayFind, linkScheme} from "../utils/index";
import {parse} from "./bmp-text-manager"; import {parse} from "./bmp-text-manager";
import {globalEvent} from "../decorators/events";
let assetsConfig = []; let assetsConfig = [];
...@@ -22,10 +23,89 @@ const loaderMapping = { ...@@ -22,10 +23,89 @@ const loaderMapping = {
'': 'Raw', '': 'Raw',
}; };
const assetGroupLoaded = {};
const assetGroupLoading = {};
/**
* 检查资源组是否已加载
* @param groupName
*/
export function checkAssetGroupLoaded(groupName) {
return assetGroupLoaded[groupName]
}
/**
* 加载多个素材组
* @param groups
* @param onStart
* @param onFinish
*/
export async function loadAssetsGroups(groups, onStart?, onFinish?) {
let total = 0;
let loaded = 0;
for (let groupName in groups) {
if (!checkAssetGroupLoaded(groupName)) {
let depAssets = groups[groupName];
if (depAssets && depAssets.length > 0) {
total += depAssets.length;
}
}
}
onStart && await onStart();
for (let groupName in groups) {
if (!checkAssetGroupLoaded(groupName)) {
let depAssets = groups[groupName];
if (depAssets && depAssets.length > 0) {
await loadAssetsGroup(depAssets, groupName, () => {
loaded++;
globalEvent.dispatchEvent('load-assets-process', {loaded, total})
}, () => {
globalEvent.dispatchEvent('load-assets-complete');
});
}
}
}
await new Promise(resolve => {
setTimeout(resolve, 100);
});
onFinish && await onFinish();
}
/**
* 加载素材组
*/
export async function loadAssetsGroup(config, groupName, onProcess?, onComplete?) {
if (checkAssetGroupLoaded[groupName]) {
return
}
if (assetGroupLoading[groupName]) {
return new Promise((resolve, reject) => {
assetGroupLoading[groupName].push({resolve, reject})
});
} else {
assetGroupLoading[groupName] = [];
}
await loadAssets(config, onProcess, onComplete);
assetGroupLoaded[groupName] = true;
for (let p of assetGroupLoading[groupName]) {
p.resolve();
}
delete assetGroupLoading[groupName];
}
/** /**
* 加载素材 * 加载素材
*/ */
export function loadAssets(config, onProgress?, onComplete?) { export function loadAssets(config, onProgress?, onComplete?) {
if (!config) {
console.log();
}
let total = config.length; let total = config.length;
let loaded = 0; let loaded = 0;
let failedList = []; let failedList = [];
...@@ -33,14 +113,16 @@ export function loadAssets(config, onProgress?, onComplete?) { ...@@ -33,14 +113,16 @@ export function loadAssets(config, onProgress?, onComplete?) {
return Promise.all( return Promise.all(
config.map(assetConfig => { config.map(assetConfig => {
assetsConfig.push(assetConfig); assetsConfig.push(assetConfig);
if (assetConfig.url.indexOf(linkScheme) === 0) {
let linkUUID = assetConfig.url.replace(linkScheme, '');
assetConfig = getAssetByUUID(linkUUID);
}
if (assetConfig) {
const {url, ext, uuid} = assetConfig; const {url, ext, uuid} = assetConfig;
const loadFunc = loaderMapping[ext]; const loadFunc = loaderMapping[ext];
if (loadFunc) { if (loadFunc) {
if(url.indexOf(linkScheme) === 0){
loaded++;
onProgress && onProgress(loaded, total);
return Promise.resolve();
}
let method = globalLoader['load' + loadFunc]; let method = globalLoader['load' + loadFunc];
return method.call(globalLoader, url, uuid).then( return method.call(globalLoader, url, uuid).then(
(data) => { (data) => {
...@@ -54,6 +136,13 @@ export function loadAssets(config, onProgress?, onComplete?) { ...@@ -54,6 +136,13 @@ export function loadAssets(config, onProgress?, onComplete?) {
} }
); );
} else { } else {
return p();
}
} else {
return p();
}
function p() {
loaded++; loaded++;
onProgress && onProgress(loaded, total); onProgress && onProgress(loaded, total);
return Promise.resolve(); return Promise.resolve();
......
...@@ -66,7 +66,9 @@ export class Rect extends ShapeBase { ...@@ -66,7 +66,9 @@ export class Rect extends ShapeBase {
protected redraw() { protected redraw() {
const {width, height, borderRadius,} = this; const {width, height, borderRadius,} = this;
if(width == 0 || height == 0){
return;
}
if (borderRadius > 0) { if (borderRadius > 0) {
this.drawRoundedRect(0, 0, width, height, borderRadius); this.drawRoundedRect(0, 0, width, height, borderRadius);
} else { } else {
...@@ -83,6 +85,9 @@ export class Circle extends ShapeBase { ...@@ -83,6 +85,9 @@ export class Circle extends ShapeBase {
super.redraw(); super.redraw();
const {width, height} = this; const {width, height} = this;
if(width == 0 || height == 0){
return;
}
const radius = Math.min(width, height) / 2; const radius = Math.min(width, height) / 2;
this.drawCircle(radius, radius, radius); this.drawCircle(radius, radius, radius);
......
/**
* Created by rockyl on 2020-05-04.
*/
import {Tween} from "../../2d/tween/Tween";
import {gameStage} from "../launcher";
import {injectProp} from "../utils/index";
import {Ease} from "../../2d/tween/Ease";
export function playViewEffect(name, params, mutex, lastView, view, container, callback) {
let effect = name ? effects[name] : effects.simple;
effect = effect || effects.simple;
effect(params || {}, mutex, lastView, view, container, callback);
}
const effects = {
simple(params, mutex, lastView, view, container, callback) {
if (mutex) {
container.removeChild(lastView);
} else {
if (lastView && !view) {
container.removeChild(lastView);
}
}
if (view) {
if (!view.parent) {
container.addChild(view);
}
view.visible = true;
}
callback();
},
fade(params, mutex, lastView, view, container, callback) {
const {duration = 300} = params;
if (mutex) {
fadeOut(() => {
fadeIn(callback);
})
} else {
if (lastView && !view) {
fadeOut(callback)
} else {
fadeIn(callback);
}
}
function fadeOut(callback) {
if (lastView) {
Tween.get(lastView, null, null, true)
.to({alpha: 0}, duration)
.call(() => {
container.removeChild(lastView);
lastView.alpha = 1;
callback();
});
} else {
callback();
}
}
function fadeIn(callback) {
if (view) {
view.visible = true;
view.alpha = 0;
Tween.get(view, null, null, true)
.to({alpha: 1}, params.duration || 300)
.call(() => {
callback();
});
} else {
callback();
}
}
},
flew(params, mutex, lastView, view, container, callback) {
const {duration = 300, direction = 'top', ease = 'backOut', inPos: inPosInput} = params;
const {stage: {width, height}} = gameStage;
let outPos: any = {};
switch (direction) {
case 'left':
outPos.x = -width;
break;
case 'right':
outPos.x = width;
break;
case 'top':
outPos.y = -height;
break;
case 'bottom':
outPos.y = height;
break;
}
let inEase = ease;
let outEase = ease ? ease.indexOf('Out') ? ease.replace('Out', 'In') : ease.replace('In', 'Out') : '';
if (mutex) {
flewOut(() => {
flewIn(callback);
})
} else {
if (lastView && !view) {
flewOut(callback)
} else {
flewIn(callback);
}
}
function flewOut(callback) {
if (lastView) {
Tween.get(lastView, null, null, true)
.to(outPos, duration, Ease[outEase])
.call(() => {
container.removeChild(lastView);
injectProp(lastView, outPos);
callback();
});
} else {
callback();
}
}
function flewIn(callback) {
if (view) {
let inPos: any = {
x: inPosInput && inPosInput.hasOwnProperty('x') ? inPosInput.x : view.x,
y: inPosInput && inPosInput.hasOwnProperty('y') ? inPosInput.y : view.y,
};
view.visible = true;
injectProp(view, outPos);
Tween.get(view, null, null, true)
.to(inPos, duration, Ease[inEase])
.call(() => {
callback();
});
} else {
callback();
}
}
},
hulu(params, mutex, lastView, view, container, callback) {
const {duration = 300, ease = 'backOut', x = 0, y = 0} = params;
let inEase = ease;
let outEase = ease ? ease.indexOf('Out') ? ease.replace('Out', 'In') : ease.replace('In', 'Out') : '';
let outPos = {
x: parseInt(x),
y: parseInt(y),
scaleX: 0, scaleY: 0,
};
if (mutex) {
huluOut(() => {
huluIn(callback);
})
} else {
if (lastView && !view) {
huluOut(callback)
} else {
huluIn(callback);
}
}
function huluOut(callback) {
if (lastView) {
outPos.x -= lastView.width / 2;
outPos.y -= lastView.height / 2;
Tween.get(lastView, null, null, true)
.to(outPos, duration, Ease[outEase])
.call(() => {
container.removeChild(lastView);
injectProp(lastView, {scaleX: 1, scaleY: 1});
callback();
});
} else {
callback();
}
}
function huluIn(callback) {
if (view) {
let inPos: any = {
x: view.x,
y: view.y,
scaleX: 1, scaleY: 1
};
outPos.x -= view.width / 2;
outPos.y -= view.height / 2;
view.visible = true;
injectProp(view, outPos);
Tween.get(view, null, null, true)
.to(inPos, duration, Ease[inEase])
.call(() => {
view.anchorX = 0;
view.anchorY = 0;
callback();
});
} else {
callback();
}
}
},
zoom(params, mutex, lastView, view, container, callback) {
const {duration = 300, ease = 'backOut'} = params;
let inEase = ease;
let outEase = ease ? ease.indexOf('Out') ? ease.replace('Out', 'In') : ease.replace('In', 'Out') : '';
if (mutex) {
zoomOut(() => {
zoomIn(callback);
})
} else {
if (lastView && !view) {
zoomOut(callback)
} else {
zoomIn(callback);
}
}
function zoomOut(callback) {
if (lastView) {
Tween.get(lastView, null, null, true)
.to({scaleX: 0, scaleY: 0}, duration, Ease[outEase])
.call(() => {
container.removeChild(lastView);
injectProp(view, {scaleX: 1, scaleY: 1});
callback();
});
} else {
callback();
}
}
function zoomIn(callback) {
if (view) {
view.anchorX = view.width / 2;
view.anchorY = view.height / 2;
view.visible = true;
injectProp(view, {scaleX: 0, scaleY: 0});
Tween.get(view, null, null, true)
.to({scaleX: 1, scaleY: 1}, duration, Ease[inEase])
.call(() => {
view.anchorX = 0;
view.anchorY = 0;
callback();
});
} else {
callback();
}
}
},
};
...@@ -3,18 +3,20 @@ ...@@ -3,18 +3,20 @@
*/ */
import {Stage} from "../2d/display/index"; import {Stage} from "../2d/display/index";
import {registerCustomModuleFromConfig, registerScripts, RENDERER_TYPE, setProcessMetaLibs, StageScaleMode} from ".."; import {GameStage, registerCustomModuleFromConfig} from "./game-warpper/index";
import {GameStage} from "./game-warpper/index"; import {setGlobalContext, setProcessMetaLibs} from "./behavior-runtime/index";
import {setGlobalContext} from "./behavior-runtime";
import {globalLoader} from "../2d/loader/Loader"; import {globalLoader} from "../2d/loader/Loader";
import {Event} from "../2d/events/Event"; import {Event} from "../2d/events/Event";
import builtinLoadingView from "./game-warpper/LoadingView"; import builtinLoadingView from "./game-warpper/LoadingView";
import {queryParams} from "./web"; import {queryParams} from "./web";
import {initAutoLayout} from "./game-warpper/auto-layout"; import {initAutoLayout} from "./game-warpper/auto-layout";
import {EditorStage} from "./game-warpper/EditorStage"; import {registerScripts} from "./decorators/scripts";
import {RENDERER_TYPE, StageScaleMode} from "../2d/const";
import { alignMgr } from "./decorators/AlignManager";
export let gameStage: GameStage; export let gameStage: GameStage;
export let editorStage: EditorStage; export let editorStage: EditorStage;
export let alignManager = alignMgr;
export let editorMode = false; export let editorMode = false;
export let assetResolver; export let assetResolver;
......
...@@ -103,9 +103,9 @@ export function dealPageRemainTime() { ...@@ -103,9 +103,9 @@ export function dealPageRemainTime() {
} }
} }
export function accessLog(pagebizid, params?) { export function accessLog(pageBizId, params?) {
let p = { let p = {
pagebizid, pageBizId,
}; };
injectProp(p, params); injectProp(p, params);
return httpRequest('buriedPoint', 'get', p); return httpRequest('buriedPoint', 'get', p);
......
...@@ -34,14 +34,14 @@ export function objClone(obj) { ...@@ -34,14 +34,14 @@ export function objClone(obj) {
return obj ? JSON.parse(JSON.stringify(obj)) : obj; return obj ? JSON.parse(JSON.stringify(obj)) : obj;
} }
const percentKeys = ['width', 'height']; const percentKeys = ['width', 'height', 'top', 'left', 'bottom', 'right'];
export function propertyParse(key, node, properties) { export function propertyParse(key, node, properties) {
let value = properties[key]; let value = properties[key];
let targetKey = key; let targetKey = key;
if (percentKeys.indexOf(key) >= 0) { if(percentKeys.indexOf(key) >= 0) {
if (typeof value === 'string') { if(typeof value === 'string') {
if (value[value.length - 1] === '%') { if(value[value.length - 1] === '%') {
targetKey = 'percent' + key[0].toUpperCase() + key.substr(1); targetKey = 'percent' + key[0].toUpperCase() + key.substr(1);
} }
value = parseInt(value); value = parseInt(value);
...@@ -60,9 +60,9 @@ export function getDataByPath(scope, path, throwException?) { ...@@ -60,9 +60,9 @@ export function getDataByPath(scope, path, throwException?) {
let func = new Function('scope', `return scope` + (path ? ('.' + path) : '')); let func = new Function('scope', `return scope` + (path ? ('.' + path) : ''));
try { try {
return func(scope); return func(scope);
} catch (e) { } catch(e) {
//console.warn(e); //console.warn(e);
if (throwException) { if(throwException) {
throw e; throw e;
} }
} }
...@@ -77,8 +77,8 @@ export function safeEval(code, throwException = false) { ...@@ -77,8 +77,8 @@ export function safeEval(code, throwException = false) {
let func = new Function(code); let func = new Function(code);
try { try {
return func(); return func();
} catch (e) { } catch(e) {
if (throwException) { if(throwException) {
throw e; throw e;
} }
} }
...@@ -328,8 +328,8 @@ export const cmdOldPrefix = '//z-'; ...@@ -328,8 +328,8 @@ export const cmdOldPrefix = '//z-';
* @param source * @param source
*/ */
export function injectProperties(target, source) { export function injectProperties(target, source) {
for (let key in source) { for(let key in source) {
if (key.indexOf('//') !== 0 && !source.hasOwnProperty(cmdPrefix + key)) { if(key.indexOf('//') !== 0 && !source.hasOwnProperty(cmdPrefix + key)) {
propertyParse(key, target, source); propertyParse(key, target, source);
} }
} }
...@@ -344,10 +344,10 @@ export function injectProperties(target, source) { ...@@ -344,10 +344,10 @@ export function injectProperties(target, source) {
* @param includeSelf * @param includeSelf
*/ */
export function traverseViewNode(node: Container, callback: Function, includeSelf = false) { export function traverseViewNode(node: Container, callback: Function, includeSelf = false) {
if (includeSelf) { if(includeSelf) {
callback(node); callback(node);
} }
for (let child of node.children) { for(let child of node.children) {
callback(child, node); callback(child, node);
if (child.children && child.children.length > 0) { if (child.children && child.children.length > 0) {
...@@ -355,3 +355,14 @@ export function traverseViewNode(node: Container, callback: Function, includeSel ...@@ -355,3 +355,14 @@ export function traverseViewNode(node: Container, callback: Function, includeSel
} }
} }
} }
/**
* 数字转化为boolean值
* NaN -> false 'aaa' -> false null -> false undefined -> false
* 666 -> true '007' -> true Infinity -> true
* @param v
* @returns {boolean}
*/
export function toBoolean(v): boolean {
return !isNaN(v) && v !== null && v !== undefined;
}
...@@ -438,10 +438,10 @@ rollup-plugin-node-resolve@^5.2.0: ...@@ -438,10 +438,10 @@ rollup-plugin-node-resolve@^5.2.0:
resolve "^1.11.1" resolve "^1.11.1"
rollup-pluginutils "^2.8.1" rollup-pluginutils "^2.8.1"
rollup-plugin-progress@^1.1.1: rollup-plugin-progress@^1.1.2:
version "1.1.1" version "1.1.2"
resolved "https://registry.npm.taobao.org/rollup-plugin-progress/download/rollup-plugin-progress-1.1.1.tgz#fcce2f915d545014ac89ea0927ee97cb48052f60" resolved "https://registry.npm.taobao.org/rollup-plugin-progress/download/rollup-plugin-progress-1.1.2.tgz#5c1dfe7c50f654906bc34d167d5512ee1a4b72d5"
integrity sha1-/M4vkV1UUBSsieoJJ+6Xy0gFL2A= integrity sha1-XB3+fFD2VJBrw00WfVUS7hpLctU=
dependencies: dependencies:
chalk "^2.4.2" chalk "^2.4.2"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment