From 1d09097b41f193fb316e069d0af6c4466de14ca0 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Sat, 28 Dec 2019 15:57:42 +0800 Subject: [PATCH] migrate editbox from creator (#5992) --- .../components/editbox/edit-box-component.ts | 741 ++++++------ .../components/editbox/edit-box-impl-base.ts | 70 ++ cocos/ui/components/editbox/edit-box-impl.ts | 1071 ++++++++--------- cocos/ui/components/editbox/tabIndexUtil.ts | 39 + 4 files changed, 1002 insertions(+), 919 deletions(-) create mode 100644 cocos/ui/components/editbox/edit-box-impl-base.ts create mode 100644 cocos/ui/components/editbox/tabIndexUtil.ts diff --git a/cocos/ui/components/editbox/edit-box-component.ts b/cocos/ui/components/editbox/edit-box-component.ts index d59ff3bce3..02576c5372 100644 --- a/cocos/ui/components/editbox/edit-box-component.ts +++ b/cocos/ui/components/editbox/edit-box-component.ts @@ -28,33 +28,33 @@ * @category ui */ +import { math } from '../../../core'; import { SpriteFrame } from '../../../core/assets/sprite-frame'; import { Component } from '../../../core/components/component'; import { EventHandler as ComponentEventHandler } from '../../../core/components/component-event-handler'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { Color, Size, Vec3 } from '../../../core/math'; import { EventTouch } from '../../../core/platform'; import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; -import { Color, Size } from '../../../core/math'; +import { Node } from '../../../core/scene-graph/node'; import { LabelComponent, VerticalTextAlignment } from '../label-component'; import { SpriteComponent } from '../sprite-component'; -import { UIRenderComponent } from '../../../core/components/ui-base/ui-render-component'; -import { UITransformComponent } from '../../../core/components/ui-base/ui-transform-component'; import { EditBoxImpl } from './edit-box-impl'; +import { EditBoxImplBase } from './edit-box-impl-base'; import { InputFlag, InputMode, KeyboardReturnType } from './types'; -import { Node } from '../../../core/scene-graph/node'; +import sys from '../../../core/platform/sys'; const LEFT_PADDING = 2; -function capitalize (string) { - return string.replace(/(?:^|\s)\S/g, (a) => { +function capitalize (str: string) { + return str.replace(/(?:^|\s)\S/g, (a) => { return a.toUpperCase(); }); } -function capitalizeFirstLetter (string) { - return string.charAt(0).toUpperCase() + string.slice(1); +function capitalizeFirstLetter (str: string) { + return str.charAt(0).toUpperCase() + str.slice(1); } - /** * @en * cc.EditBoxComponent is a component for inputing text, you can use it to gather small amounts of text from users. @@ -76,7 +76,7 @@ export class EditBoxComponent extends Component { * 输入框的初始输入内容,如果为空则会显示占位符的文本。 */ @property({ - tooltip:'输入框的初始输入内容,如果为空则会显示占位符的文本', + tooltip: '输入框的初始输入内容,如果为空则会显示占位符的文本', }) get string () { return this._string; @@ -88,11 +88,53 @@ export class EditBoxComponent extends Component { } this._string = value; - if (this._impl) { - this._updateString(value); - } + this._updateString(value); } + /** + * @en The Label component attached to the node for EditBox's input text label + * + * @zh 输入框输入文本节点上挂载的 Label 组件对象 + */ + @property({ + tooltip: '输入框输入文本节点上挂载的 Label 组件对象', + type: LabelComponent, + }) + get textLabel () { + return this._textLabel; + } + + set textLabel (oldValue) { + if (this._textLabel !== oldValue) { + this._textLabel = oldValue; + if (this._textLabel){ + this._updateTextLabel(); + this._updateLabels(); + } + } + } + /** + * @en The Label component attached to the node for EditBox's placeholder text label. + * + * @zh 输入框占位符节点上挂载的 Label 组件对象。 + */ + @property({ + tooltip: '输入框占位符节点上挂载的 Label 组件对象', + type: LabelComponent, + }) + get placeholderLabel () { + return this._placeholderLabel; + } + + set placeholderLabel (oldValue) { + if (this._placeholderLabel !== oldValue) { + this._placeholderLabel = oldValue; + if (this._placeholderLabel){ + this._updatePlaceholderLabel(); + this._updateLabels(); + } + } + } /** * @en * The background image of EditBox. @@ -102,7 +144,7 @@ export class EditBoxComponent extends Component { */ @property({ type: SpriteFrame, - tooltip:'输入框的背景图片', + tooltip: '输入框的背景图片', }) get backgroundImage () { return this._backgroundImage; @@ -128,7 +170,7 @@ export class EditBoxComponent extends Component { */ @property({ type: KeyboardReturnType, - tooltip:'指定移动设备上面回车按钮的样式', + tooltip: '指定移动设备上面回车按钮的样式', }) get returnType () { return this._returnType; @@ -136,9 +178,6 @@ export class EditBoxComponent extends Component { set returnType (value: KeyboardReturnType) { this._returnType = value; - if (this._impl) { - this._impl.returnType = this._returnType; - } } /** @@ -150,18 +189,15 @@ export class EditBoxComponent extends Component { */ @property({ type: InputFlag, - tooltip:'指定输入标志位,可以指定输入方式为密码或者单词首字母大写' + tooltip: '指定输入标志位,可以指定输入方式为密码或者单词首字母大写', }) get inputFlag () { return this._inputFlag; } - set inputFlag (value: InputFlag) { + set inputFlag (value) { this._inputFlag = value; - if (this._impl) { - this._impl.setInputFlag(this._inputFlag); - this._updateString(this._string); - } + this._updateString(this._string); } /** * @en @@ -173,17 +209,19 @@ export class EditBoxComponent extends Component { */ @property({ type: InputMode, - tooltip:'指定输入模式: ANY 表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式' + tooltip: '指定输入模式: ANY 表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式', }) get inputMode () { return this._inputMode; } - set inputMode (value: InputMode) { - this._inputMode = value; - if (this._impl) { - this._impl.setInputMode(this._inputMode); - } + set inputMode (oldValue) { + if (this._inputMode !== oldValue) { + this._inputMode = oldValue; + this._updateTextLabel(); + this._updatePlaceholderLabel(); + } + } /** @@ -191,26 +229,21 @@ export class EditBoxComponent extends Component { * Font size of the input text. * * @zh - * 输入框文本的字体大小。 + * 输入框文本的字体大小。该属性会在将来的版本中移除,请使用 editBox.textLabel.fontSize。 */ @property({ - tooltip:'输入框文本的字体大小', + tooltip: '输入框文本的字体大小', }) get fontSize () { - return this._fontSize; + if (!this._textLabel){ + return 20; + } + return this._textLabel!.fontSize; } set fontSize (value) { - if (this._fontSize === value) { - return; - } - - this._fontSize = value; if (this._textLabel) { - this._textLabel.fontSize = this._fontSize; - } - if (this._impl) { - this._impl.setFontSize(this._fontSize); + this._textLabel.fontSize = value; } } @@ -222,20 +255,17 @@ export class EditBoxComponent extends Component { * 输入框文本的行高。 */ @property({ - tooltip:'输入框文本的行高' + tooltip: '输入框文本的行高', }) get lineHeight () { - return this._lineHeight; - } - - set lineHeight (value) { - if (this._lineHeight === value) { - return; + if (!this._textLabel){ + return 40; } - - this._lineHeight = value; + return this._textLabel!.lineHeight; + } + set lineHeight (value: number) { if (this._textLabel) { - this._textLabel.lineHeight = this._lineHeight; + this._textLabel.lineHeight = value; } } @@ -244,31 +274,22 @@ export class EditBoxComponent extends Component { * Font color of the input text. * * @zh - * 输入框文本的颜色。 + * 输入框文本的颜色。该属性会在将来的版本中移除,请使用 editBox.textLabel.color */ @property({ type: Color, - tooltip:'输入框文本的颜色', + tooltip: '输入框文本的颜色', }) get fontColor () { - return this._fontColor; + if (!this._textLabel){ + return math.Color.WHITE.clone(); + } + return this._textLabel!.color; } set fontColor (value) { - if (this._fontColor === value) { - return; - } - - this._fontColor.set(value); if (this._textLabel) { - // this._textLabel.node.opacity = this._fontColor.a; - const renderComp = this._textLabel.node.getComponent(UIRenderComponent); - if (renderComp) { - renderComp.color = this._fontColor; - } - } - if (this._impl) { - this._impl.setFontColor(this._fontColor); + this._textLabel.color = value; } } @@ -280,23 +301,18 @@ export class EditBoxComponent extends Component { * 输入框占位符的文本内容。 */ @property({ - tooltip:'输入框占位符的文本内容', + tooltip: '输入框占位符的文本内容', }) get placeholder () { - return this._placeholder; + if (!this._placeholderLabel) { + return ''; + } + return this._placeholderLabel.string; } set placeholder (value) { - if (this._placeholder === value) { - return; - } - - this._placeholder = value; if (this._placeholderLabel) { - this._placeholderLabel.string = this._placeholder; - } - if (this._impl) { - this._impl.setPlaceholderText(this._placeholder); + this._placeholderLabel.string = value; } } @@ -305,23 +321,20 @@ export class EditBoxComponent extends Component { * The font size of placeholder. * * @zh - * 输入框占位符的字体大小。 + * 输入框占位符的字体大小。该属性会在将来的版本中移除,请使用 editBox.placeholderLabel.fontSize */ @property({ - tooltip:'输入框占位符的字体大小' + tooltip: '输入框占位符的字体大小', }) get placeholderFontSize () { - return this._placeholderFontSize; - } - - set placeholderFontSize (value) { - if (this._placeholderFontSize === value) { - return; + if (!this._placeholderLabel){ + return 20; } - - this._placeholderFontSize = value; + return this._placeholderLabel!.fontSize; + } + set placeholderFontSize (value) { if (this._placeholderLabel) { - this._placeholderLabel.fontSize = this._placeholderFontSize; + this._placeholderLabel.fontSize = value; } } @@ -330,28 +343,23 @@ export class EditBoxComponent extends Component { * The font color of placeholder. * * @zh - * 输入框占位符的字体颜色。 + * 输入框占位符的字体颜色。该属性会在将来的版本中移除,请使用 editBox.placeholderLabel.color */ @property({ - tooltip:'输入框占位符的字体颜色', + tooltip: '输入框占位符的字体颜色', }) get placeholderFontColor () { - return this._placeholderFontColor; + if (!this._placeholderLabel) { + return math.Color.GRAY.clone(); + } + return this._placeholderLabel!.color; } set placeholderFontColor (value) { - if (this._placeholderFontColor === value) { - return; + if (this._placeholderLabel) { + this._placeholderLabel.color = value; } - this._placeholderFontColor = value; - if (this._placeholderLabel) { - const comp = this._placeholderLabel.node.getComponent(UIRenderComponent); - if (comp) { - comp.color = this._placeholderFontColor; - } - // this._placeholderLabel.node.opacity = this._placeholderFontColor.a; - } } /** @@ -364,20 +372,13 @@ export class EditBoxComponent extends Component { * - 如果值为 0,则不允许用户进行任何输入。 */ @property({ - tooltip:'输入框最大允许输入的字符个数', + tooltip: '输入框最大允许输入的字符个数', }) get maxLength () { return this._maxLength; } - set maxLength (value) { - if (this._maxLength === value) { - return; - } - + set maxLength (value: number) { this._maxLength = value; - if (this._impl) { - this._impl.setMaxLength(this._maxLength); - } } /** @@ -387,19 +388,18 @@ export class EditBoxComponent extends Component { * @zh * 输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义) * Note: only available on Web at the moment. + * + * @deprecated */ @property({ - tooltip:'输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义)' + tooltip: '输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义)', }) get stayOnTop () { - return this._stayOnTop; + return; } set stayOnTop (value) { - this._stayOnTop = value; - if (this._impl) { - this._updateStayOnTop(); - } + console.warn('stayOnTop is removed.'); } /** @@ -410,20 +410,22 @@ export class EditBoxComponent extends Component { * 修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)。 */ @property({ - tooltip:'修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)', + tooltip: '修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)', }) get tabIndex () { return this._tabIndex; } set tabIndex (value) { - this._tabIndex = value; - if (this._impl) { - this._impl.setTabIndex(value); + if (this._tabIndex !== value) { + this._tabIndex = value; + if (this._impl) { + this._impl.setTabIndex(value); + } } } - public static _EditBoxImpl = EditBoxImpl; + public static _EditBoxImpl = EditBoxImplBase; public static KeyboardReturnType = KeyboardReturnType; public static InputFlag = InputFlag; public static InputMode = InputMode; @@ -436,7 +438,7 @@ export class EditBoxComponent extends Component { */ @property({ type: [ComponentEventHandler], - tooltip:'该事件在用户点击输入框获取焦点的时候被触发', + tooltip: '该事件在用户点击输入框获取焦点的时候被触发', }) public editingDidBegan: ComponentEventHandler[] = []; @@ -449,7 +451,7 @@ export class EditBoxComponent extends Component { */ @property({ type: [ComponentEventHandler], - tooltip:'编辑文本输入框时触发的事件回调' + tooltip: '编辑文本输入框时触发的事件回调', }) public textChanged: ComponentEventHandler[] = []; @@ -462,7 +464,7 @@ export class EditBoxComponent extends Component { */ @property({ type: [ComponentEventHandler], - tooltip:'在单行模式下面,一般是在用户按下回车或者点击屏幕输入框以外的地方调用该函数。 如果是多行输入,一般是在用户点击屏幕输入框以外的地方调用该函数', + tooltip: '在单行模式下面,一般是在用户按下回车或者点击屏幕输入框以外的地方调用该函数。 如果是多行输入,一般是在用户点击屏幕输入框以外的地方调用该函数', }) public editingDidEnded: ComponentEventHandler[] = []; @@ -475,52 +477,59 @@ export class EditBoxComponent extends Component { */ @property({ type: [ComponentEventHandler], - tooltip:'该事件在用户按下回车键的时候被触发, 如果是单行输入框,按回车键还会使输入框失去焦点', + tooltip: '该事件在用户按下回车键的时候被触发, 如果是单行输入框,按回车键还会使输入框失去焦点', }) public editingReturn: ComponentEventHandler[] = []; - public _impl: EditBoxImpl | null = null; - public _textLabel: LabelComponent | null = null; - public _placeholderLabel: LabelComponent | null = null; + public _impl: EditBoxImplBase | null = null; public _background: SpriteComponent | null = null; + @property - private _returnType = KeyboardReturnType.DEFAULT; + protected _textLabel: LabelComponent | null = null; @property - private _useOriginalSize = true; + protected _placeholderLabel: LabelComponent | null = null; @property - private _string = ''; + protected _returnType = KeyboardReturnType.DEFAULT; @property - private _tabIndex = 0; + protected _useOriginalSize = true; @property - private _backgroundImage: SpriteFrame | null = null; + protected _string = ''; @property - private _inputFlag = InputFlag.DEFAULT; + protected _tabIndex = 0; @property - private _inputMode = InputMode.ANY; + protected _backgroundImage: SpriteFrame | null = null; @property - private _fontSize = 20; + protected _inputFlag = InputFlag.DEFAULT; @property - private _lineHeight = 40; + protected _inputMode = InputMode.ANY; @property - private _maxLength = 20; - @property - private _fontColor: Color = Color.WHITE.clone(); - @property - private _placeholder = 'Enter text here...'; - @property - private _placeholderFontSize = 20; - @property - private _placeholderFontColor: Color = Color.GRAY.clone(); - @property - private _stayOnTop = false; + protected _maxLength = 20; + + private _isLabelVisible = false; + + public __preload () { + this._init(); + } public onEnable () { + if (!CC_EDITOR) { + this._registerEvent(); + } if (this._impl) { this._impl.onEnable(); } } + public update () { + if (this._impl) { + this._impl.update(); + } + } + public onDisable () { + if (!CC_EDITOR) { + this._unregisterEvent(); + } if (this._impl) { this._impl.onDisable(); } @@ -532,92 +541,114 @@ export class EditBoxComponent extends Component { } } - public _init () { + /** + * @en Let the EditBox get focus + * @zh 让当前 EditBox 获得焦点。 + */ + public setFocus () { + if (this._impl) { + this._impl.setFocus(true); + } + } + + /** + * @en Let the EditBox get focus + * @zh 让当前 EditBox 获得焦点 + */ + public focus () { + if (this._impl) { + this._impl.setFocus(true); + } + } + + /** + * @en Let the EditBox lose focus + * @zh 让当前 EditBox 失去焦点 + */ + public blur () { + if (this._impl) { + this._impl.setFocus(false); + } + } + + /** + * @en Determine whether EditBox is getting focus or not. + * @zh 判断 EditBox 是否获得了焦点。 + * Note: only available on Web at the moment. + */ + public isFocused () { + if (this._impl) { + return this._impl.isFocused(); + } + return false; + } + + public _editBoxEditingDidBegan () { + ComponentEventHandler.emitEvents(this.editingDidBegan, this); + this.node.emit('editing-did-began', this); + } + + public _editBoxEditingDidEnded () { + ComponentEventHandler.emitEvents(this.editingDidEnded, this); + this.node.emit('editing-did-ended', this); + } + + public _editBoxTextChanged (text: string) { + text = this._updateLabelStringStyle(text, true); + this.string = text; + ComponentEventHandler.emitEvents(this.textChanged, text, this); + this.node.emit('text-changed', this); + } + + public _editBoxEditingReturn () { + ComponentEventHandler.emitEvents(this.editingReturn, this); + this.node.emit('editing-return', this); + } + + public _showLabels () { + this._isLabelVisible = true; + this._updateLabels(); + } + + public _hideLabels () { + this._isLabelVisible = false; + if (this._textLabel) { + this._textLabel.node.active = false; + } + if (this._placeholderLabel) { + this._placeholderLabel.node.active = false; + } + } + + protected _onTouchBegan (event: EventTouch) { + event.propagationStopped = true; + } + + protected _onTouchCancel (event: EventTouch) { + event.propagationStopped = true; + } + + protected _onTouchEnded (event: EventTouch) { + if (this._impl) { + this._impl.beginEditing(); + } + event.propagationStopped = true; + } + + protected _init () { this._createBackgroundSprite(); - this._createLabels(); + this._updatePlaceholderLabel(); + this._updateTextLabel(); + this._isLabelVisible = true; this.node.on(SystemEventType.SIZE_CHANGED, this._resizeChildNodes, this); - const impl = this._impl = new EditBoxImpl(); - - impl.setDelegate(this); - impl.setNode(this.node); - impl.setInputMode(this._inputMode); - impl.setMaxLength(this._maxLength); - impl.setInputFlag(this._inputFlag); - impl.setReturnType(this._returnType); - impl.setTabIndex(this._tabIndex); - impl.setFontColor(this._fontColor); - impl.setFontSize(this._fontSize); - impl.setPlaceholderText(this._placeholder); - - this._updateStayOnTop(); + const impl = this._impl = new EditBoxComponent._EditBoxImpl(); + impl.init(this); this._updateString(this._string); this._syncSize(); } - public __preload () { - if (!CC_EDITOR) { - this._registerEvent(); - } - this._init(); - } - - public _registerEvent () { - this.node.on(SystemEventType.TOUCH_START, this._onTouchBegan, this); - this.node.on(SystemEventType.TOUCH_END, this._onTouchEnded, this); - } - - public _updateStayOnTop () { - if (this.stayOnTop) { - this._hideLabels(); - } else { - this._showLabels(); - } - - if (this._impl) { - this._impl.stayOnTop(this.stayOnTop); - } - } - - public _syncSize () { - const size = this.node.getContentSize(); - - if (this._background) { - this._background.node.setAnchorPoint(this.node.getAnchorPoint()); - this._background.node.setContentSize(size); - } - - this._updateLabelPosition(size); - if (this._impl) { - this._impl.setSize(size.width, size.height); - } - } - - public _updateLabelPosition (size: Size) { - const node = this.node; - const offx = -node.anchorX * node.width; - const offy = -node.anchorY * node.height; - - const placeholderLabel = this._placeholderLabel; - const textLabel = this._textLabel; - if (textLabel) { - textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); - textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, textLabel.node.getPosition().z); - textLabel.verticalAlign = this._inputMode === InputMode.ANY ? VerticalTextAlignment.TOP : VerticalTextAlignment.CENTER; - textLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false; - } - - if (placeholderLabel) { - placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); - placeholderLabel.lineHeight = size.height; - placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, placeholderLabel.node.getPosition().z); - placeholderLabel.verticalAlign = this._inputMode === InputMode.ANY ? - VerticalTextAlignment.TOP : VerticalTextAlignment.CENTER; - placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false; - } - } - - public _createBackgroundSprite () { + protected _createBackgroundSprite () { if (!this._background) { this._background = this.node.getComponent(SpriteComponent); if (!this._background) { @@ -628,109 +659,99 @@ export class EditBoxComponent extends Component { this._background!.type = SpriteComponent.Type.SLICED; this._background!.spriteFrame = this._backgroundImage; - // let background = this._background; - // if (!background) { - // let node = this.node.getChildByName('BACKGROUND_SPRITE') as Node; - // if (!node) { - // node = new cc.Node('BACKGROUND_SPRITE') as Node; - // } - - // background = node.getComponent(cc.SpriteComponent); - // if (!background) { - // background = node.addComponent(cc.SpriteComponent); - // } - // background.type = cc.SpriteComponent.Type.SLICED; - - // node.parent = this.node; - // this._background = background; - // } - // background.spriteFrame = this._backgroundImage; } - public _createLabels () { - if (!this._textLabel) { + protected _updateTextLabel () { + let textLabel = this._textLabel; + + // If textLabel doesn't exist, create one. + if (!textLabel) { let node = this.node.getChildByName('TEXT_LABEL'); if (!node) { node = new Node('TEXT_LABEL'); } - let textLabel = node!.getComponent(LabelComponent); - node!.parent = this.node; - + textLabel = node!.getComponent(LabelComponent); if (!textLabel) { textLabel = node!.addComponent(LabelComponent); } - - const transformComp = node!.getComponent(UITransformComponent); - transformComp!.setAnchorPoint(0, 1); - textLabel!.color = this._fontColor; - textLabel!.overflow = LabelComponent.Overflow.CLAMP; - textLabel!.fontSize = this._fontSize; - textLabel!.lineHeight = this.lineHeight; + node!.parent = this.node; this._textLabel = textLabel; } - if (!this._placeholderLabel) { + // update + const transformComp = this._textLabel!.node._uiProps.uiTransformComp; + transformComp!.setAnchorPoint(0, 1); + textLabel!.overflow = LabelComponent.Overflow.CLAMP; + if (this._inputMode === InputMode.ANY) { + textLabel!.verticalAlign = VerticalTextAlignment.TOP; + textLabel!.enableWrapText = true; + } + else { + textLabel!.verticalAlign = VerticalTextAlignment.CENTER; + textLabel!.enableWrapText = false; + } + textLabel!.string = this._updateLabelStringStyle(this._string); + } + + protected _updatePlaceholderLabel () { + let placeholderLabel = this._placeholderLabel; + + // If placeholderLabel doesn't exist, create one. + if (!placeholderLabel) { let node = this.node.getChildByName('PLACEHOLDER_LABEL'); if (!node) { node = new Node('PLACEHOLDER_LABEL'); } - let placeholderLabel = node!.getComponent(LabelComponent); + placeholderLabel = node!.getComponent(LabelComponent); if (!placeholderLabel) { placeholderLabel = node!.addComponent(LabelComponent); } - const transform = node!.getComponent(UITransformComponent); - node!.parent = this.node; - placeholderLabel!.color = this._placeholderFontColor; - transform!.setAnchorPoint(0, 1); - - placeholderLabel!.overflow = LabelComponent.Overflow.CLAMP; - placeholderLabel!.fontSize = this._placeholderFontSize; - placeholderLabel!.string = this._placeholder; this._placeholderLabel = placeholderLabel; } + + // update + const transform = this._placeholderLabel!.node._uiProps.uiTransformComp; + transform!.setAnchorPoint(0, 1); + placeholderLabel!.overflow = LabelComponent.Overflow.CLAMP; + if (this._inputMode === InputMode.ANY) { + placeholderLabel!.verticalAlign = VerticalTextAlignment.TOP; + placeholderLabel!.enableWrapText = true; + } + else { + placeholderLabel!.verticalAlign = VerticalTextAlignment.CENTER; + placeholderLabel!.enableWrapText = false; + } + placeholderLabel!.string = this.placeholder; } - public _resizeChildNodes () { - const textLabelNode = this._textLabel && this._textLabel.node; - if (textLabelNode) { - textLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, textLabelNode.getPosition().z); - textLabelNode.width = this.node.width; - textLabelNode.height = this.node.height; + protected _syncSize () { + const size = this.node.getContentSize(); + + if (this._background) { + this._background.node._uiProps.uiTransformComp!.anchorPoint = this.node._uiProps.uiTransformComp!.anchorPoint; + this._background.node.setContentSize(size); } - const placeholderLabelNode = this._placeholderLabel && this._placeholderLabel.node; - if (placeholderLabelNode) { - placeholderLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, placeholderLabelNode.getPosition().z); - placeholderLabelNode.width = this.node.width; - placeholderLabelNode.height = this.node.height; - } - const backgroundNode = this._background && this._background.node; - if (backgroundNode) { - backgroundNode.width = this.node.width; - backgroundNode.height = this.node.height; + + this._updateLabelPosition(size); + if (this._impl) { + this._impl.setSize(size.width, size.height); } } - public _showLabels () { - if (this._textLabel) { - const displayText = this._textLabel.string; - this._textLabel.node.active = displayText !== ''; + protected _updateLabels () { + if (this._isLabelVisible) { + const content = this._string; + if (this._textLabel) { + this._textLabel.node.active = (content !== ''); + } if (this._placeholderLabel) { - this._placeholderLabel.node.active = displayText === ''; + this._placeholderLabel.node.active = (content === ''); } } } - public _hideLabels () { - if (this._textLabel) { - this._textLabel.node.active = false; - } - if (this._placeholderLabel) { - this._placeholderLabel.node.active = false; - } - } - - public _updateString (text: string) { + protected _updateString (text: string) { const textLabel = this._textLabel; // Not inited yet if (!textLabel) { @@ -743,15 +764,11 @@ export class EditBoxComponent extends Component { } textLabel.string = displayText; - if (this._impl) { - this._impl.setString(text); - if (!this._impl.editing && !this.stayOnTop) { - this._showLabels(); - } - } + + this._updateLabels(); } - public _updateLabelStringStyle (text: string, ignorePassword: boolean = false) { + protected _updateLabelStringStyle (text: string, ignorePassword: boolean = false) { const inputFlag = this._inputFlag; if (!ignorePassword && inputFlag === InputFlag.PASSWORD) { let passwordString = ''; @@ -771,81 +788,63 @@ export class EditBoxComponent extends Component { return text; } - public editBoxEditingDidBegan () { - this._hideLabels(); - ComponentEventHandler.emitEvents(this.editingDidBegan, this); - this.node.emit('editing-did-began', this); + protected _registerEvent () { + this.node.on(SystemEventType.TOUCH_START, this._onTouchBegan, this); + this.node.on(SystemEventType.TOUCH_END, this._onTouchEnded, this); } - public editBoxEditingDidEnded () { - if (!this.stayOnTop) { - this._showLabels(); + protected _unregisterEvent () { + this.node.off(SystemEventType.TOUCH_START, this._onTouchBegan, this); + this.node.off(SystemEventType.TOUCH_END, this._onTouchEnded, this); + } + + protected _updateLabelPosition (size: Size) { + const node = this.node; + const offX = -node.anchorX * node.width; + const offY = -node.anchorY * node.height; + + const placeholderLabel = this._placeholderLabel; + const textLabel = this._textLabel; + if (textLabel) { + textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); + textLabel.node.position = new Vec3 (offX + LEFT_PADDING, offY + size.height, textLabel.node.position.z); + textLabel.verticalAlign = this._inputMode === InputMode.ANY ? VerticalTextAlignment.TOP : VerticalTextAlignment.CENTER; + textLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false; } - ComponentEventHandler.emitEvents(this.editingDidEnded, this); - this.node.emit('editing-did-ended', this); - } - public editBoxTextChanged (text) { - text = this._updateLabelStringStyle(text, true); - this.string = text; - ComponentEventHandler.emitEvents(this.textChanged, text, this); - this.node.emit('text-changed', this); - } - - public editBoxEditingReturn () { - ComponentEventHandler.emitEvents(this.editingReturn, this); - this.node.emit('editing-return', this); - } - - public _onTouchBegan (event: EventTouch) { - if (this._impl) { - this._impl._onTouchBegan(event.touch); - } - event.propagationStopped = true; - } - - // public _onTouchCancel (event) { - // // if (this._impl) { - // // this._impl._onTouchCancel(); - // // } - // event.propagationStopped = true; - // } - - public _onTouchEnded (event: EventTouch) { - if (this._impl) { - this._impl._onTouchEnded(); - } - event.propagationStopped = true; - } - - /** - * @en Let the EditBox get focus - * @zh 让当前 EditBox 获得焦点。 - */ - public setFocus () { - if (this._impl) { - this._impl.setFocus(); + if (placeholderLabel) { + placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); + placeholderLabel.lineHeight = size.height; + placeholderLabel.node.position = new Vec3 (offX + LEFT_PADDING, offY + size.height, placeholderLabel.node.position.z); + placeholderLabel.verticalAlign = this._inputMode === InputMode.ANY ? + VerticalTextAlignment.TOP : VerticalTextAlignment.CENTER; + placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false; } } - /** - * @en Determine whether EditBox is getting focus or not. - * @zh 判断 EditBox 是否获得了焦点。 - * Note: only available on Web at the moment. - */ - public isFocused () { - let isFocused = false; - if (this._impl) { - isFocused = this._impl.isFocused(); + protected _resizeChildNodes () { + const textLabelNode = this._textLabel && this._textLabel.node; + if (textLabelNode) { + textLabelNode.position = new Vec3(-this.node.width / 2, this.node.height / 2, textLabelNode.position.z); + textLabelNode.width = this.node.width; + textLabelNode.height = this.node.height; + } + const placeholderLabelNode = this._placeholderLabel && this._placeholderLabel.node; + if (placeholderLabelNode) { + placeholderLabelNode.position = new Vec3(-this.node.width / 2, this.node.height / 2, placeholderLabelNode.position.z); + placeholderLabelNode.width = this.node.width; + placeholderLabelNode.height = this.node.height; + } + const backgroundNode = this._background && this._background.node; + if (backgroundNode) { + backgroundNode.width = this.node.width; + backgroundNode.height = this.node.height; } - return isFocused; } +} - public update () { - if (this._impl) { - this._impl.update(); - } - } +if (sys.isBrowser){ + EditBoxComponent._EditBoxImpl = EditBoxImpl; } cc.EditBoxComponent = EditBoxComponent; diff --git a/cocos/ui/components/editbox/edit-box-impl-base.ts b/cocos/ui/components/editbox/edit-box-impl-base.ts new file mode 100644 index 0000000000..8cc54aaeea --- /dev/null +++ b/cocos/ui/components/editbox/edit-box-impl-base.ts @@ -0,0 +1,70 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2012 James Chen + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +import { EditBoxComponent } from './edit-box-component'; + +export class EditBoxImplBase { + public _editing = false; + public _delegate: EditBoxComponent | null = null; + + public init (delegate: EditBoxComponent) {} + + public onEnable () {} + + public update () { } + + public onDisable () { + if (this._editing) { + this.endEditing(); + } + } + + public clear () { + this._delegate = null; + } + + public setTabIndex (index: number) {} + + public setSize (width: number, height: number) {} + + public setFocus (value) { + if (value) { + this.beginEditing(); + } + else { + this.endEditing(); + } + } + + public isFocused () { + return this._editing; + } + + public beginEditing () {} + + public endEditing () {} +} diff --git a/cocos/ui/components/editbox/edit-box-impl.ts b/cocos/ui/components/editbox/edit-box-impl.ts index b131fed74a..2f6ae83553 100644 --- a/cocos/ui/components/editbox/edit-box-impl.ts +++ b/cocos/ui/components/editbox/edit-box-impl.ts @@ -30,27 +30,26 @@ * @hidden */ -import { ccclass } from '../../../core/data/class-decorator'; +import { BitmapFont } from '../../../core'; +import { director } from '../../../core/director'; +import { game } from '../../../core/game'; +import { Color, Mat4, Size, Vec3 } from '../../../core/math'; +import { screen, view } from '../../../core/platform'; import { macro } from '../../../core/platform/macro'; import { contains } from '../../../core/utils/misc'; -import { Color, Mat4, Size, Vec3 } from '../../../core/math'; -import { UIRenderComponent } from '../../../core/components/ui-base/ui-render-component'; +import { LabelComponent } from '../label-component'; import { EditBoxComponent} from './edit-box-component'; +import { tabIndexUtil } from './tabIndexUtil'; import { InputFlag, InputMode, KeyboardReturnType } from './types'; -import { warnID } from '../../../core/platform/debug'; import sys from '../../../core/platform/sys'; -import { view, screen } from '../../../core/platform'; -import { director } from '../../../core/director'; import visibleRect from '../../../core/platform/visible-rect'; -import { game } from '../../../core/game'; import { Node } from '../../../core'; +import { EditBoxImplBase } from './edit-box-impl-base'; // https://segmentfault.com/q/1010000002914610 const SCROLLY = 40; const LEFT_PADDING = 2; const DELAY_TIME = 400; -const FOCUS_DELAY_UC = 400; -const FOCUS_DELAY_FIREFOX = 0; const _matrix = new Mat4(); const _matrix_temp = new Mat4(); @@ -58,6 +57,8 @@ const _vec3 = new Vec3(); let _currentEditBoxImpl: EditBoxImpl | null = null; +let _domCount = 0; + // polyfill const polyfill = { zoomInvalid: false, @@ -69,31 +70,12 @@ if (sys.OS_ANDROID === sys.os && polyfill.zoomInvalid = true; } -function getKeyboardReturnType (type) { - switch (type) { - case KeyboardReturnType.DEFAULT: - case KeyboardReturnType.DONE: - return 'done'; - case KeyboardReturnType.SEND: - return 'send'; - case KeyboardReturnType.SEARCH: - return 'search'; - case KeyboardReturnType.GO: - return 'go'; - case KeyboardReturnType.NEXT: - return 'next'; - } - return 'done'; -} - -@ccclass -export class EditBoxImpl { +export class EditBoxImpl extends EditBoxImplBase { public _delegate: EditBoxComponent | null = null; - public _inputMode = -1; - public _inputFlag = -1; + public _inputMode = InputMode.ANY; + public _inputFlag = InputFlag.DEFAULT; public _returnType = KeyboardReturnType.DEFAULT; public _maxLength = 50; - public _text = ''; public _placeholderText = ''; public _alwaysOnTop = false; public _size: Size = new Size(); @@ -109,319 +91,230 @@ export class EditBoxImpl { public _edFontSize = 14; private _isTextArea = false; - get text () { - return this._text; - } + private _textLabelFont = null; + private _textLabelFontSize = null; + private _textLabelFontColor = null; + private _textLabelAlign = null; + private _placeholderLabelFont = null; + private _placeholderLabelFontSize = null; + private _placeholderLabelFontColor = null; + private _placeholderLabelAlign = null; + private _placeholderLineHeight = null; + private _placeholderStyleSheet: any = null; + private _domId = `EditBoxId_${++_domCount}`; - set text (value: string) { - this._text = value; - } + public init (delegate: EditBoxComponent) { + if (!delegate){ + return; + } - get textColor () { - return this._textColor; - } + this._delegate = delegate; + if (delegate.inputMode === InputMode.ANY){ + this._createTextArea(); + } else { + this._createInput(); + } - get fontSize () { - return this._edFontSize; - } + tabIndexUtil.add(this); + this.setTabIndex(delegate.tabIndex); + this._initStyleSheet(); + this._registerEventListeners(); + this._addDomToGameContainer(); - set returnType (value: KeyboardReturnType) { - this._returnType = value; - } - - get alwayOnTop () { - return this._alwaysOnTop; - } - - get editing (){ - return this._editing; - } - - set editing (value: boolean) { - this._editing = value; - } - - get delegate () { - return this._delegate; - } - - get eventListeners () { - return this.__eventListeners; + this.__fullscreen = view.isAutoFullScreenEnabled(); + this.__autoResize = view._resizeWithBrowserSize; } public onEnable () { - if (!this._edTxt) { - return; - } - if (this._alwaysOnTop) { - this._edTxt.style.display = ''; - } else { - this._edTxt.style.display = 'none'; - } + // Do nothing } public onDisable () { - if (!this._edTxt) { - return; + if (this._editing && this._edTxt) { + this._edTxt.blur(); } - this._edTxt.style.display = 'none'; - } - - public setTabIndex (index: number) { - if (this._edTxt) { - this._edTxt.tabIndex = index; - } - } - - public setFocus () { - this._beginEditing(); - } - - public isFocused () { - if (this._edTxt) { - return document.activeElement === this._edTxt; - } - warnID(4700); - return false; - } - - public stayOnTop (flag) { - if (this._alwaysOnTop === flag || !this._edTxt) { return; } - - this._alwaysOnTop = flag; - - if (flag) { - this._edTxt.style.display = ''; - } else { - this._edTxt.style.display = 'none'; - } - } - - public setMaxLength (maxLength: number) { - if (!isNaN(maxLength)) { - if (maxLength < 0) { - // we can't set Number.MAX_VALUE to input's maxLength property - // so we use a magic number here, it should works at most use cases. - maxLength = 65535; - } - this._maxLength = maxLength; - if (this._edTxt) { - this._edTxt.maxLength = maxLength; - } - } - } - - public setString (text: string) { - this._text = text; - if (this._edTxt) { - this._edTxt.value = text; - } - } - - public getString () { - return this._text; - } - - public setPlaceholderText (text: string) { - this._placeholderText = text; - } - - public getPlaceholderText () { - return this._placeholderText; - } - - public setDelegate (delegate: EditBoxComponent | null) { - this._delegate = delegate; - } - - public setInputMode (inputMode: InputMode) { - if (this._inputMode === inputMode) { return; } - - this._inputMode = inputMode; - this.createInput(); - - this._updateDomInputType(); - this._updateSize(this._size.width, this._size.height); - } - - public setInputFlag (inputFlag: InputFlag) { - if (this._inputFlag === inputFlag) { return; } - - this._inputFlag = inputFlag; - this._updateDomInputType(); - - let textTransform = 'none'; - - if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { - textTransform = 'uppercase'; - } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { - textTransform = 'capitalize'; - } - - if (this._edTxt) { - this._edTxt.style.textTransform = textTransform; - this._edTxt.value = this._text; - } - } - - public setReturnType (returnType: KeyboardReturnType) { - this._returnType = returnType; - this._updateDomInputType(); - } - - public setFontSize (fontSize: number) { - this._edFontSize = fontSize || this._edFontSize; - if (this._edTxt) { - this._edTxt.style.fontSize = this._edFontSize + 'px'; - } - } - - public setFontColor (color: Color) { - this._textColor = color; - if (this._edTxt) { - this._edTxt.style.color = color.toCSS('rgba'); - } - } - - public setSize (width: number, height: number) { - this._size.width = width; - this._size.height = height; - this._updateSize(width, height); - } - - public setNode (node: Node) { - this._node = node; - } - - public update () { - // TODO: find better way to update matrix - // if (this._editing) { - this._updateMatrix(); - // } } public clear () { - this._node = null; - this.setDelegate(null); - this.removeDom(); - } + this._removeEventListeners(); + this._removeDomFromGameContainer(); - public _onTouchBegan (touch) { + tabIndexUtil.remove(this); - } - - public _onTouchEnded () { - this._beginEditing(); - } - - public _beginEditing () { - if (sys.isMobile && !this._editing) { - // Pre adaptation - this._beginEditingOnMobile(); + // clear while editing + if (_currentEditBoxImpl === this) { + _currentEditBoxImpl = null; } - const self = this; - function startFocus () { - self._edTxt && self._edTxt.focus(); + this._delegate = null; + } + + public update () { + this._updateMatrix(); + } + + public setTabIndex (index: number) { + this._edTxt!.tabIndex = index; + tabIndexUtil.resort(); + } + + public setSize (width: number, height: number) { + const elem = this._edTxt; + if (elem){ + elem.style.width = width + 'px'; + elem.style.height = height + 'px'; } - if (this._edTxt) { - this._edTxt.style.display = ''; + } - if (sys.browserType === sys.BROWSER_TYPE_UC) { - setTimeout(startFocus, FOCUS_DELAY_UC); - } else if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) { - setTimeout(startFocus, FOCUS_DELAY_FIREFOX); - } else { - startFocus(); - } + public setFocus (value: boolean) { + if (value){ + this.beginEditing(); + } + else { + this._edTxt!.blur(); + } + } + + public isFocused () { + return this._editing; + } + + public beginEditing () { + if (_currentEditBoxImpl && _currentEditBoxImpl !== this) { + _currentEditBoxImpl.setFocus(false); } this._editing = true; + _currentEditBoxImpl = this; + this._showDom(); + if (this._edTxt && this._delegate){ + this._edTxt.focus(); + this._delegate._editBoxEditingDidBegan(); + } } - public _endEditing () { + public endEditing () { + // Do nothing, handle endEditing on blur callback + } + + private _createInput () { + this._isTextArea = false; + this._edTxt = document.createElement('input'); + } + + private _createTextArea () { + this._isTextArea = true; + this._edTxt = document.createElement('textarea'); + } + + private _addDomToGameContainer () { + if (game.container && this._edTxt) { + game.container.appendChild(this._edTxt); + document.head.appendChild(this._placeholderStyleSheet); + } + } + + private _removeDomFromGameContainer () { + const hasElem = contains(game.container, this._edTxt); + if (hasElem && this._edTxt) { + game.container!.removeChild(this._edTxt); + } + const hasStyleSheet = contains(document.head, this._placeholderStyleSheet); + if (hasStyleSheet) { + document.head.removeChild(this._placeholderStyleSheet); + } + + delete this._edTxt; + delete this._placeholderStyleSheet; + } + + private _showDom () { + this._updateMaxLength(); + this._updateInputType(); + this._updateStyleSheet(); + if (this._edTxt && this._delegate){ + this._edTxt.style.display = ''; + this._delegate._hideLabels(); + } + if (sys.isMobile) { + this._showDomOnMobile(); + } + } + + private _hideDom () { + const elem = this._edTxt; + if (elem && this._delegate) { + elem.style.display = 'none'; + this._delegate._showLabels(); + } + if (sys.isMobile) { + this._hideDomOnMobile(); + } + } + + private _showDomOnMobile () { + if (sys.os !== sys.OS_ANDROID) { + return; + } + + if (this.__fullscreen) { + view.enableAutoFullScreen(false); + screen.exitFullScreen(); + } + if (this.__autoResize) { + view.resizeWithBrowserSize(false); + } + + this._adjustWindowScroll(); + } + + private _hideDomOnMobile () { + if (sys.os === sys.OS_ANDROID) { + setTimeout(() => { + if (!_currentEditBoxImpl) { + if (this.__fullscreen) { + view.enableAutoFullScreen(true); + } + if (this.__autoResize) { + view.resizeWithBrowserSize(true); + } + } + }, DELAY_TIME); + } + + this._scrollBackWindow(); + } + + private _adjustWindowScroll () { const self = this; - const hideDomInputAndShowLabel = () => { - if (!self._alwaysOnTop && self._edTxt) { - self._edTxt.style.display = 'none'; + setTimeout(() => { + if (window.scrollY < SCROLLY) { + self._edTxt!.scrollIntoView({block: 'start', inline: 'nearest', behavior: 'smooth'}); } - if (self._delegate && self._delegate.editBoxEditingDidEnded) { - self._delegate.editBoxEditingDidEnded(); - } - }; - if (this._editing) { - if (sys.isMobile) { - // Delay end editing adaptation to ensure virtual keyboard is disapeared - setTimeout(() => { - self._endEditingOnMobile(); - hideDomInputAndShowLabel(); - }, DELAY_TIME); - } else { - hideDomInputAndShowLabel(); - } - } - this._editing = false; + }, DELAY_TIME); } - public _updateDomInputType () { - const inputMode = this._inputMode; - let edTxt = this._edTxt; - if (!edTxt) { return; } + private _scrollBackWindow () { + setTimeout(() => { + if (sys.browserType === sys.BROWSER_TYPE_WECHAT && sys.os === sys.OS_IOS) { + if (window.top) { + window.top.scrollTo(0, 0); + } - if (this._isTextArea) { - edTxt = edTxt as HTMLTextAreaElement; - let textTransform = 'none'; - if (this._inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { - textTransform = 'uppercase'; - } else if (this._inputFlag === InputFlag.INITIAL_CAPS_WORD) { - textTransform = 'capitalize'; + return; } - edTxt.style.textTransform = textTransform; + window.scrollTo(0, 0); + }, DELAY_TIME); + } + + private _updateMatrix () { + if (!this._edTxt) { return; } - edTxt = edTxt as HTMLInputElement; - - if (this._inputFlag === InputFlag.PASSWORD) { - edTxt.type = 'password'; - return; - } - - let type = edTxt.type; - if (inputMode === InputMode.EMAIL_ADDR) { - type = 'email'; - } else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) { - type = 'number'; - } else if (inputMode === InputMode.PHONE_NUMBER) { - type = 'number'; - edTxt.pattern = '[0-9]*'; - } else if (inputMode === InputMode.URL) { - type = 'url'; - } else { - type = 'text'; - - if (this._returnType === KeyboardReturnType.SEARCH) { - type = 'search'; - } - } - - edTxt.type = type; - } - - public _updateSize (newWidth, newHeight) { - const edTxt = this._edTxt; - if (!edTxt) { return; } - - edTxt.style.width = newWidth + 'px'; - edTxt.style.height = newHeight + 'px'; - } - - public _updateMatrix () { - if (!this._edTxt) { return; } - - const node = this._node!; + const node = this._delegate!.node; let scaleX = view.getScaleX(); let scaleY = view.getScaleY(); const viewport = view.getViewportRect(); @@ -453,7 +346,6 @@ export class EditBoxImpl { _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13); Mat4.multiply(_matrix_temp, _matrix_temp, _matrix); - scaleX /= dpr; scaleY /= dpr; @@ -471,7 +363,7 @@ export class EditBoxImpl { const ty = _matrix_temp.m13 * scaleY + offsetY; if (polyfill.zoomInvalid) { - this._updateSize(this._size.width * a, this._size.height * d); + this.setSize(this._size.width * a, this._size.height * d); a = 1; d = 1; } @@ -483,252 +375,335 @@ export class EditBoxImpl { this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px'; } - public _adjustEditBoxPosition () { - this._node!.getWorldMatrix(_matrix); - const y = _matrix.m13; - const windowHeight = visibleRect.height; - const windowWidth = visibleRect.width; - let factor = 0.5; - if (windowWidth > windowHeight) { - factor = 0.7; - } - setTimeout(() => { - if (window.scrollY < SCROLLY && y < windowHeight * factor) { - let scrollOffset = windowHeight * factor - y - window.scrollY; - if (scrollOffset < 35) { scrollOffset = 35; } - if (scrollOffset > 320) { scrollOffset = 320; } - window.scrollTo(0, scrollOffset); - } - }, DELAY_TIME); - } + private _updateInputType () { + const delegate = this._delegate; + const inputMode = delegate!.inputMode; + const inputFlag = delegate!.inputFlag; + const returnType = delegate!.returnType; + let elem = this._edTxt; - public createInput () { - this._isTextArea = false; - if (this._inputMode === InputMode.ANY) { - this._isTextArea = true; - this._createDomTextArea(); - } else { - this._createDomInput(); - } - } - - // Called before editbox focus to register cc.view status - public _beginEditingOnMobile () { - const self = this; - this.__orientationChanged = () => { - self._adjustEditBoxPosition(); - }; - window.addEventListener('orientationchange', this.__orientationChanged); - - if (view.isAutoFullScreenEnabled()) { - this.__fullscreen = true; - view.enableAutoFullScreen(false); - screen.exitFullScreen(); - } else { - this.__fullscreen = false; - } - this.__autoResize = view._resizeWithBrowserSize; - view.resizeWithBrowserSize(false); - _currentEditBoxImpl = this; - } - - // Called after keyboard disappeared to readapte the game view - public _endEditingOnMobile () { - if (this.__rotateScreen) { - if (game.container) { - game.container.style['-webkit-transform'] = 'rotate(90deg)'; - game.container.style.transform = 'rotate(90deg)'; - } - - const width = view._originalDesignResolutionSize.width; - const height = view._originalDesignResolutionSize.height; - if (width > 0) { - view.setDesignResolutionSize(width, height, view.getResolutionPolicy()); - } - this.__rotateScreen = false; - } - - if (this.__orientationChanged) { - window.removeEventListener('orientationchange', this.__orientationChanged); - } - - if (this.__fullscreen) { - view.enableAutoFullScreen(true); - } - - // In case focus on editBox A from editBox B - // A disable resizeWithBrowserSize - // whilte B enable resizeWithBrowserSize - // Only _currentEditBoxImpl can enable resizeWithBrowserSize - if (this.__autoResize && _currentEditBoxImpl === this) { - view.resizeWithBrowserSize(true); - } - } - - public _createDomInput () { - this.removeDom(); - - const tmpEdTxt = this._edTxt = document.createElement('input'); - tmpEdTxt.type = 'text'; - tmpEdTxt.style.fontSize = this._edFontSize + 'px'; - tmpEdTxt.style.color = '#000000'; - tmpEdTxt.style.border = '0px'; - tmpEdTxt.style.background = 'transparent'; - tmpEdTxt.style.width = '100%'; - tmpEdTxt.style.height = '100%'; - // tmpEdTxt.style.active = 0; - tmpEdTxt.style.outline = 'medium'; - tmpEdTxt.style.padding = '0'; - tmpEdTxt.style.textTransform = 'uppercase'; - tmpEdTxt.style.display = 'none'; - tmpEdTxt.style.position = 'absolute'; - tmpEdTxt.style.bottom = '0px'; - tmpEdTxt.style.left = LEFT_PADDING + 'px'; - tmpEdTxt.style['-moz-appearance'] = 'textfield'; - tmpEdTxt.className = 'cocosEditBox'; - tmpEdTxt.style.fontFamily = 'Arial'; - - registerInputEventListener(tmpEdTxt, this); - - return tmpEdTxt; - } - - public _createDomTextArea () { - this.removeDom(); - - const tmpEdTxt = this._edTxt = document.createElement('textarea'); - // tmpEdTxt.type = 'text'; - tmpEdTxt.style.fontSize = this._edFontSize + 'px'; - tmpEdTxt.style.color = '#000000'; - tmpEdTxt.style.border = '0'; - tmpEdTxt.style.background = 'transparent'; - tmpEdTxt.style.width = '100%'; - tmpEdTxt.style.height = '100%'; - // tmpEdTxt.style.active = 0; - tmpEdTxt.style.outline = 'medium'; - tmpEdTxt.style.padding = '0'; - tmpEdTxt.style.resize = 'none'; - tmpEdTxt.style.textTransform = 'uppercase'; - tmpEdTxt.style.overflowY = 'scroll'; - tmpEdTxt.style.display = 'none'; - tmpEdTxt.style.position = 'absolute'; - tmpEdTxt.style.bottom = '0px'; - tmpEdTxt.style.left = LEFT_PADDING + 'px'; - tmpEdTxt.className = 'cocosEditBox'; - tmpEdTxt.style.fontFamily = 'Arial'; - - registerInputEventListener(tmpEdTxt, this, true); - - return tmpEdTxt; - } - - public _addDomToGameContainer () { - if (game.container && this._edTxt) { - game.container.appendChild(this._edTxt); - } - } - - public removeDom () { - const edTxt = this._edTxt; - if (edTxt) { - // Remove listeners - const cbs = this.__eventListeners; - edTxt.removeEventListener('compositionstart', cbs.compositionstart); - edTxt.removeEventListener('compositionend', cbs.compositionend); - edTxt.removeEventListener('input', cbs.input); - edTxt.removeEventListener('focus', cbs.focus); - edTxt.removeEventListener('keypress', cbs.keypress); - edTxt.removeEventListener('blur', cbs.blur); - cbs.compositionstart = null; - cbs.compositionend = null; - cbs.input = null; - cbs.focus = null; - cbs.keypress = null; - cbs.blur = null; - - const hasChild = contains(game.container, edTxt); - if (hasChild && game.container) { - game.container.removeChild(edTxt); - } - } - this._edTxt = null; - } -} - -function _inputValueHandle (input: any, editBoxImpl: EditBoxImpl) { - if (input.value.length > editBoxImpl._maxLength) { - input.value = input.value.slice(0, editBoxImpl._maxLength); - } - if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxTextChanged) { - if (editBoxImpl._text !== input.value) { - editBoxImpl._text = input.value; - editBoxImpl._delegate.editBoxTextChanged(editBoxImpl._text); - } - } -} - -function registerInputEventListener (tmpEdTxt: HTMLInputElement | HTMLTextAreaElement, editBoxImpl: EditBoxImpl, isTextarea = false) { - let inputLock = false; - const cbs = editBoxImpl.eventListeners; - cbs.compositionstart = () => { - inputLock = true; - }; - tmpEdTxt.addEventListener('compositionstart', cbs.compositionstart); - - cbs.compositionend = function () { - inputLock = false; - _inputValueHandle(this, editBoxImpl); - }; - tmpEdTxt.addEventListener('compositionend', cbs.compositionend); - - cbs.input = function () { - if (inputLock) { + if (this._inputMode === inputMode && + this._inputFlag === inputFlag && + this._returnType === returnType) { return; } - _inputValueHandle(this, editBoxImpl); - }; - tmpEdTxt.addEventListener('input', cbs.input); - cbs.focus = function () { - this.style.fontSize = editBoxImpl.fontSize + 'px'; - this.style.color = editBoxImpl.textColor.toCSS('rgba'); - // When stayOnTop, input will swallow touch event - if (editBoxImpl.alwayOnTop) { - editBoxImpl.editing = true; - } + // update cache + this._inputMode = inputMode; + this._inputFlag = inputFlag; + this._returnType = returnType; - if (sys.isMobile) { - editBoxImpl._beginEditingOnMobile(); - } - - if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingDidBegan) { - editBoxImpl.delegate.editBoxEditingDidBegan(); - } - - }; - tmpEdTxt.addEventListener('focus', cbs.focus); - - cbs.keypress = function (e) { - if (e.keyCode === macro.KEY.enter) { - e.propagationStopped = true; - - if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingReturn) { - editBoxImpl.delegate.editBoxEditingReturn(); + // FIX ME: TextArea actually dose not support password type. + if (this._isTextArea) { + // input flag + let textTransform = 'none'; + if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { + textTransform = 'uppercase'; } - if (!isTextarea) { - editBoxImpl.text = this.value; - editBoxImpl._endEditing(); - game.canvas && game.canvas.focus(); + else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + textTransform = 'capitalize'; + } + elem!.style.textTransform = textTransform; + return; + } + + elem = elem as HTMLInputElement; + // begin to updateInputType + if (inputFlag === InputFlag.PASSWORD) { + elem.type = 'password'; + return; + } + + // input mode + let type = elem.type; + if (inputMode === InputMode.EMAIL_ADDR) { + type = 'email'; + } else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) { + type = 'number'; + } else if (inputMode === InputMode.PHONE_NUMBER) { + type = 'number'; + elem.pattern = '[0-9]*'; + } else if (inputMode === InputMode.URL) { + type = 'url'; + } else { + type = 'text'; + + if (returnType === KeyboardReturnType.SEARCH) { + type = 'search'; } } - }; - tmpEdTxt.addEventListener('keypress', cbs.keypress); + elem!.type = type; - cbs.blur = function () { - editBoxImpl.text = this.value; - editBoxImpl._endEditing(); - }; - tmpEdTxt.addEventListener('blur', cbs.blur); + // input flag + let textTransform = 'none'; + if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { + textTransform = 'uppercase'; + } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + textTransform = 'capitalize'; + } + elem.style.textTransform = textTransform; + } - editBoxImpl._addDomToGameContainer(); + private _updateMaxLength () { + let maxLength = this._delegate!.maxLength; + if (maxLength < 0) { + maxLength = 65535; + } + this._edTxt!.maxLength = maxLength; + } + + private _initStyleSheet () { + if (!this._edTxt) { + return; + } + let elem = this._edTxt; + elem.style.fontSize = this._edFontSize + 'px'; + elem.style.color = '#000000'; + elem.style.border = '0px'; + elem.style.background = 'transparent'; + elem.style.width = '100%'; + elem.style.height = '100%'; + elem.style.outline = 'medium'; + elem.style.padding = '0'; + elem.style.textTransform = 'uppercase'; + elem.style.display = 'none'; + elem.style.position = 'absolute'; + elem.style.bottom = '0px'; + elem.style.left = LEFT_PADDING + 'px'; + elem.className = 'cocosEditBox'; + elem.style.fontFamily = 'Arial'; + elem.id = this._domId; + + if (!this._isTextArea) { + elem = elem as HTMLInputElement; + elem.type = 'text'; + elem.style['-moz-appearance'] = 'textfield'; + } + else { + elem.style.resize = 'none'; + elem.style.overflowY = 'scroll'; + + } + + this._placeholderStyleSheet = document.createElement('style'); + } + + private _updateStyleSheet () { + const delegate = this._delegate; + const elem = this._edTxt; + if (elem && delegate){ + elem.value = delegate.string; + elem.placeholder = delegate.placeholder; + + this._updateTextLabel(delegate.textLabel); + this._updatePlaceholderLabel(delegate.placeholderLabel); + } + } + + private _updateTextLabel (textLabel) { + if (!textLabel) { + return; + } + + let font = textLabel.font; + if (font && !(font instanceof BitmapFont)) { + font = font._fontFamily; + } + else { + font = textLabel.fontFamily; + } + + if (this._textLabelFont === font + && this._textLabelFontSize === textLabel.fontSize + && this._textLabelFontColor === textLabel.fontColor + && this._textLabelAlign === textLabel.horizontalAlign) { + return; + } + + this._textLabelFont = font; + this._textLabelFontSize = textLabel.fontSize; + this._textLabelFontColor = textLabel.fontColor; + this._textLabelAlign = textLabel.horizontalAlign; + + if (!this._edTxt) { + return; + } + + const elem = this._edTxt; + elem.style.fontSize = `${textLabel.fontSize}px`; + elem.style.color = textLabel.color.toCSS('rgba'); + elem.style.fontFamily = font; + + switch (textLabel.horizontalAlign) { + case LabelComponent.HorizontalAlign.LEFT: + elem.style.textAlign = 'left'; + break; + case LabelComponent.HorizontalAlign.CENTER: + elem.style.textAlign = 'center'; + break; + case LabelComponent.HorizontalAlign.RIGHT: + elem.style.textAlign = 'right'; + break; + } + } + + private _updatePlaceholderLabel (placeholderLabel) { + if (!placeholderLabel) { + return; + } + + let font = placeholderLabel.font; + if (font && !(font instanceof BitmapFont)) { + font = placeholderLabel.font._fontFamily; + } + else { + font = placeholderLabel.fontFamily; + } + + if (this._placeholderLabelFont === font + && this._placeholderLabelFontSize === placeholderLabel.fontSize + && this._placeholderLabelFontColor === placeholderLabel.fontColor + && this._placeholderLabelAlign === placeholderLabel.horizontalAlign + && this._placeholderLineHeight === placeholderLabel.fontSize) { + return; + } + + this._placeholderLabelFont = font; + this._placeholderLabelFontSize = placeholderLabel.fontSize; + this._placeholderLabelFontColor = placeholderLabel.fontColor; + this._placeholderLabelAlign = placeholderLabel.horizontalAlign; + this._placeholderLineHeight = placeholderLabel.fontSize; + + const styleEl = this._placeholderStyleSheet; + const fontSize = placeholderLabel.fontSize; + const fontColor = placeholderLabel.color.toCSS('rgba'); + const lineHeight = placeholderLabel.fontSize; + + let horizontalAlign = ''; + switch (placeholderLabel.horizontalAlign) { + case LabelComponent.HorizontalAlign.LEFT: + horizontalAlign = 'left'; + break; + case LabelComponent.HorizontalAlign.CENTER: + horizontalAlign = 'center'; + break; + case LabelComponent.HorizontalAlign.RIGHT: + horizontalAlign = 'right'; + break; + } + + styleEl!.innerHTML = ` + #${this._domId}::-webkit-input-placeholder { + text-transform: initial; + font-family: ${font}; + font-size: ${fontSize}px; + color: ${fontColor}; + line-height: ${lineHeight}px; + text-align: ${horizontalAlign}; + } + #${this._domId}::-moz-placeholder { + text-transform: initial; + font-family: ${font}; + font-size: ${fontSize}px; + color: ${fontColor}; + line-height: ${lineHeight}px; + text-align: ${horizontalAlign}; + } + #${this._domId}:-ms-input-placeholder { + text-transform: initial; + font-family: ${font}; + font-size: ${fontSize}px; + color: ${fontColor}; + line-height: ${lineHeight}px; + text-align: ${horizontalAlign}; + } + `; + } + + private _registerEventListeners () { + if (!this._edTxt){ + return; + } + + const impl = this; + const elem = this._edTxt; + let inputLock = false; + const cbs = this.__eventListeners; + + cbs.compositionStart = () => { + inputLock = true; + }; + + cbs.compositionEnd = () => { + inputLock = false; + impl._delegate!._editBoxTextChanged(elem!.value); + }; + + cbs.onInput = () => { + if (inputLock) { + return; + } + impl._delegate!._editBoxTextChanged(elem!.value); + }; + + cbs.onClick = () => { + if (impl._editing) { + if (sys.isMobile) { + impl._adjustWindowScroll(); + } + } + }; + + cbs.onKeydown = (e) => { + if (e.keyCode === macro.KEY.enter) { + e.propagationStopped = true; + impl._delegate!._editBoxEditingReturn(); + + if (!impl._isTextArea) { + elem.blur(); + } + } else if (e.keyCode === macro.KEY.tab) { + e.propagationStopped = true; + e.preventDefault(); + + tabIndexUtil.next(impl); + } + }; + + cbs.onBlur = () => { + impl._editing = false; + _currentEditBoxImpl = null; + impl._hideDom(); + impl._delegate!._editBoxEditingDidEnded(); + }; + + elem.addEventListener('compositionstart', cbs.compositionStart); + elem.addEventListener('compositionend', cbs.compositionEnd); + elem.addEventListener('input', cbs.onInput); + elem.addEventListener('keydown', cbs.onKeydown); + elem.addEventListener('blur', cbs.onBlur); + elem.addEventListener('touchstart', cbs.onClick); + } + private _removeEventListeners () { + if (!this._edTxt){ + return; + } + + const elem = this._edTxt; + const cbs = this.__eventListeners; + + elem.removeEventListener('compositionstart', cbs.compositionStart); + elem.removeEventListener('compositionend', cbs.compositionEnd); + elem.removeEventListener('input', cbs.onInput); + elem.removeEventListener('keydown', cbs.onKeydown); + elem.removeEventListener('blur', cbs.onBlur); + elem.removeEventListener('touchstart', cbs.onClick); + + cbs.compositionStart = null; + cbs.compositionEnd = null; + cbs.onInput = null; + cbs.onKeydown = null; + cbs.onBlur = null; + cbs.onClick = null; + } } diff --git a/cocos/ui/components/editbox/tabIndexUtil.ts b/cocos/ui/components/editbox/tabIndexUtil.ts new file mode 100644 index 0000000000..d08352b71f --- /dev/null +++ b/cocos/ui/components/editbox/tabIndexUtil.ts @@ -0,0 +1,39 @@ +import { EditBoxImpl } from './edit-box-impl'; + +export class tabIndexUtil { + public static _tabIndexList: EditBoxImpl[] = []; + + public static add (editBoxImpl: EditBoxImpl) { + const list = this._tabIndexList; + const index = list.indexOf(editBoxImpl); + if (index === -1){ + list.push(editBoxImpl); + } + } + + public static remove (editBoxImpl: EditBoxImpl) { + const list = this._tabIndexList; + const index = list.indexOf(editBoxImpl); + if (index !== -1) { + list.splice(index, 1); + } + } + + public static resort () { + this._tabIndexList.sort((a: EditBoxImpl, b: EditBoxImpl) => { + return a._delegate!.tabIndex - b._delegate!.tabIndex; + }); + } + + public static next (editBoxImpl: EditBoxImpl) { + const list = this._tabIndexList; + const index = list.indexOf(editBoxImpl); + editBoxImpl.setFocus(false); + if (index !== -1) { + const nextImpl = list[index + 1]; + if (nextImpl && nextImpl._delegate!.tabIndex >= 0) { + nextImpl.setFocus(true); + } + } + } +}