diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index 6868f69d1b..bf5b8d5cc8 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -238,7 +238,8 @@ export class CanvasComponent extends Component { } public alignWithScreen () { - let nodeSize, designSize; + let nodeSize; + let designSize; if (CC_EDITOR) { // nodeSize = designSize = cc.engine.getDesignResolutionSize(); nodeSize = designSize = this._designResolution; @@ -247,7 +248,7 @@ export class CanvasComponent extends Component { else { const canvasSize = cc.visibleRect; nodeSize = canvasSize; - const designSize = cc.view.getDesignResolutionSize(); + designSize = cc.view.getDesignResolutionSize(); const clipTopRight = !this.fitHeight && !this.fitWidth; let offsetX = 0; let offsetY = 0; @@ -300,3 +301,5 @@ export class CanvasComponent extends Component { } } } + +cc.CanvasComponent = CanvasComponent; diff --git a/cocos/3d/ui/components/scroll-bar-component.ts b/cocos/3d/ui/components/scroll-bar-component.ts index c5b2a15380..3c7c130d14 100644 --- a/cocos/3d/ui/components/scroll-bar-component.ts +++ b/cocos/3d/ui/components/scroll-bar-component.ts @@ -25,14 +25,14 @@ ****************************************************************************/ import { Component } from '../../../components/component'; -import { clamp01 } from '../../../core/utils/misc'; import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Vec3, Vec2, Size } from '../../../core/value-types'; +import { clamp01 } from '../../../core/utils/misc'; +import { Size, Vec2, Vec3 } from '../../../core/value-types'; +import { ccenum } from '../../../core/value-types/enum'; +import { vec3 } from '../../../core/vmath'; import { Node } from '../../../scene-graph/node'; import { ScrollViewComponent } from './scroll-view-component'; -import { vec3 } from '../../../core/vmath'; import { SpriteComponent } from './sprite-component'; -import { ccenum } from '../../../core/value-types/enum'; const GETTINGSHORTERFACTOR = 20; const ZERO = new Vec3(); @@ -53,8 +53,8 @@ enum Direction { /** * @property {Number} VERTICAL */ - VERTICAL = 1 -}; + VERTICAL = 1, +} ccenum(Direction); @@ -69,20 +69,6 @@ ccenum(Direction); @executionOrder(100) @menu('UI/ScrollBar') export class ScrollBarComponent extends Component { - @property - private _scrollView: ScrollViewComponent | null = null; - @property - private _handle: SpriteComponent | null = null; - @property - private _direction = Direction.HORIZONTAL; - @property - private _enableAutoHide = false; - @property - private _autoHideTime = 1.0; - - private _touching = false; - private _opacity = 255; - private _autoHideRemainingTime = 0; /** * !#en The "handle" part of the scrollbar. @@ -90,15 +76,15 @@ export class ScrollBarComponent extends Component { * @property {Sprite} handle */ @property({ - type: SpriteComponent + type: SpriteComponent, }) - get handle() { + get handle () { return this._handle; } - set handle(value: SpriteComponent | null) { + set handle (value: SpriteComponent | null) { if (this._handle === value) { - return + return; } this._handle = value; this.onScroll(cc.v2(0, 0)); @@ -110,13 +96,13 @@ export class ScrollBarComponent extends Component { * @property {Scrollbar.Direction} direction */ @property({ - type: Direction + type: Direction, }) - get direction() { + get direction () { return this._direction; } - set direction(value) { + set direction (value) { if (this._direction === value) { return; } @@ -131,11 +117,11 @@ export class ScrollBarComponent extends Component { * @property {Boolean} enableAutoHide */ @property - get enableAutoHide() { + get enableAutoHide () { return this._enableAutoHide; } - set enableAutoHide(value) { + set enableAutoHide (value) { if (this._enableAutoHide === value) { return; } @@ -156,11 +142,11 @@ export class ScrollBarComponent extends Component { * @property {Number} autoHideTime */ @property - get autoHideTime() { + get autoHideTime () { return this._autoHideTime; } - set autoHideTime(value) { + set autoHideTime (value) { if (this._autoHideTime === value) { return; } @@ -168,62 +154,35 @@ export class ScrollBarComponent extends Component { this._autoHideTime = value; } - static Direction = Direction; + public static Direction = Direction; + @property + private _scrollView: ScrollViewComponent | null = null; + @property + private _handle: SpriteComponent | null = null; + @property + private _direction = Direction.HORIZONTAL; + @property + private _enableAutoHide = false; + @property + private _autoHideTime = 1.0; - protected onEnable() { - let renderComp = this.node.getComponent(SpriteComponent); - if (renderComp) { - this._opacity = renderComp.color.a; - } - } + private _touching = false; + private _opacity = 255; + private _autoHideRemainingTime = 0; - protected start() { - if (this._enableAutoHide) { - this._setOpacity(0); - } - } - - public hide() { + public hide () { this._autoHideRemainingTime = 0; this._setOpacity(0); } - public show() { + public show () { this._autoHideRemainingTime = this._autoHideTime; this._setOpacity(this._opacity); } - protected update(dt) { - this._processAutoHide(dt); - } - - private _convertToScrollViewSpace(content: Node) { + public onScroll (outOfBoundary: Vec3) { if (!this._scrollView) { - return ZERO; - } - - const worldSpacePos = content.uiTransfromComp!.convertToWorldSpace(ZERO); - const scrollViewSpacePos = this._scrollView.node.uiTransfromComp!.convertToNodeSpace(worldSpacePos); - return scrollViewSpacePos; - } - - private _setOpacity(opacity: number) { - if (this._handle) { - let renderComp = this.node.getComponent(SpriteComponent); - if (renderComp) { - renderComp.color.a = opacity; - } - - renderComp = this._handle.getComponent(SpriteComponent); - if (renderComp) { - renderComp.color.a = opacity; - } - } - } - - public onScroll(outOfBoundary: Vec3) { - if (!this._scrollView) { - return + return; } const content = this._scrollView.content; @@ -231,9 +190,9 @@ export class ScrollBarComponent extends Component { return; } - var contentSize = content.getContentSize(); - var scrollViewSize = this._scrollView.node.getContentSize(); - var barSize = this.node.getContentSize(); + const contentSize = content.getContentSize(); + const scrollViewSize = this._scrollView.node.getContentSize(); + const barSize = this.node.getContentSize(); if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) { return; @@ -272,14 +231,87 @@ export class ScrollBarComponent extends Component { this._updateLength(length); this._updateHanlderPosition(position); - } - public setScrollView(scrollView: ScrollViewComponent) { + public setScrollView (scrollView: ScrollViewComponent) { this._scrollView = scrollView; } - private _updateHanlderPosition(position: Vec3) { + public onTouchBegan () { + if (!this._enableAutoHide) { + return; + } + this._touching = true; + } + + public onTouchEnded () { + if (!this._enableAutoHide) { + return; + } + + this._touching = false; + + if (this._autoHideTime <= 0) { + return; + } + + if (this._scrollView) { + const content = this._scrollView.content; + if (content) { + const contentSize = content.getContentSize(); + const scrollViewSize = this._scrollView.node.getContentSize(); + + if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) { + return; + } + } + } + + this._autoHideRemainingTime = this._autoHideTime; + } + + protected onEnable () { + const renderComp = this.node.getComponent(SpriteComponent); + if (renderComp) { + this._opacity = renderComp.color.a; + } + } + + protected start () { + if (this._enableAutoHide) { + this._setOpacity(0); + } + } + + protected update (dt) { + this._processAutoHide(dt); + } + + private _convertToScrollViewSpace (content: Node) { + if (!this._scrollView) { + return ZERO; + } + + const worldSpacePos = content.uiTransfromComp!.convertToWorldSpace(ZERO); + const scrollViewSpacePos = this._scrollView.node.uiTransfromComp!.convertToNodeSpace(worldSpacePos); + return scrollViewSpacePos; + } + + private _setOpacity (opacity: number) { + if (this._handle) { + let renderComp = this.node.getComponent(SpriteComponent); + if (renderComp) { + renderComp.color.a = opacity; + } + + renderComp = this._handle.getComponent(SpriteComponent); + if (renderComp) { + renderComp.color.a = opacity; + } + } + } + + private _updateHanlderPosition (position: Vec3) { if (this._handle) { const oldPosition = this._fixupHandlerPosition(); @@ -287,14 +319,13 @@ export class ScrollBarComponent extends Component { } } - private _fixupHandlerPosition() { + private _fixupHandlerPosition () { const barSize = this.node.getContentSize(); const barAnchor = this.node.getAnchorPoint(); const handleSize = this.handle!.node.getContentSize(); const handleParent = this.handle!.node.parent!; - vec3.set(_tempPos_1, -barSize.width * barAnchor.x, -barSize.height * barAnchor.y, 0); const leftBottomWorldPosition = this.node!.uiTransfromComp!.convertToWorldSpaceAR(_tempPos_2, _tempPos_1); let fixupPosition = new Vec3(); @@ -311,14 +342,7 @@ export class ScrollBarComponent extends Component { return fixupPosition; } - public onTouchBegan() { - if (!this._enableAutoHide) { - return; - } - this._touching = true; - } - - private _conditionalDisableScrollBar(contentSize: Size, scrollViewSize: Size) { + private _conditionalDisableScrollBar (contentSize: Size, scrollViewSize: Size) { if (contentSize.width <= scrollViewSize.width && this._direction === Direction.HORIZONTAL) { return true; } @@ -329,34 +353,7 @@ export class ScrollBarComponent extends Component { return false; } - public onTouchEnded() { - if (!this._enableAutoHide) { - return; - } - - this._touching = false; - - if (this._autoHideTime <= 0) { - return; - } - - - if (this._scrollView) { - const content = this._scrollView.content; - if (content) { - const contentSize = content.getContentSize(); - const scrollViewSize = this._scrollView.node.getContentSize(); - - if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) { - return; - } - } - } - - this._autoHideRemainingTime = this._autoHideTime; - } - - private _calculateLength(contentMeasure: number, scrollViewMeasure: number, handleNodeMeasure: number, outOfBoundary: number) { + private _calculateLength (contentMeasure: number, scrollViewMeasure: number, handleNodeMeasure: number, outOfBoundary: number) { let denominatorValue = contentMeasure; if (outOfBoundary) { denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR; @@ -366,7 +363,14 @@ export class ScrollBarComponent extends Component { return handleNodeMeasure * lengthRation; } - private _calculatePosition(contentMeasure: number, scrollViewMeasure: number, handleNodeMeasure: number, contentPosition: number, outOfBoundary: number, actualLenth: number) { + private _calculatePosition ( + contentMeasure: number, + scrollViewMeasure: number, + handleNodeMeasure: number, + contentPosition: number, + outOfBoundary: number, + actualLenth: number, + ) { let denominatorValue = contentMeasure - scrollViewMeasure; if (outOfBoundary) { denominatorValue += Math.abs(outOfBoundary); @@ -386,12 +390,12 @@ export class ScrollBarComponent extends Component { } } - private _updateLength(length: number) { + private _updateLength (length: number) { if (this._handle) { - let handleNode = this._handle.node; + const handleNode = this._handle.node; const handleNodeSize = handleNode.getContentSize(); const anchor = handleNode.getAnchorPoint(); - if(anchor.x !== defaultAnchor.x || anchor.y !== defaultAnchor.y){ + if (anchor.x !== defaultAnchor.x || anchor.y !== defaultAnchor.y){ handleNode.setAnchorPoint(defaultAnchor); } @@ -403,14 +407,13 @@ export class ScrollBarComponent extends Component { } } - private _processAutoHide(deltaTime: number) { + private _processAutoHide (deltaTime: number) { if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) { return; } else if (this._touching) { return; } - this._autoHideRemainingTime -= deltaTime; if (this._autoHideRemainingTime <= this._autoHideTime) { this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime); @@ -419,3 +422,5 @@ export class ScrollBarComponent extends Component { } } } + +cc.ScrollBarComponent = ScrollBarComponent; diff --git a/cocos/3d/ui/components/scroll-view-component.ts b/cocos/3d/ui/components/scroll-view-component.ts index 34e3b6bede..7f9adb75bf 100644 --- a/cocos/3d/ui/components/scroll-view-component.ts +++ b/cocos/3d/ui/components/scroll-view-component.ts @@ -23,16 +23,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -import { Node } from '../../../scene-graph/node'; -import { Enum, Vec2, Vec3, Size } from '../../../core/value-types'; -import { ViewGroupComponent } from './view-group-component'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { ScrollBarComponent } from './scroll-bar-component'; import ComponentEventHandler from '../../../components/CCComponentEventHandler'; -import { LayoutComponent } from './layout-component'; +import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { EventTouch } from '../../../core/platform/event-manager'; import Touch from '../../../core/platform/event-manager/CCTouch'; +import { Enum, Size, Vec2, Vec3 } from '../../../core/value-types'; import { vec3 } from '../../../core/vmath'; +import { Node } from '../../../scene-graph/node'; +import { LayoutComponent } from './layout-component'; +import { ScrollBarComponent } from './scroll-bar-component'; +import { ViewGroupComponent } from './view-group-component'; const NodeEvent = Node.EventType; @@ -43,13 +43,13 @@ const MOVEMENT_FACTOR = 0.7; const ZERO = new Vec3(); const _tempPos = new Vec3(); -let quintEaseOut = function (time) { +const quintEaseOut = (time) => { time -= 1; return (time * time * time * time * time + 1); }; -let getTimeInMilliseconds = function () { - let currentTime = new Date(); +const getTimeInMilliseconds = () => { + const currentTime = new Date(); return currentTime.getMilliseconds(); }; @@ -136,7 +136,7 @@ enum EventType { * !#zh 滚动视图滚动开始时发出的事件 * @property {Number} SCROLL_BEGAN */ - SCROLL_BEGAN = 12 + SCROLL_BEGAN = 12, } Enum(EventType); @@ -154,7 +154,7 @@ const eventMap = { 'scroll-ended': EventType.SCROLL_ENDED, 'touch-up': EventType.TOUCH_UP, 'scroll-ended-with-threshold': EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD, - 'scroll-began': EventType.SCROLL_BEGAN + 'scroll-began': EventType.SCROLL_BEGAN, }; /** @@ -172,6 +172,87 @@ const eventMap = { @executionOrder(100) @menu('UI/ScrollView') export class ScrollViewComponent extends ViewGroupComponent { + + /** + * !#en This is a reference to the UI element to be scrolled. + * !#zh 可滚动展示内容的节点。 + * @property {Node} content + */ + @property({ + type: Node, + }) + get content () { + return this._content; + } + set content (value: Node | null) { + if (this._content === value){ + return; + } + + this._content = value; + this._calculateBoundary(); + } + + /** + * !#en The horizontal scrollbar reference. + * !#zh 水平滚动的 ScrollBar。 + * @property {Scrollbar} horizontalScrollBar + */ + @property({ + type: ScrollBarComponent, + }) + get horizontalScrollBar () { + return this._horizontalScrollBar; + } + + set horizontalScrollBar (value: ScrollBarComponent | null) { + if (this._horizontalScrollBar === value){ + return; + } + + this._horizontalScrollBar = value; + + if (this._horizontalScrollBar) { + this._horizontalScrollBar.setScrollView(this); + // this._updateScrollBar(0); + this._updateScrollBar(ZERO); + } + } + + /** + * !#en The vertical scrollbar reference. + * !#zh 垂直滚动的 ScrollBar。 + * @property {Scrollbar} verticalScrollBar + */ + @property({ + type: ScrollBarComponent, + }) + get verticalScrollBar () { + return this._verticalScrollBar; + } + + set verticalScrollBar (value: ScrollBarComponent | null) { + if (this._verticalScrollBar === value) { + return; + } + + this._verticalScrollBar = value; + + if (this._verticalScrollBar) { + this._verticalScrollBar.setScrollView(this); + this._updateScrollBar(ZERO); + } + } + + get view () { + if (!this._content) { + return null; + } + + return this._content.parent; + } + + public static EventType = EventType; /** * !#en Enable horizontal scroll. * !#zh 是否开启水平滚动。 @@ -205,7 +286,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * @property {Number} brake */ @property({ - range: [0, 1, 0.1] + range: [0, 1, 0.1], }) public brake = 0.5; @@ -222,7 +303,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * @property {Number} bounceDuration */ @property({ - range: [0, 10] + range: [0, 10], }) public bounceDuration = 1; @@ -275,94 +356,13 @@ export class ScrollViewComponent extends ViewGroupComponent { private _stopMouseWheel = false; private _mouseWheelEventElapsedTime = 0.0; private _isScrollEndedWithThresholdEventFired = false; - //use bit wise operations to indicate the direction + // use bit wise operations to indicate the direction private _scrollEventEmitMask = 0; private _isBouncing = false; private _scrolling = false; private _contentPos = new Vec3(); private _deltaPos = new Vec3(); - /** - * !#en This is a reference to the UI element to be scrolled. - * !#zh 可滚动展示内容的节点。 - * @property {Node} content - */ - @property({ - type: Node - }) - get content() { - return this._content; - } - set content(value: Node | null) { - if(this._content === value){ - return; - } - - this._content = value; - this._calculateBoundary(); - } - - /** - * !#en The horizontal scrollbar reference. - * !#zh 水平滚动的 ScrollBar。 - * @property {Scrollbar} horizontalScrollBar - */ - @property({ - type: ScrollBarComponent - }) - get horizontalScrollBar() { - return this._horizontalScrollBar; - } - - set horizontalScrollBar(value: ScrollBarComponent | null) { - if(this._horizontalScrollBar === value){ - return; - } - - this._horizontalScrollBar = value; - - if (this._horizontalScrollBar) { - this._horizontalScrollBar.setScrollView(this); - // this._updateScrollBar(0); - this._updateScrollBar(ZERO); - } - } - - /** - * !#en The vertical scrollbar reference. - * !#zh 垂直滚动的 ScrollBar。 - * @property {Scrollbar} verticalScrollBar - */ - @property({ - type: ScrollBarComponent - }) - get verticalScrollBar() { - return this._verticalScrollBar; - } - - set verticalScrollBar(value: ScrollBarComponent | null) { - if (this._verticalScrollBar === value) { - return; - } - - this._verticalScrollBar = value; - - if (this._verticalScrollBar) { - this._verticalScrollBar.setScrollView(this); - this._updateScrollBar(ZERO); - } - } - - get view() { - if (!this._content) { - return null; - } - - return this._content.parent; - } - - static EventType = EventType; - /** * !#en Scroll the content to the bottom boundary of ScrollView. * !#zh 视图内容将在规定时间内滚动到视图底部。 @@ -374,8 +374,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to the bottom of the view. * scrollView.scrollToBottom(0.1); */ - scrollToBottom(timeInSecond: number, attenuated: boolean) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToBottom (timeInSecond: number, attenuated: boolean) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: false, applyToVertical: true, @@ -399,8 +399,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to the top of the view. * scrollView.scrollToTop(0.1); */ - scrollToTop(timeInSecond: number, attenuated: boolean) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToTop (timeInSecond: number, attenuated: boolean) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 1), applyToHorizontal: false, applyToVertical: true, @@ -424,8 +424,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to the left of the view. * scrollView.scrollToLeft(0.1); */ - scrollToLeft(timeInSecond: number, attenuated: boolean) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToLeft (timeInSecond: number, attenuated: boolean) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: true, applyToVertical: false, @@ -449,8 +449,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to the right of the view. * scrollView.scrollToRight(0.1); */ - scrollToRight(timeInSecond, attenuated) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToRight (timeInSecond, attenuated) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 0), applyToHorizontal: true, applyToVertical: false, @@ -474,8 +474,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to the upper left corner of the view. * scrollView.scrollToTopLeft(0.1); */ - scrollToTopLeft(timeInSecond, attenuated) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToTopLeft (timeInSecond, attenuated) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 1), applyToHorizontal: true, applyToVertical: true, @@ -499,8 +499,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to the top right corner of the view. * scrollView.scrollToTopRight(0.1); */ - scrollToTopRight(timeInSecond, attenuated) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToTopRight (timeInSecond, attenuated) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 1), applyToHorizontal: true, applyToVertical: true, @@ -524,8 +524,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to the lower left corner of the view. * scrollView.scrollToBottomLeft(0.1); */ - scrollToBottomLeft(timeInSecond, attenuated) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToBottomLeft (timeInSecond, attenuated) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: true, applyToVertical: true, @@ -549,8 +549,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to the lower right corner of the view. * scrollView.scrollToBottomRight(0.1); */ - scrollToBottomRight(timeInSecond, attenuated) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToBottomRight (timeInSecond, attenuated) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 0), applyToHorizontal: true, applyToVertical: true, @@ -563,7 +563,6 @@ export class ScrollViewComponent extends ViewGroupComponent { } } - /** * !#en Scroll with an offset related to the ScrollView's top left origin, if timeInSecond is omitted, then it will jump to the * specific offset immediately. @@ -578,11 +577,11 @@ export class ScrollViewComponent extends ViewGroupComponent { * let maxScrollOffset = this.getMaxScrollOffset(); * scrollView.scrollToOffset(new Vec3(maxScrollOffset.x / 2, 0, 0), 0.1); */ - scrollToOffset(offset, timeInSecond, attenuated) { - let maxScrollOffset = this.getMaxScrollOffset(); + public scrollToOffset (offset, timeInSecond, attenuated) { + const maxScrollOffset = this.getMaxScrollOffset(); - let anchor = new Vec2(0, 0); - //if maxScrollOffset is 0, then always align the content's top left origin to the top left corner of its parent + const anchor = new Vec2(0, 0); + // if maxScrollOffset is 0, then always align the content's top left origin to the top left corner of its parent if (maxScrollOffset.x === 0) { anchor.x = 0; } else { @@ -604,9 +603,9 @@ export class ScrollViewComponent extends ViewGroupComponent { * @method getScrollOffset * @return {Vec2} - A Vec2 value indicate the current scroll offset. */ - getScrollOffset() { - let topDelta = this._getContentTopBoundary() - this._topBoundary; - let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; + public getScrollOffset () { + const topDelta = this._getContentTopBoundary() - this._topBoundary; + const leftDeta = this._getContentLeftBoundary() - this._leftBoundary; return new Vec3(leftDeta, topDelta, 0); } @@ -617,9 +616,9 @@ export class ScrollViewComponent extends ViewGroupComponent { * @method getMaxScrollOffset * @return {Vec2} - A Vec2 value indicate the maximize scroll offset in x and y axis. */ - getMaxScrollOffset() { - let scrollSize = this.node.getContentSize(); - let contentSize = this._content!.getContentSize(); + public getMaxScrollOffset () { + const scrollSize = this.node.getContentSize(); + const contentSize = this._content!.getContentSize(); let horizontalMaximizeOffset = contentSize.width - scrollSize.width; let verticalMaximizeOffset = contentSize.height - scrollSize.height; horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0; @@ -640,8 +639,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to middle position. * scrollView.scrollToBottomRight(0.5, 0.1); */ - scrollToPercentHorizontal(percent, timeInSecond, attenuated) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToPercentHorizontal (percent, timeInSecond, attenuated) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(percent, 0), applyToHorizontal: true, applyToVertical: false, @@ -669,8 +668,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Horizontal scroll to view right. * scrollView.scrollTo(new Vec2(1, 0), 0.1); */ - scrollTo(anchor: Vec2, timeInSecond: number, attenuated?: boolean) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollTo (anchor: Vec2, timeInSecond: number, attenuated?: boolean) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(anchor), applyToHorizontal: true, applyToVertical: true, @@ -694,8 +693,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * // Scroll to middle position. * scrollView.scrollToPercentVertical(0.5, 0.1); */ - scrollToPercentVertical(percent: number, timeInSecond: number, attenuated?: boolean) { - let moveDelta = this._calculateMovePercentDelta({ + public scrollToPercentVertical (percent: number, timeInSecond: number, attenuated?: boolean) { + const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, percent), applyToHorizontal: false, applyToVertical: true, @@ -713,7 +712,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * !#zh 停止自动滚动, 调用此 API 可以让 Scrollview 立即停止滚动 * @method stopAutoScroll */ - stopAutoScroll() { + public stopAutoScroll () { this._autoScrolling = false; this._autoScrollAccumulatedTime = this._autoScrollTotalTime; } @@ -724,7 +723,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * @method setContentPosition * @param {Vec2} position - The position in content's parent space. */ - setContentPosition(position: Vec3) { + public setContentPosition (position: Vec3) { if (position.fuzzyEquals(this.getContentPosition(), EPSILON)) { return; } @@ -739,8 +738,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * @method getContentPosition * @returns {Position} - The content's position in its parent space. */ - getContentPosition() { - if(!this._content){ + public getContentPosition () { + if (!this._content){ return ZERO; } @@ -754,7 +753,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * @method isScrolling * @returns {Boolean} - Whether the user is currently dragging the ScrollView to scroll it */ - isScrolling() { + public isScrolling () { return this._scrolling; } @@ -764,12 +763,12 @@ export class ScrollViewComponent extends ViewGroupComponent { * @method isAutoScrolling * @returns {Boolean} - Whether the ScrollView is currently scrolling because of a bounceback or inertia slowdown. */ - isAutoScrolling() { + public isAutoScrolling () { return this._autoScrolling; } - //private methods - _registerEvent() { + // private methods + public _registerEvent () { this.node.on(NodeEvent.TOUCH_START, this._onTouchBegan, this, true); this.node.on(NodeEvent.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.on(NodeEvent.TOUCH_END, this._onTouchEnded, this, true); @@ -777,7 +776,7 @@ export class ScrollViewComponent extends ViewGroupComponent { this.node.on(NodeEvent.MOUSE_WHEEL, this._onMouseWheel, this, true); } - _unregisterEvent() { + public _unregisterEvent () { this.node.off(NodeEvent.TOUCH_START, this._onTouchBegan, this, true); this.node.off(NodeEvent.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.off(NodeEvent.TOUCH_END, this._onTouchEnded, this, true); @@ -785,9 +784,9 @@ export class ScrollViewComponent extends ViewGroupComponent { this.node.off(NodeEvent.MOUSE_WHEEL, this._onMouseWheel, this, true); } - _onMouseWheel(event, captureListeners) { - if (!this.enabledInHierarchy) return; - if (this._hasNestedViewGroup(event, captureListeners)) return; + public _onMouseWheel (event, captureListeners) { + if (!this.enabledInHierarchy) { return; } + if (this._hasNestedViewGroup(event, captureListeners)) { return; } let deltaMove = new Vec3(); let wheelPrecision = -0.1; @@ -813,9 +812,686 @@ export class ScrollViewComponent extends ViewGroupComponent { this._stopPropagationIfTargetIsMe(event); } - _checkMouseWheel(dt: number) { - let currentOutOfBoundary = this._getHowMuchOutOfBoundary(); - let maxElapsedTime = 0.1; + public _calculateBoundary () { + if (this.content) { + // refresh content size + const layout = this.content.getComponent(LayoutComponent); + if (layout && layout.enabledInHierarchy) { + layout.updateLayout(); + } + const viewSize = this.view!.getContentSize(); + + const anchorX = viewSize.width * this.view!.anchorX; + const anchorY = viewSize.height * this.view!.anchorY; + + this._leftBoundary = -anchorX; + this._bottomBoundary = -anchorY; + + this._rightBoundary = this._leftBoundary + viewSize.width; + this._topBoundary = this._bottomBoundary + viewSize.height; + + this._moveContentToTopLeft(viewSize); + } + + } + + // this is for nested scrollview + public _hasNestedViewGroup (event?: EventTouch, captureListeners?: any) { + if (!event || event.eventPhase !== cc.Event.CAPTURING_PHASE) { return; } + + if (captureListeners) { + // captureListeners are arranged from child to parent + for (const listerner of captureListeners) { + const item = listerner as Node; + + if (this.node === item) { + if (event.target && (event.target as Node).getComponent(ViewGroupComponent)) { + return true; + } + return false; + } + + if (item.getComponent(ViewGroupComponent)) { + return true; + } + } + } + return false; + } + + public getScrollEndedEventTiming () { + return EPSILON; + } + + public _startInertiaScroll (touchMoveVelocity: Vec3) { + const inertiaTotalMovement = touchMoveVelocity.mul(MOVEMENT_FACTOR); + this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity); + } + + public _calculateAttenuatedFactor (distance: number) { + if (this.brake <= 0) { + return (1 - this.brake); + } + + // attenuate formula from: http://learnopengl.com/#!Lighting/Light-casters + return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008)); + } + + public _startAttenuatingAutoScroll (deltaMove: Vec3, initialVelocity: Vec3) { + let time = this._calculateAutoScrollTimeByInitalSpeed(initialVelocity.mag()); + + let targetDelta = deltaMove.normalize(); + const contentSize = this._content!.getContentSize(); + const scrollviewSize = this.node.getContentSize(); + + const totalMoveWidth = (contentSize.width - scrollviewSize.width); + const totalMoveHeight = (contentSize.height - scrollviewSize.height); + + const attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth); + const attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight); + + targetDelta = new Vec3( + targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, + targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake), + 0); + + const originalMoveLength = deltaMove.mag(); + let factor = targetDelta.mag() / originalMoveLength; + targetDelta = targetDelta.add(deltaMove); + + if (this.brake > 0 && factor > 7) { + factor = Math.sqrt(factor); + targetDelta = deltaMove.mul(factor).add(deltaMove); + } + + if (this.brake > 0 && factor > 3) { + factor = 3; + time = time * factor; + } + + if (this.brake === 0 && factor > 1) { + time = time * factor; + } + + this._startAutoScroll(targetDelta, time, true); + } + + public _calculateAutoScrollTimeByInitalSpeed (initalSpeed) { + return Math.sqrt(Math.sqrt(initalSpeed / 5)); + } + + public _startAutoScroll (deltaMove: Vec3, timeInSecond: number, attenuated: boolean = false) { + const adjustedDeltaMove = this._flattenVectorByDirection(deltaMove); + + this._autoScrolling = true; + this._autoScrollTargetDelta = adjustedDeltaMove; + this._autoScrollAttenuate = attenuated; + vec3.copy(this._autoScrollStartPosition, this.getContentPosition()); + this._autoScrollTotalTime = timeInSecond; + this._autoScrollAccumulatedTime = 0; + this._autoScrollBraking = false; + this._isScrollEndedWithThresholdEventFired = false; + this._autoScrollBrakingStartPosition = new Vec3(); + + const currentOutOfBoundary = this._getHowMuchOutOfBoundary(); + if (!currentOutOfBoundary.fuzzyEquals(ZERO, EPSILON)) { + this._autoScrollCurrentlyOutOfBoundary = true; + } + } + + public _calculateTouchMoveVelocity () { + let totalTime = 0; + totalTime = this._touchMoveTimeDeltas.reduce((a, b) => { + return a + b; + }, totalTime); + + if (totalTime <= 0 || totalTime >= 0.5) { + return new Vec3(); + } + + let totalMovement = new Vec3(); + totalMovement = this._touchMoveDisplacements.reduce((a, b) => { + return a.add(b); + }, totalMovement); + + return new Vec3(totalMovement.x * (1 - this.brake) / totalTime, + totalMovement.y * (1 - this.brake) / totalTime, 0); + } + + public _flattenVectorByDirection (vector: Vec3) { + const result = vector; + result.x = this.horizontal ? result.x : 0; + result.y = this.vertical ? result.y : 0; + return result; + } + + public _moveContent (deltaMove: Vec3, canStartBounceBack?: boolean) { + const adjustedMove = this._flattenVectorByDirection(deltaMove); + this.getContentPosition().add(adjustedMove, _tempPos); + + this.setContentPosition(_tempPos); + + const outOfBoundary = this._getHowMuchOutOfBoundary(); + this._updateScrollBar(outOfBoundary); + + if (this.elastic && canStartBounceBack) { + this._startBounceBackIfNeeded(); + } + } + + public _getContentLeftBoundary () { + const contentPos = this.getContentPosition(); + return contentPos.x - this._content!.getAnchorPoint().x * this._content!.getContentSize().width; + } + + public _getContentRightBoundary () { + const contentSize = this._content!.getContentSize(); + return this._getContentLeftBoundary() + contentSize.width; + } + + public _getContentTopBoundary () { + const contentSize = this._content!.getContentSize(); + return this._getContentBottomBoundary() + contentSize.height; + } + + public _getContentBottomBoundary () { + const contentPos = this.getContentPosition(); + return contentPos.y - this._content!.getAnchorPoint().y * this._content!.getContentSize().height; + } + + public _getHowMuchOutOfBoundary (addition?: Vec3) { + addition = addition || new Vec3(); + if (addition.fuzzyEquals(ZERO, EPSILON) && !this._outOfBoundaryAmountDirty) { + return this._outOfBoundaryAmount; + } + + let outOfBoundaryAmount = new Vec3(); + if (this._getContentLeftBoundary() + addition.x > this._leftBoundary) { + outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x); + } else if (this._getContentRightBoundary() + addition.x < this._rightBoundary) { + outOfBoundaryAmount.x = this._rightBoundary - (this._getContentRightBoundary() + addition.x); + } + + if (this._getContentTopBoundary() + addition.y < this._topBoundary) { + outOfBoundaryAmount.y = this._topBoundary - (this._getContentTopBoundary() + addition.y); + } else if (this._getContentBottomBoundary() + addition.y > this._bottomBoundary) { + outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y); + } + + if (addition.fuzzyEquals(ZERO, EPSILON)) { + this._outOfBoundaryAmount = outOfBoundaryAmount; + this._outOfBoundaryAmountDirty = false; + } + + outOfBoundaryAmount = this._clampDelta(outOfBoundaryAmount); + return outOfBoundaryAmount; + } + + public _updateScrollBar (outOfBoundary: Vec3) { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onScroll(outOfBoundary); + } + + if (this.verticalScrollBar) { + this.verticalScrollBar.onScroll(outOfBoundary); + } + } + + public _onScrollBarTouchBegan () { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onTouchBegan(); + } + + if (this.verticalScrollBar) { + this.verticalScrollBar.onTouchBegan(); + } + } + + public _onScrollBarTouchEnded () { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onTouchEnded(); + } + + if (this.verticalScrollBar) { + this.verticalScrollBar.onTouchEnded(); + } + } + + public _dispatchEvent (event) { + if (event === 'scroll-ended') { + this._scrollEventEmitMask = 0; + + } else if (event === 'scroll-to-top' + || event === 'scroll-to-bottom' + || event === 'scroll-to-left' + || event === 'scroll-to-right') { + + const flag = (1 << eventMap[event]); + if (this._scrollEventEmitMask & flag) { + return; + } else { + this._scrollEventEmitMask |= flag; + } + } + + cc.Component.EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]); + this.node.emit(event, this); + } + + public _adjustContentOutOfBoundary () { + if (!this._content){ + return; + } + + this._outOfBoundaryAmountDirty = true; + if (this._isOutOfBoundary()) { + const outOfBoundary = this._getHowMuchOutOfBoundary(new Vec3()); + const newPosition = this.getContentPosition().add(outOfBoundary); + if (this._content) { + this._content.setPosition(newPosition); + // this._updateScrollBar(0); + this._updateScrollBar(ZERO); + } + } + } + + public start () { + this._calculateBoundary(); + // Because widget component will adjust content position and scrollview position is correct after visit + // So this event could make sure the content is on the correct position after loading. + if (this._content) { + cc.director.once(cc.Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); + } + } + + public _hideScrollbar () { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.hide(); + } + + if (this.verticalScrollBar) { + this.verticalScrollBar.hide(); + } + } + + public _showScrollbar () { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.show(); + } + + if (this.verticalScrollBar) { + this.verticalScrollBar.show(); + } + } + + public onDisable () { + if (!CC_EDITOR) { + this._unregisterEvent(); + if (this.content) { + this.content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + this.content.off(NodeEvent.SCALE_PART, this._calculateBoundary, this); + if (this.view!) { + this.view!.off(NodeEvent.POSITION_PART, this._calculateBoundary, this); + this.view!.off(NodeEvent.SCALE_PART, this._calculateBoundary, this); + this.view!.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + } + } + } + this._hideScrollbar(); + this.stopAutoScroll(); + } + + public onEnable () { + if (!CC_EDITOR) { + this._registerEvent(); + if (this.content) { + this.content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + this.content.on(NodeEvent.SCALE_PART, this._calculateBoundary, this); + if (this.view!) { + this.view!.on(NodeEvent.POSITION_PART, this._calculateBoundary, this); + this.view!.on(NodeEvent.SCALE_PART, this._calculateBoundary, this); + this.view!.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + } + } + } + this._showScrollbar(); + } + + public update (dt) { + if (this._autoScrolling) { + this._processAutoScrolling(dt); + } + } + + // This is for Scrollview as children of a Button + private _stopPropagationIfTargetIsMe (event?: EventTouch) { + if (event && event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) { + event.propagationStopped = true; + } + } + + // touch event handler + private _onTouchBegan (event?: EventTouch, captureListeners?: any) { + if (!this.enabledInHierarchy || !this._content) { return; } + if (this._hasNestedViewGroup(event, captureListeners)) { return; } + + // let touch = event.touch; + if (this._content) { + this._handlePressLogic(); + } + this._touchMoved = false; + this._stopPropagationIfTargetIsMe(event); + } + + private _onTouchMoved (event?: EventTouch, captureListeners?: any) { + if (!this.enabledInHierarchy || !this._content) { return; } + if (this._hasNestedViewGroup(event, captureListeners)) { return; } + + if (!event || !event.touch){ + return; + } + + const touch = event.touch; + if (this._content) { + this._handleMoveLogic(touch); + } + // Do not prevent touch events in inner nodes + if (!this.cancelInnerEvents) { + return; + } + + const deltaMove = touch.getLocation().sub(touch.getStartLocation()); + // FIXME: touch move delta should be calculated by DPI. + if (deltaMove.mag() > 7) { + if (!this._touchMoved && event.target !== this.node) { + // Simulate touch cancel for target node + const cancelEvent = new EventTouch(event.getTouches(), event.bubbles); + cancelEvent.type = NodeEvent.TOUCH_CANCEL; + cancelEvent.touch = event.touch; + // cancelEvent.simulate = true; + (event.target as Node)!.dispatchEvent(cancelEvent); + this._touchMoved = true; + } + } + this._stopPropagationIfTargetIsMe(event); + } + + private _onTouchEnded (event?: EventTouch, captureListeners?: any) { + if (!this.enabledInHierarchy || !this._content || !event) { return; } + if (this._hasNestedViewGroup(event, captureListeners)) { return; } + + this._dispatchEvent('touch-up'); + + const touch = event.touch; + if (this._content) { + this._handleReleaseLogic(touch); + } + if (this._touchMoved) { + event.propagationStopped = true; + } else { + this._stopPropagationIfTargetIsMe(event); + } + } + + private _onTouchCancelled (event?: EventTouch, captureListeners?: any) { + if (!this.enabledInHierarchy || !this._content) { return; } + if (this._hasNestedViewGroup(event, captureListeners)) { return; } + + // Filte touch cancel event send from self + if (event && !event.simulate) { + const touch = event.touch; + if (this._content) { + this._handleReleaseLogic(touch); + } + } + this._stopPropagationIfTargetIsMe(event); + } + + private _processDeltaMove (deltaMove: Vec3) { + this._scrollChildren(deltaMove); + this._gatherTouchMove(deltaMove); + } + + private _handleMoveLogic (touch: Touch) { + const delta = touch.getDelta(); + vec3.set(this._deltaPos, delta.x, delta.y, 0); + this._processDeltaMove(this._deltaPos); + } + + private _scrollChildren (deltaMove: Vec3) { + deltaMove = this._clampDelta(deltaMove); + + let realMove = deltaMove; + let outOfBoundary; + if (this.elastic) { + outOfBoundary = this._getHowMuchOutOfBoundary(); + realMove.x *= (outOfBoundary.x === 0 ? 1 : 0.5); + realMove.y *= (outOfBoundary.y === 0 ? 1 : 0.5); + } + + if (!this.elastic) { + outOfBoundary = this._getHowMuchOutOfBoundary(realMove); + realMove = realMove.add(outOfBoundary); + } + + let scrollEventType = ''; + const pos = new Vec3(); + this._content!.getPosition(pos); + + if (realMove.y > 0) { // up + const icBottomPos = pos.y - this._content!.anchorY * this._content!.height; + + if (icBottomPos + realMove.y > this._bottomBoundary) { + scrollEventType = 'scroll-to-bottom'; + } + } + else if (realMove.y < 0) { // down + const icTopPos = pos.y - this._content!.anchorY * this._content!.height + this._content!.height; + + if (icTopPos + realMove.y <= this._topBoundary) { + scrollEventType = 'scroll-to-top'; + } + } + else if (realMove.x < 0) { // left + const icRightPos = pos.x - this._content!.anchorX * this._content!.width + this._content!.width; + if (icRightPos + realMove.x <= this._rightBoundary) { + scrollEventType = 'scroll-to-right'; + } + } + else if (realMove.x > 0) { // right + const icLeftPos = pos.x - this._content!.anchorX * this._content!.width; + if (icLeftPos + realMove.x >= this._leftBoundary) { + scrollEventType = 'scroll-to-left'; + } + } + + this._moveContent(realMove, false); + + if (realMove.x !== 0 || realMove.y !== 0) { + if (!this._scrolling) { + this._scrolling = true; + this._dispatchEvent('scroll-began'); + } + this._dispatchEvent('scrolling'); + } + + if (scrollEventType.length > 0) { + this._dispatchEvent(scrollEventType); + } + + } + + private _handlePressLogic () { + if (this._autoScrolling) { + this._dispatchEvent('scroll-ended'); + } + this._autoScrolling = false; + this._isBouncing = false; + + this._touchMovePreviousTimestamp = getTimeInMilliseconds(); + this._touchMoveDisplacements.length = 0; + this._touchMoveTimeDeltas.length = 0; + + this._onScrollBarTouchBegan(); + } + + private _clampDelta (delta: Vec3) { + const contentSize = this._content!.getContentSize(); + const scrollViewSize = this.node.getContentSize(); + if (contentSize.width < scrollViewSize.width) { + delta.x = 0; + } + if (contentSize.height < scrollViewSize.height) { + delta.y = 0; + } + + return delta; + } + + private _gatherTouchMove (delta: Vec3) { + delta = this._clampDelta(delta); + + while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) { + this._touchMoveDisplacements.shift(); + this._touchMoveTimeDeltas.shift(); + } + + this._touchMoveDisplacements.push(delta); + + const timeStamp = getTimeInMilliseconds(); + this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000); + this._touchMovePreviousTimestamp = timeStamp; + } + + private _startBounceBackIfNeeded () { + if (!this.elastic) { + return false; + } + + let bounceBackAmount = this._getHowMuchOutOfBoundary(); + bounceBackAmount = this._clampDelta(bounceBackAmount); + + if (bounceBackAmount.fuzzyEquals(_tempPos, EPSILON)) { + return false; + } + + const bounceBackTime = Math.max(this.bounceDuration, 0); + this._startAutoScroll(bounceBackAmount, bounceBackTime, true); + + if (!this._isBouncing) { + if (bounceBackAmount.y > 0) { this._dispatchEvent('bounce-top'); } + if (bounceBackAmount.y < 0) { this._dispatchEvent('bounce-bottom'); } + if (bounceBackAmount.x > 0) { this._dispatchEvent('bounce-right'); } + if (bounceBackAmount.x < 0) { this._dispatchEvent('bounce-left'); } + this._isBouncing = true; + } + + return true; + } + + private _processInertiaScroll () { + const bounceBackStarted = this._startBounceBackIfNeeded(); + if (!bounceBackStarted && this.inertia) { + const touchMoveVelocity = this._calculateTouchMoveVelocity(); + if (!touchMoveVelocity.fuzzyEquals(_tempPos, EPSILON) && this.brake < 1) { + this._startInertiaScroll(touchMoveVelocity); + } + } + + this._onScrollBarTouchEnded(); + } + + private _handleReleaseLogic (touch) { + const delta = touch.getDelta(); + vec3.set(this._deltaPos, delta.x, delta.y, 0); + this._gatherTouchMove(this._deltaPos); + this._processInertiaScroll(); + + if (this._scrolling) { + this._scrolling = false; + if (!this._autoScrolling) { + this._dispatchEvent('scroll-ended'); + } + } + } + + private _isOutOfBoundary () { + const outOfBoundary = this._getHowMuchOutOfBoundary(); + return !outOfBoundary.fuzzyEquals(ZERO, EPSILON); + } + + private _isNecessaryAutoScrollBrake () { + if (this._autoScrollBraking) { + return true; + } + + if (this._isOutOfBoundary()) { + if (!this._autoScrollCurrentlyOutOfBoundary) { + this._autoScrollCurrentlyOutOfBoundary = true; + this._autoScrollBraking = true; + this._autoScrollBrakingStartPosition = this.getContentPosition(); + return true; + } + + } else { + this._autoScrollCurrentlyOutOfBoundary = false; + } + + return false; + } + + private _processAutoScrolling (dt) { + const isAutoScrollBrake = this._isNecessaryAutoScrollBrake(); + const brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1; + this._autoScrollAccumulatedTime += dt * (1 / brakingFactor); + + let percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime); + if (this._autoScrollAttenuate) { + percentage = quintEaseOut(percentage); + } + + let newPosition = this._autoScrollStartPosition.add(this._autoScrollTargetDelta.mul(percentage)); + let reachedEnd = Math.abs(percentage - 1) <= EPSILON; + + const fireEvent = Math.abs(percentage - 1) <= this.getScrollEndedEventTiming(); + if (fireEvent && !this._isScrollEndedWithThresholdEventFired) { + this._dispatchEvent('scroll-ended-with-threshold'); + this._isScrollEndedWithThresholdEventFired = true; + } + + if (this.elastic) { + let brakeOffsetPosition = newPosition.sub(this._autoScrollBrakingStartPosition); + if (isAutoScrollBrake) { + brakeOffsetPosition = brakeOffsetPosition.mul(brakingFactor); + } + newPosition = this._autoScrollBrakingStartPosition.add(brakeOffsetPosition); + } else { + const moveDelta = newPosition.sub(this.getContentPosition()); + const outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta); + if (!outOfBoundary.fuzzyEquals(ZERO, EPSILON)) { + newPosition = newPosition.add(outOfBoundary); + reachedEnd = true; + } + } + + if (reachedEnd) { + this._autoScrolling = false; + } + + const deltaMove = newPosition.sub(this.getContentPosition()); + this._moveContent(this._clampDelta(deltaMove), reachedEnd); + this._dispatchEvent('scrolling'); + + if (!this._autoScrolling) { + this._isBouncing = false; + this._scrolling = false; + this._dispatchEvent('scroll-ended'); + } + } + + private _checkMouseWheel (dt: number) { + const currentOutOfBoundary = this._getHowMuchOutOfBoundary(); + const maxElapsedTime = 0.1; if (!currentOutOfBoundary.fuzzyEquals(ZERO, EPSILON)) { this._processInertiaScroll(); @@ -826,7 +1502,7 @@ export class ScrollViewComponent extends ViewGroupComponent { this._mouseWheelEventElapsedTime += dt; - //mouse wheel event is ended + // mouse wheel event is ended if (this._mouseWheelEventElapsedTime > maxElapsedTime) { this._onScrollBarTouchEnded(); this.unschedule(this._checkMouseWheel); @@ -834,23 +1510,23 @@ export class ScrollViewComponent extends ViewGroupComponent { } } - _calculateMovePercentDelta(options) { + private _calculateMovePercentDelta (options) { let anchor = options.anchor; - let applyToHorizontal = options.applyToHorizontal; - let applyToVertical = options.applyToVertical; + const applyToHorizontal = options.applyToHorizontal; + const applyToVertical = options.applyToVertical; this._calculateBoundary(); anchor = anchor.clampf(new Vec2(0, 0), new Vec2(1, 1)); - let scrollSize = this.node.getContentSize(); - let contentSize = this._content!.getContentSize(); + const scrollSize = this.node.getContentSize(); + const contentSize = this._content!.getContentSize(); let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; leftDeta = -leftDeta; - let moveDelta = new Vec3(); + const moveDelta = new Vec3(); let totalScrollDelta = 0; if (applyToHorizontal) { totalScrollDelta = contentSize.width - scrollSize.width; @@ -865,12 +1541,12 @@ export class ScrollViewComponent extends ViewGroupComponent { return moveDelta; } - _moveContentToTopLeft(scrollViewSize: Size) { - let contentSize = this._content!.getContentSize(); + private _moveContentToTopLeft (scrollViewSize: Size) { + const contentSize = this._content!.getContentSize(); let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; - let moveDelta = new Vec3(); + const moveDelta = new Vec3(); let totalScrollDelta = 0; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; @@ -906,682 +1582,10 @@ export class ScrollViewComponent extends ViewGroupComponent { this._moveContent(moveDelta); this._adjustContentOutOfBoundary(); } - - _calculateBoundary() { - if (this.content) { - //refresh content size - let layout = this.content.getComponent(LayoutComponent); - if (layout && layout.enabledInHierarchy) { - layout.updateLayout(); - } - let viewSize = this.view!.getContentSize(); - - let anchorX = viewSize.width * this.view!.anchorX; - let anchorY = viewSize.height * this.view!.anchorY; - - this._leftBoundary = -anchorX; - this._bottomBoundary = -anchorY; - - this._rightBoundary = this._leftBoundary + viewSize.width; - this._topBoundary = this._bottomBoundary + viewSize.height; - - this._moveContentToTopLeft(viewSize); - } - - } - - //this is for nested scrollview - _hasNestedViewGroup(event?: EventTouch, captureListeners?: any) { - if (!event || event.eventPhase !== cc.Event.CAPTURING_PHASE) return; - - if (captureListeners) { - //captureListeners are arranged from child to parent - for (let i = 0; i < captureListeners.length; ++i) { - let item = captureListeners[i] as Node; - - if (this.node === item) { - if (event.target && (event.target as Node).getComponent(ViewGroupComponent)) { - return true; - } - return false; - } - - if (item.getComponent(ViewGroupComponent)) { - return true; - } - } - } - return false; - } - - //This is for Scrollview as children of a Button - _stopPropagationIfTargetIsMe(event?: EventTouch) { - if (event && event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) { - event.propagationStopped = true; - } - } - - // touch event handler - _onTouchBegan(event?: EventTouch, captureListeners?: any) { - if (!this.enabledInHierarchy||!this._content) return; - if (this._hasNestedViewGroup(event, captureListeners)) return; - - // let touch = event.touch; - if (this._content) { - this._handlePressLogic(); - } - this._touchMoved = false; - this._stopPropagationIfTargetIsMe(event); - } - - _onTouchMoved(event?: EventTouch, captureListeners?: any) { - if (!this.enabledInHierarchy || !this._content) return; - if (this._hasNestedViewGroup(event, captureListeners)) return; - - if (!event || !event.touch){ - return; - } - - let touch = event.touch; - if (this._content) { - this._handleMoveLogic(touch); - } - // Do not prevent touch events in inner nodes - if (!this.cancelInnerEvents) { - return; - } - - let deltaMove = touch.getLocation().sub(touch.getStartLocation()); - //FIXME: touch move delta should be calculated by DPI. - if (deltaMove.mag() > 7) { - if (!this._touchMoved && event.target !== this.node) { - // Simulate touch cancel for target node - let cancelEvent = new EventTouch(event.getTouches(), event.bubbles); - cancelEvent.type = NodeEvent.TOUCH_CANCEL; - cancelEvent.touch = event.touch; - // cancelEvent.simulate = true; - (event.target as Node)!.dispatchEvent(cancelEvent); - this._touchMoved = true; - } - } - this._stopPropagationIfTargetIsMe(event); - } - - _onTouchEnded(event?: EventTouch, captureListeners?: any) { - if (!this.enabledInHierarchy || !this._content || !event) return; - if (this._hasNestedViewGroup(event, captureListeners)) return; - - this._dispatchEvent('touch-up'); - - let touch = event.touch; - if (this._content) { - this._handleReleaseLogic(touch); - } - if (this._touchMoved) { - event.propagationStopped = true; - } else { - this._stopPropagationIfTargetIsMe(event); - } - } - - _onTouchCancelled(event?: EventTouch, captureListeners?: any) { - if (!this.enabledInHierarchy || !this._content) return; - if (this._hasNestedViewGroup(event, captureListeners)) return; - - // Filte touch cancel event send from self - if (event && !event['simulate']) { - let touch = event.touch; - if (this._content) { - this._handleReleaseLogic(touch); - } - } - this._stopPropagationIfTargetIsMe(event); - } - - _processDeltaMove(deltaMove: Vec3) { - this._scrollChildren(deltaMove); - this._gatherTouchMove(deltaMove); - } - - _handleMoveLogic(touch: Touch) { - const delta = touch.getDelta(); - vec3.set(this._deltaPos, delta.x, delta.y, 0); - this._processDeltaMove(this._deltaPos); - } - - _scrollChildren(deltaMove: Vec3) { - deltaMove = this._clampDelta(deltaMove); - - let realMove = deltaMove; - let outOfBoundary; - if (this.elastic) { - outOfBoundary = this._getHowMuchOutOfBoundary(); - realMove.x *= (outOfBoundary.x === 0 ? 1 : 0.5); - realMove.y *= (outOfBoundary.y === 0 ? 1 : 0.5); - } - - if (!this.elastic) { - outOfBoundary = this._getHowMuchOutOfBoundary(realMove); - realMove = realMove.add(outOfBoundary); - } - - let scrollEventType = ''; - let pos = new Vec3(); - this._content!.getPosition(pos); - - if (realMove.y > 0) { //up - let icBottomPos = pos.y - this._content!.anchorY * this._content!.height; - - if (icBottomPos + realMove.y > this._bottomBoundary) { - scrollEventType = 'scroll-to-bottom'; - } - } - else if (realMove.y < 0) { //down - let icTopPos = pos.y - this._content!.anchorY * this._content!.height + this._content!.height; - - if (icTopPos + realMove.y <= this._topBoundary) { - scrollEventType = 'scroll-to-top'; - } - } - else if (realMove.x < 0) { //left - let icRightPos = pos.x - this._content!.anchorX * this._content!.width + this._content!.width; - if (icRightPos + realMove.x <= this._rightBoundary) { - scrollEventType = 'scroll-to-right'; - } - } - else if (realMove.x > 0) { //right - let icLeftPos = pos.x - this._content!.anchorX * this._content!.width; - if (icLeftPos + realMove.x >= this._leftBoundary) { - scrollEventType = 'scroll-to-left'; - } - } - - this._moveContent(realMove, false); - - if (realMove.x !== 0 || realMove.y !== 0) { - if (!this._scrolling) { - this._scrolling = true; - this._dispatchEvent('scroll-began'); - } - this._dispatchEvent('scrolling'); - } - - if (scrollEventType.length > 0) { - this._dispatchEvent(scrollEventType); - } - - } - - _handlePressLogic() { - if (this._autoScrolling) { - this._dispatchEvent('scroll-ended'); - } - this._autoScrolling = false; - this._isBouncing = false; - - this._touchMovePreviousTimestamp = getTimeInMilliseconds(); - this._touchMoveDisplacements.length = 0; - this._touchMoveTimeDeltas.length = 0; - - this._onScrollBarTouchBegan(); - } - - _clampDelta(delta: Vec3) { - let contentSize = this._content!.getContentSize(); - let scrollViewSize = this.node.getContentSize(); - if (contentSize.width < scrollViewSize.width) { - delta.x = 0; - } - if (contentSize.height < scrollViewSize.height) { - delta.y = 0; - } - - return delta; - } - - _gatherTouchMove(delta: Vec3) { - delta = this._clampDelta(delta); - - while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) { - this._touchMoveDisplacements.shift(); - this._touchMoveTimeDeltas.shift(); - } - - this._touchMoveDisplacements.push(delta); - - let timeStamp = getTimeInMilliseconds(); - this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000); - this._touchMovePreviousTimestamp = timeStamp; - } - - _startBounceBackIfNeeded() { - if (!this.elastic) { - return false; - } - - let bounceBackAmount = this._getHowMuchOutOfBoundary(); - bounceBackAmount = this._clampDelta(bounceBackAmount); - - if (bounceBackAmount.fuzzyEquals(_tempPos, EPSILON)) { - return false; - } - - let bounceBackTime = Math.max(this.bounceDuration, 0); - this._startAutoScroll(bounceBackAmount, bounceBackTime, true); - - if (!this._isBouncing) { - if (bounceBackAmount.y > 0) this._dispatchEvent('bounce-top'); - if (bounceBackAmount.y < 0) this._dispatchEvent('bounce-bottom'); - if (bounceBackAmount.x > 0) this._dispatchEvent('bounce-right'); - if (bounceBackAmount.x < 0) this._dispatchEvent('bounce-left'); - this._isBouncing = true; - } - - return true; - } - - _processInertiaScroll() { - let bounceBackStarted = this._startBounceBackIfNeeded(); - if (!bounceBackStarted && this.inertia) { - let touchMoveVelocity = this._calculateTouchMoveVelocity(); - if (!touchMoveVelocity.fuzzyEquals(_tempPos, EPSILON) && this.brake < 1) { - this._startInertiaScroll(touchMoveVelocity); - } - } - - this._onScrollBarTouchEnded(); - } - - _handleReleaseLogic(touch) { - let delta = touch.getDelta(); - vec3.set(this._deltaPos, delta.x, delta.y, 0); - this._gatherTouchMove(this._deltaPos); - this._processInertiaScroll(); - - if (this._scrolling) { - this._scrolling = false; - if (!this._autoScrolling) { - this._dispatchEvent('scroll-ended'); - } - } - } - - _isOutOfBoundary() { - let outOfBoundary = this._getHowMuchOutOfBoundary(); - return !outOfBoundary.fuzzyEquals(ZERO, EPSILON); - } - - _isNecessaryAutoScrollBrake() { - if (this._autoScrollBraking) { - return true; - } - - if (this._isOutOfBoundary()) { - if (!this._autoScrollCurrentlyOutOfBoundary) { - this._autoScrollCurrentlyOutOfBoundary = true; - this._autoScrollBraking = true; - this._autoScrollBrakingStartPosition = this.getContentPosition(); - return true; - } - - } else { - this._autoScrollCurrentlyOutOfBoundary = false; - } - - return false; - } - - getScrollEndedEventTiming() { - return EPSILON; - } - - _processAutoScrolling(dt) { - let isAutoScrollBrake = this._isNecessaryAutoScrollBrake(); - let brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1; - this._autoScrollAccumulatedTime += dt * (1 / brakingFactor); - - let percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime); - if (this._autoScrollAttenuate) { - percentage = quintEaseOut(percentage); - } - - let newPosition = this._autoScrollStartPosition.add(this._autoScrollTargetDelta.mul(percentage)); - let reachedEnd = Math.abs(percentage - 1) <= EPSILON; - - let fireEvent = Math.abs(percentage - 1) <= this.getScrollEndedEventTiming(); - if (fireEvent && !this._isScrollEndedWithThresholdEventFired) { - this._dispatchEvent('scroll-ended-with-threshold'); - this._isScrollEndedWithThresholdEventFired = true; - } - - if (this.elastic) { - let brakeOffsetPosition = newPosition.sub(this._autoScrollBrakingStartPosition); - if (isAutoScrollBrake) { - brakeOffsetPosition = brakeOffsetPosition.mul(brakingFactor); - } - newPosition = this._autoScrollBrakingStartPosition.add(brakeOffsetPosition); - } else { - let moveDelta = newPosition.sub(this.getContentPosition()); - let outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta); - if (!outOfBoundary.fuzzyEquals(ZERO, EPSILON)) { - newPosition = newPosition.add(outOfBoundary); - reachedEnd = true; - } - } - - if (reachedEnd) { - this._autoScrolling = false; - } - - let deltaMove = newPosition.sub(this.getContentPosition()); - this._moveContent(this._clampDelta(deltaMove), reachedEnd); - this._dispatchEvent('scrolling'); - - if (!this._autoScrolling) { - this._isBouncing = false; - this._scrolling = false; - this._dispatchEvent('scroll-ended'); - } - } - - _startInertiaScroll(touchMoveVelocity: Vec3) { - let inertiaTotalMovement = touchMoveVelocity.mul(MOVEMENT_FACTOR); - this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity); - } - - _calculateAttenuatedFactor(distance: number) { - if (this.brake <= 0) { - return (1 - this.brake); - } - - //attenuate formula from: http://learnopengl.com/#!Lighting/Light-casters - return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008)); - } - - _startAttenuatingAutoScroll(deltaMove: Vec3, initialVelocity: Vec3) { - let time = this._calculateAutoScrollTimeByInitalSpeed(initialVelocity.mag()); - - let targetDelta = deltaMove.normalize(); - let contentSize = this._content!.getContentSize(); - let scrollviewSize = this.node.getContentSize(); - - let totalMoveWidth = (contentSize.width - scrollviewSize.width); - let totalMoveHeight = (contentSize.height - scrollviewSize.height); - - let attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth); - let attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight); - - targetDelta = new Vec3(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake), 0); - - let originalMoveLength = deltaMove.mag(); - let factor = targetDelta.mag() / originalMoveLength; - targetDelta = targetDelta.add(deltaMove); - - if (this.brake > 0 && factor > 7) { - factor = Math.sqrt(factor); - targetDelta = deltaMove.mul(factor).add(deltaMove); - } - - if (this.brake > 0 && factor > 3) { - factor = 3; - time = time * factor; - } - - if (this.brake === 0 && factor > 1) { - time = time * factor; - } - - this._startAutoScroll(targetDelta, time, true); - } - - _calculateAutoScrollTimeByInitalSpeed(initalSpeed) { - return Math.sqrt(Math.sqrt(initalSpeed / 5)); - } - - _startAutoScroll(deltaMove: Vec3, timeInSecond: number, attenuated: boolean = false) { - let adjustedDeltaMove = this._flattenVectorByDirection(deltaMove); - - this._autoScrolling = true; - this._autoScrollTargetDelta = adjustedDeltaMove; - this._autoScrollAttenuate = attenuated; - vec3.copy(this._autoScrollStartPosition, this.getContentPosition()); - this._autoScrollTotalTime = timeInSecond; - this._autoScrollAccumulatedTime = 0; - this._autoScrollBraking = false; - this._isScrollEndedWithThresholdEventFired = false; - this._autoScrollBrakingStartPosition = new Vec3(); - - let currentOutOfBoundary = this._getHowMuchOutOfBoundary(); - if (!currentOutOfBoundary.fuzzyEquals(ZERO, EPSILON)) { - this._autoScrollCurrentlyOutOfBoundary = true; - } - } - - _calculateTouchMoveVelocity() { - let totalTime = 0; - totalTime = this._touchMoveTimeDeltas.reduce(function (a, b) { - return a + b; - }, totalTime); - - if (totalTime <= 0 || totalTime >= 0.5) { - return new Vec3(); - } - - let totalMovement = new Vec3(); - totalMovement = this._touchMoveDisplacements.reduce(function (a, b) { - return a.add(b); - }, totalMovement); - - return new Vec3(totalMovement.x * (1 - this.brake) / totalTime, - totalMovement.y * (1 - this.brake) / totalTime, 0); - } - - _flattenVectorByDirection(vector: Vec3) { - let result = vector; - result.x = this.horizontal ? result.x : 0; - result.y = this.vertical ? result.y : 0; - return result; - } - - _moveContent(deltaMove: Vec3, canStartBounceBack?: boolean) { - let adjustedMove = this._flattenVectorByDirection(deltaMove); - this.getContentPosition().add(adjustedMove, _tempPos); - - this.setContentPosition(_tempPos); - - let outOfBoundary = this._getHowMuchOutOfBoundary(); - this._updateScrollBar(outOfBoundary); - - if (this.elastic && canStartBounceBack) { - this._startBounceBackIfNeeded(); - } - } - - _getContentLeftBoundary() { - let contentPos = this.getContentPosition(); - return contentPos.x - this._content!.getAnchorPoint().x * this._content!.getContentSize().width; - } - - _getContentRightBoundary() { - let contentSize = this._content!.getContentSize(); - return this._getContentLeftBoundary() + contentSize.width; - } - - _getContentTopBoundary() { - let contentSize = this._content!.getContentSize(); - return this._getContentBottomBoundary() + contentSize.height; - } - - _getContentBottomBoundary() { - let contentPos = this.getContentPosition(); - return contentPos.y - this._content!.getAnchorPoint().y * this._content!.getContentSize().height; - } - - _getHowMuchOutOfBoundary(addition?: Vec3) { - addition = addition || new Vec3(); - if (addition.fuzzyEquals(ZERO, EPSILON) && !this._outOfBoundaryAmountDirty) { - return this._outOfBoundaryAmount; - } - - let outOfBoundaryAmount = new Vec3(); - if (this._getContentLeftBoundary() + addition.x > this._leftBoundary) { - outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x); - } else if (this._getContentRightBoundary() + addition.x < this._rightBoundary) { - outOfBoundaryAmount.x = this._rightBoundary - (this._getContentRightBoundary() + addition.x); - } - - if (this._getContentTopBoundary() + addition.y < this._topBoundary) { - outOfBoundaryAmount.y = this._topBoundary - (this._getContentTopBoundary() + addition.y); - } else if (this._getContentBottomBoundary() + addition.y > this._bottomBoundary) { - outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y); - } - - if (addition.fuzzyEquals(ZERO, EPSILON)) { - this._outOfBoundaryAmount = outOfBoundaryAmount; - this._outOfBoundaryAmountDirty = false; - } - - outOfBoundaryAmount = this._clampDelta(outOfBoundaryAmount); - return outOfBoundaryAmount; - } - - _updateScrollBar(outOfBoundary: Vec3) { - if (this._horizontalScrollBar) { - this._horizontalScrollBar.onScroll(outOfBoundary); - } - - if (this.verticalScrollBar) { - this.verticalScrollBar.onScroll(outOfBoundary); - } - } - - _onScrollBarTouchBegan() { - if (this._horizontalScrollBar) { - this._horizontalScrollBar.onTouchBegan(); - } - - if (this.verticalScrollBar) { - this.verticalScrollBar.onTouchBegan(); - } - } - - _onScrollBarTouchEnded() { - if (this._horizontalScrollBar) { - this._horizontalScrollBar.onTouchEnded(); - } - - if (this.verticalScrollBar) { - this.verticalScrollBar.onTouchEnded(); - } - } - - _dispatchEvent(event) { - if (event === 'scroll-ended') { - this._scrollEventEmitMask = 0; - - } else if (event === 'scroll-to-top' - || event === 'scroll-to-bottom' - || event === 'scroll-to-left' - || event === 'scroll-to-right') { - - let flag = (1 << eventMap[event]); - if (this._scrollEventEmitMask & flag) { - return; - } else { - this._scrollEventEmitMask |= flag; - } - } - - cc.Component.EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]); - this.node.emit(event, this); - } - - _adjustContentOutOfBoundary() { - if(!this._content){ - return; - } - - this._outOfBoundaryAmountDirty = true; - if (this._isOutOfBoundary()) { - let outOfBoundary = this._getHowMuchOutOfBoundary(new Vec3()); - let newPosition = this.getContentPosition().add(outOfBoundary); - if (this._content) { - this._content.setPosition(newPosition); - // this._updateScrollBar(0); - this._updateScrollBar(ZERO); - } - } - } - - start() { - this._calculateBoundary(); - //Because widget component will adjust content position and scrollview position is correct after visit - //So this event could make sure the content is on the correct position after loading. - if (this._content) { - cc.director.once(cc.Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); - } - } - - _hideScrollbar() { - if (this._horizontalScrollBar) { - this._horizontalScrollBar.hide(); - } - - if (this.verticalScrollBar) { - this.verticalScrollBar.hide(); - } - } - - _showScrollbar() { - if (this._horizontalScrollBar) { - this._horizontalScrollBar.show(); - } - - if (this.verticalScrollBar) { - this.verticalScrollBar.show(); - } - } - - onDisable() { - if (!CC_EDITOR) { - this._unregisterEvent(); - if (this.content) { - this.content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this.content.off(NodeEvent.SCALE_PART, this._calculateBoundary, this); - if (this.view!) { - this.view!.off(NodeEvent.POSITION_PART, this._calculateBoundary, this); - this.view!.off(NodeEvent.SCALE_PART, this._calculateBoundary, this); - this.view!.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - } - } - } - this._hideScrollbar(); - this.stopAutoScroll(); - } - - onEnable() { - if (!CC_EDITOR) { - this._registerEvent(); - if (this.content) { - this.content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this.content.on(NodeEvent.SCALE_PART, this._calculateBoundary, this); - if (this.view!) { - this.view!.on(NodeEvent.POSITION_PART, this._calculateBoundary, this); - this.view!.on(NodeEvent.SCALE_PART, this._calculateBoundary, this); - this.view!.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - } - } - } - this._showScrollbar(); - } - - update(dt) { - if (this._autoScrolling) { - this._processAutoScrolling(dt); - } - } } +cc.ScrollViewComponent = ScrollViewComponent; + /** * !#en * Note: This event is emitted from the node to which the component belongs. @@ -1693,11 +1697,11 @@ export class ScrollViewComponent extends ViewGroupComponent { */ /** -* !#en -* Note: This event is emitted from the node to which the component belongs. -* !#zh -* 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 -* @event scroll-began -* @param {Event.EventCustom} event -* @param {ScrollView} scrollView - The ScrollView component. -*/ + * !#en + * Note: This event is emitted from the node to which the component belongs. + * !#zh + * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + * @event scroll-began + * @param {Event.EventCustom} event + * @param {ScrollView} scrollView - The ScrollView component. + */ diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts index 1dde53ed94..530b3e37ce 100644 --- a/cocos/3d/ui/components/slider-component.ts +++ b/cocos/3d/ui/components/slider-component.ts @@ -76,11 +76,11 @@ export class SliderComponent extends Component { @property({ type: SpriteComponent, }) - get handle() { + get handle () { return this._handle; } - set handle(value: SpriteComponent | null) { + set handle (value: SpriteComponent | null) { if (this._handle === value) { return; } @@ -99,11 +99,11 @@ export class SliderComponent extends Component { @property({ type: Direction, }) - get direction() { + get direction () { return this._direction; } - set direction(value: number) { + set direction (value: number) { if (this._direction === value) { return; } @@ -119,11 +119,11 @@ export class SliderComponent extends Component { slide: true, range: [0, 1, 0.01], }) - get progress() { + get progress () { return this._progress; } - set progress(value: number) { + set progress (value: number) { if (this._progress === value) { return; } @@ -140,11 +140,11 @@ export class SliderComponent extends Component { @property({ type: ComponentEventHandler, }) - get slideEvents() { + get slideEvents () { return this._slideEvents; } - set slideEvents(value: ComponentEventHandler[]) { + set slideEvents (value: ComponentEventHandler[]) { this._slideEvents = value; } @@ -164,12 +164,12 @@ export class SliderComponent extends Component { private _handlelocalPos = new Vec3(); private _touchPos = new Vec3(); - public __preload() { + public __preload () { this._updateHandlePosition(); } // 注册事件 - public onEnable() { + public onEnable () { this._updateHandlePosition(); this.node.on(EventType.TOUCH_START, this._onTouchBegan, this); @@ -183,7 +183,7 @@ export class SliderComponent extends Component { } } - public onDisable() { + public onDisable () { this.node.off(EventType.TOUCH_START, this._onTouchBegan, this); this.node.off(EventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.off(EventType.TOUCH_END, this._onTouchEnded, this); @@ -195,7 +195,7 @@ export class SliderComponent extends Component { } } - private _onHandleDragStart(event?: EventTouch) { + private _onHandleDragStart (event?: EventTouch) { if (!event || !this._handle || !this._handle.node.uiTransfromComp) { return; } @@ -209,7 +209,7 @@ export class SliderComponent extends Component { event.propagationStopped = true; } - private _onTouchBegan(event?: EventTouch) { + private _onTouchBegan (event?: EventTouch) { if (!this._handle || !event) { return; } @@ -222,7 +222,7 @@ export class SliderComponent extends Component { event.propagationStopped = true; } - private _onTouchMoved(event?: EventTouch) { + private _onTouchMoved (event?: EventTouch) { if (!this._dragging || !event) { return; } @@ -231,7 +231,7 @@ export class SliderComponent extends Component { event.propagationStopped = true; } - private _onTouchEnded(event?: EventTouch) { + private _onTouchEnded (event?: EventTouch) { this._dragging = false; this._touchHandle = false; this._offset = cc.v2(); @@ -241,24 +241,24 @@ export class SliderComponent extends Component { } } - private _onTouchCancelled(event?: EventTouch) { + private _onTouchCancelled (event?: EventTouch) { this._dragging = false; if (event) { event.propagationStopped = true; } } - private _handleSliderLogic(touch) { + private _handleSliderLogic (touch) { this._updateProgress(touch); this._emitSlideEvent(); } - private _emitSlideEvent() { + private _emitSlideEvent () { cc.Component.EventHandler.emitEvents(this.slideEvents, this); this.node.emit('slide', this); } - private _updateProgress(touch: EventTouch) { + private _updateProgress (touch: EventTouch) { if (!this._handle) { return; } const touchPos = (touch as EventTouch).getLocation(); vec3.set(this._touchPos, touchPos.x, touchPos.y, 0); @@ -270,7 +270,7 @@ export class SliderComponent extends Component { } } - private _updateHandlePosition() { + private _updateHandlePosition () { if (!this._handle) { return; } this._handlelocalPos.set(this._handle.node.getPosition()); if (this._direction === Direction.Horizontal) { diff --git a/cocos/3d/ui/components/toggle-component.ts b/cocos/3d/ui/components/toggle-component.ts index 0984400014..7a81171798 100644 --- a/cocos/3d/ui/components/toggle-component.ts +++ b/cocos/3d/ui/components/toggle-component.ts @@ -41,14 +41,6 @@ import { ToggleGroupComponent} from './toggle-group-component'; @menu('UI/Toggle') @executeInEditMode export class ToggleComponent extends ButtonComponent { - @property - public _isChecked: boolean = true; - @property - public _toggleGroup: ToggleGroupComponent | null = null; - @property - public _checkMark: SpriteComponent | null = null; - @property - public _checkEvents: ComponentEventHandler[] = []; /** * !#en When this value is true, the check mark component will be enabled, otherwise @@ -148,6 +140,14 @@ export class ToggleComponent extends ButtonComponent { // } return null; } + @property + public _isChecked: boolean = true; + @property + public _toggleGroup: ToggleGroupComponent | null = null; + @property + public _checkMark: SpriteComponent | null = null; + @property + public _checkEvents: ComponentEventHandler[] = []; public onEnable () { super.onEnable(); @@ -217,13 +217,6 @@ export class ToggleComponent extends ButtonComponent { this._emitToggleEvents(); } - private _emitToggleEvents () { - this.node.emit('toggle', this); - if (this._checkEvents) { - ComponentEventHandler.emitEvents(this._checkEvents, this); - } - } - /** * !#en Make the toggle button checked. * !#zh 使 toggle 按钮处于选中状态 @@ -265,6 +258,13 @@ export class ToggleComponent extends ButtonComponent { this._emitToggleEvents(); } + + private _emitToggleEvents () { + this.node.emit('toggle', this); + if (this._checkEvents) { + ComponentEventHandler.emitEvents(this._checkEvents, this); + } + } } cc.ToggleComponent = ToggleComponent;