From ae7d762bd79c9854addfeee96baedc2f2ca3ed9d Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Fri, 12 Jan 2018 17:54:14 +0800 Subject: [PATCH] support edit box --- cocos2d/core/components/CCSprite.js | 2 +- .../components/{ => editbox}/CCEditBox.js | 497 +++---- .../core/components/editbox/CCEditBoxImpl.js | 582 ++++++++ cocos2d/core/components/editbox/types.js | 157 +++ cocos2d/core/components/index.js | 2 +- cocos2d/core/editbox/CCSGEditBox.js | 1248 ----------------- .../assemblers/label/ttf-assembler.js | 37 +- 7 files changed, 1032 insertions(+), 1493 deletions(-) rename cocos2d/core/components/{ => editbox}/CCEditBox.js (61%) create mode 100644 cocos2d/core/components/editbox/CCEditBoxImpl.js create mode 100644 cocos2d/core/components/editbox/types.js delete mode 100644 cocos2d/core/editbox/CCSGEditBox.js diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index c25328af0b..dbb2e1f822 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -477,7 +477,7 @@ var Sprite = cc.Class({ _activateMaterial: function () { // cannot be activated if texture not loaded yet - if (!this._spriteFrame.textureLoaded()) { + if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { return; } diff --git a/cocos2d/core/components/CCEditBox.js b/cocos2d/core/components/editbox/CCEditBox.js similarity index 61% rename from cocos2d/core/components/CCEditBox.js rename to cocos2d/core/components/editbox/CCEditBox.js index 6c96a98869..4c5d98c116 100644 --- a/cocos2d/core/components/CCEditBox.js +++ b/cocos2d/core/components/editbox/CCEditBox.js @@ -24,133 +24,24 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -require('../editbox/CCSGEditBox'); -/** - * !#en Enum for keyboard return types - * !#zh 键盘的返回键类型 - * @readonly - * @enum EditBox.KeyboardReturnType - */ -/** - * !#en TODO - * !#zh 默认 - * @property {Number} DEFAULT - */ -/** - * !#en TODO - * !#zh 完成类型 - * @property {Number} DONE - */ -/** - * !#en TODO - * !#zh 发送类型 - * @property {Number} SEND - */ -/** - * !#en TODO - * !#zh 搜索类型 - * @property {Number} SEARCH - */ -/** - * !#en TODO - * !#zh 跳转类型 - * @property {Number} GO - */ -var KeyboardReturnType = _ccsg.EditBox.KeyboardReturnType; +const EditBoxImpl = require('../editbox/CCEditBoxImpl'); +const Label = require('../CCLabel'); -/** - * !#en The EditBox's InputMode defines the type of text that the user is allowed to enter. - * !#zh 输入模式 - * @readonly - * @enum EditBox.InputMode - */ -/** - * !#en TODO - * !#zh 用户可以输入任何文本,包括换行符。 - * @property {Number} ANY - */ -/** - * !#en The user is allowed to enter an e-mail address. - * !#zh 允许用户输入一个电子邮件地址。 - * @property {Number} EMAIL_ADDR - */ -/** - * !#en The user is allowed to enter an integer value. - * !#zh 允许用户输入一个整数值。 - * @property {Number} NUMERIC - */ -/** - * !#en The user is allowed to enter a phone number. - * !#zh 允许用户输入一个电话号码。 - * @property {Number} PHONE_NUMBER - */ -/** - * !#en The user is allowed to enter a URL. - * !#zh 允许用户输入一个 URL。 - * @property {Number} URL - */ -/** - * !#en - * The user is allowed to enter a real number value. - * This extends kEditBoxInputModeNumeric by allowing a decimal point. - * !#zh - * 允许用户输入一个实数。 - * @property {Number} DECIMAL - */ -/** - * !#en The user is allowed to enter any text, except for line breaks. - * !#zh 除了换行符以外,用户可以输入任何文本。 - * @property {Number} SINGLE_LINE - */ -var InputMode = _ccsg.EditBox.InputMode; +const Types = require('./types'); +const InputMode = Types.InputMode; +const InputFlag = Types.InputFlag; +const KeyboardReturnType = Types.KeyboardReturnType; + +const LEFT_PADDING = 2; + +function capitalize (string) { + return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); +}; + +function capitalizeFirstLetter (string) { + return string.charAt(0).toUpperCase() + string.slice(1); +} -/** - * !#en Enum for the EditBox's input flags - * !#zh 定义了一些用于设置文本显示和文本格式化的标志位。 - * @readonly - * @enum EditBox.InputFlag - */ -/** - * !#en - * Indicates that the text entered is confidential data that should be - * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. - * !#zh - * 表明输入的文本是保密的数据,任何时候都应该隐藏起来,它隐含了 EDIT_BOX_INPUT_FLAG_SENSITIVE。 - * @property {Number} PASSWORD - */ -/** - * !#en - * Indicates that the text entered is sensitive data that the - * implementation must never store into a dictionary or table for use - * in predictive, auto-completing, or other accelerated input schemes. - * A credit card number is an example of sensitive data. - * !#zh - * 表明输入的文本是敏感数据,它禁止存储到字典或表里面,也不能用来自动补全和提示用户输入。 - * 一个信用卡号码就是一个敏感数据的例子。 - * @property {Number} SENSITIVE - */ -/** - * !#en - * This flag is a hint to the implementation that during text editing, - * the initial letter of each word should be capitalized. - * !#zh - * 这个标志用来指定在文本编辑的时候,是否把每一个单词的首字母大写。 - * @property {Number} INITIAL_CAPS_WORD - */ -/** - * !#en - * This flag is a hint to the implementation that during text editing, - * the initial letter of each sentence should be capitalized. - * !#zh - * 这个标志用来指定在文本编辑是否每个句子的首字母大写。 - * @property {Number} INITIAL_CAPS_SENTENCE - */ -/** - * !#en Capitalize all characters automatically. - * !#zh 自动把输入的所有字符大写。 - * @property {Number} INITIAL_CAPS_ALL_CHARACTERS - */ -var InputFlag = _ccsg.EditBox.InputFlag; /** * !#en cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users. @@ -179,11 +70,16 @@ var EditBox = cc.Class({ */ string: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.string', - get: function () { - return this._sgNode.string; + get () { + return this._string; }, - set: function(value) { - this._sgNode.string = this._string = value; + set(value) { + if (value.length >= this.maxLength) { + value = value.slice(0, this.maxLength); + } + + this._string = value; + this._updateString(value); } }, @@ -196,16 +92,8 @@ var EditBox = cc.Class({ tooltip: CC_DEV && 'i18n:COMPONENT.editbox.backgroundImage', default: null, type: cc.SpriteFrame, - notify: function() { - var sgNode = this._sgNode; - var backgroundSprite = sgNode.getBackgroundSprite(); - if(this.backgroundImage) { - var sprite = this._createBackgroundSprite(); - sprite.setContentSize(sgNode.getContentSize()); - } - else { - backgroundSprite.removeFromParent(); - } + notify() { + this._createBackgroundSprite(); } }, @@ -224,8 +112,8 @@ var EditBox = cc.Class({ tooltip: CC_DEV && 'i18n:COMPONENT.editbox.returnType', displayName: 'KeyboardReturnType', type: KeyboardReturnType, - notify: function() { - this._sgNode.returnType = this.returnType; + notify() { + this._impl.returnType = this.returnType; } }, @@ -239,8 +127,8 @@ var EditBox = cc.Class({ tooltip: CC_DEV && 'i18n:COMPONENT.editbox.input_flag', default: InputFlag.DEFAULT, type: InputFlag, - notify: function() { - this._sgNode.inputFlag = this.inputFlag; + notify() { + this._impl.inputFlag = this.inputFlag; } }, /** @@ -256,8 +144,8 @@ var EditBox = cc.Class({ tooltip: CC_DEV && 'i18n:COMPONENT.editbox.input_mode', default: InputMode.ANY, type: InputMode, - notify: function() { - this._sgNode.inputMode = this.inputMode; + notify() { + this._impl.setInputMode(this.inputMode); } }, @@ -269,8 +157,8 @@ var EditBox = cc.Class({ fontSize: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.font_size', default: 20, - notify: function() { - this._sgNode.fontSize = this.fontSize; + notify() { + this._textLabel.fontSize = this.fontSize; } }, @@ -282,8 +170,8 @@ var EditBox = cc.Class({ lineHeight: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.line_height', default: 40, - notify: function() { - this._sgNode.setLineHeight(this.lineHeight); + notify() { + this._textLabel.lineHeight = this.lineHeight; } }, @@ -295,8 +183,8 @@ var EditBox = cc.Class({ fontColor: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.font_color', default: cc.Color.WHITE, - notify: function() { - this._sgNode.fontColor = this.fontColor; + notify() { + this._textLabel.node.color = this.fontColor; } }, @@ -308,8 +196,8 @@ var EditBox = cc.Class({ placeholder: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder', default: 'Enter text here...', - notify: function() { - this._sgNode.placeholder = this.placeholder; + notify() { + this._placeholderLabel.string = this.placeholder; } }, @@ -321,8 +209,8 @@ var EditBox = cc.Class({ placeholderFontSize: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder_font_size', default: 20, - notify: function() { - this._sgNode.placeholderFontSize = this.placeholderFontSize; + notify() { + this._placeholderLabel.fontSize = this.placeholderFontSize; } }, @@ -334,8 +222,8 @@ var EditBox = cc.Class({ placeholderFontColor: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder_font_color', default: cc.Color.GRAY, - notify: function() { - this._sgNode.placeholderFontColor = this.placeholderFontColor; + notify() { + this._placeholderLabel.node.color = this.placeholderFontColor; } }, @@ -351,8 +239,8 @@ var EditBox = cc.Class({ maxLength: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.max_length', default: 20, - notify: function() { - this._sgNode.maxLength = this.maxLength; + notify() { + this._impl.setMaxLength(this.maxLength); } }, @@ -365,11 +253,9 @@ var EditBox = cc.Class({ stayOnTop: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.stay_on_top', default: false, - notify: function () { - if(!CC_JSB) { - this._sgNode.stayOnTop(this.stayOnTop); - this._sgNode.fontSize = this.fontSize; - this._sgNode.fontColor = this.fontColor; + notify () { + if (!CC_JSB) { + this._updateStayOnTop(); } } }, @@ -383,12 +269,12 @@ var EditBox = cc.Class({ */ tabIndex: { tooltip: CC_DEV && 'i18n:COMPONENT.editbox.tab_index', - get: function () { + get () { return this._tabIndex; }, - set: function (value) { + set (value) { this._tabIndex = value; - this._sgNode.setTabIndex(value); + this._impl.setTabIndex(value); } }, @@ -440,112 +326,239 @@ var EditBox = cc.Class({ InputMode: InputMode }, - _applyCapInset: function (sprite) { - var backgroundImage = this.backgroundImage; - sprite.setInsetTop(backgroundImage.insetTop); - sprite.setInsetBottom(backgroundImage.insetBottom); - sprite.setInsetRight(backgroundImage.insetRight); - sprite.setInsetLeft(backgroundImage.insetLeft); - }, - - _createSgNode: function() { - return new _ccsg.EditBox(cc.size(160, 40)); - }, - - _createBackgroundSprite: function() { - var sgNode = this._sgNode; - var bgSprite = new cc.Scale9Sprite(); - bgSprite.setRenderingType(cc.Scale9Sprite.RenderingType.SLICED); - if (this.backgroundImage) { - this.backgroundImage.ensureLoadTexture(); - bgSprite.setSpriteFrame(this.backgroundImage); - this._applyCapInset(bgSprite); - } - sgNode.initWithSizeAndBackgroundSprite(cc.size(160, 40), bgSprite); - return bgSprite; - }, - - _initSgNode: function() { - var sgNode = this._sgNode; - if(!CC_JSB) { - sgNode.createDomElementIfNeeded(); - } - + _init() { this._createBackgroundSprite(); + this._createLabels(); - if (CC_EDITOR && this._useOriginalSize) { - this.node.setContentSize(sgNode.getContentSize()); - this._useOriginalSize = false; - } else { - sgNode.setContentSize(this.node.getContentSize()); - } + let impl = this._impl = new EditBoxImpl(); - sgNode.inputMode = this.inputMode; - sgNode.maxLength = this.maxLength; + 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); - sgNode.string = this._string; - sgNode.fontSize = this.fontSize; - sgNode.fontColor = this.fontColor; - sgNode.placeholder = this.placeholder; - sgNode.placeholderFontSize = this.placeholderFontSize; - sgNode.placeholderFontColor = this.placeholderFontColor; - sgNode.inputFlag = this.inputFlag; - sgNode.returnType = this.returnType; - sgNode.setLineHeight(this.lineHeight); - sgNode.stayOnTop(this.stayOnTop); - sgNode.setTabIndex(this.tabIndex); + impl.setDelegate(this); - sgNode.setDelegate(this); + this._updateStayOnTop(); + this._updateString(this.string); + this._syncSize(); }, - editBoxEditingDidBegan: function() { + _updateStayOnTop () { + if (this.stayOnTop) { + this._hideLabels(); + } + else { + this._showLabels(); + } + this._impl.stayOnTop(this.stayOnTop); + }, + + _syncSize () { + let size = this.node.getContentSize(); + + this._background.node.setAnchorPoint(this.node.getAnchorPoint()); + this._background.node.setContentSize(size); + + this._updateLabelPosition(size); + this._impl.setSize(size.width, size.height); + }, + + _updateLabelPosition (size) { + let node = this.node; + let offx = -node.anchorX * node.width; + let offy = -node.anchorY * node.height; + + let placeholderLabel = this._placeholderLabel; + let textLabel = this._textLabel; + + textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); + placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); + placeholderLabel.lineHeight = size.height; + + placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height); + textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height); + + if (this.inputMode === InputMode.ANY){ + placeholderLabel.verticalAlign = cc.VerticalTextAlignment.TOP; + textLabel.verticalAlign = cc.VerticalTextAlignment.TOP; + textLabel.enableWrapText = true; + } + else { + placeholderLabel.verticalAlign = cc.VerticalTextAlignment.CENTER; + textLabel.verticalAlign = cc.VerticalTextAlignment.CENTER; + textLabel.enableWrapText = false; + } + }, + + _createBackgroundSprite() { + let background = this._background; + if (!background) { + let node = this.node.getChildByName('BACKGROUND_SPRITE'); + if (!node) { + node = new cc.Node('BACKGROUND_SPRITE'); + } + + background = node.getComponent(cc.Sprite); + if (!background) { + background = node.addComponent(cc.Sprite); + } + background.type = cc.Sprite.Type.SLICED; + + node.parent = this.node; + this._background = background; + } + background.spriteFrame = this.backgroundImage; + }, + + _createLabels () { + if (!this._textLabel) { + let node = this.node.getChildByName('TEXT_LABEL'); + if (!node) { + node = new cc.Node('TEXT_LABEL'); + } + node.color = this.fontColor; + node.parent = this.node; + node.setAnchorPoint(0, 1); + + let textLabel = node.getComponent(Label); + if (!textLabel) { + textLabel = node.addComponent(Label); + } + textLabel.overflow = Label.Overflow.CLAMP; + textLabel.fontSize = this.fontSize; + textLabel.lineHeight = this.lineHeight; + this._textLabel = textLabel; + } + + if (!this._placeholderLabel) { + let node = this.node.getChildByName('PLACEHOLDER_LABEL'); + if (!node) { + node = new cc.Node('PLACEHOLDER_LABEL'); + } + node.color = this.placeholderFontColor; + node.parent = this.node; + node.setAnchorPoint(0, 1); + + let placeholderLabel = node.getComponent(Label); + if (!placeholderLabel) { + placeholderLabel = node.addComponent(Label); + } + placeholderLabel.overflow = Label.Overflow.CLAMP; + placeholderLabel.fontSize = this.placeholderFontSize; + placeholderLabel.string = this.placeholder; + this._placeholderLabel = placeholderLabel; + } + }, + + _showLabels () { + this._textLabel.node.active = true; + this._placeholderLabel.node.active = true; + }, + + _hideLabels () { + this._textLabel.node.active = false; + this._placeholderLabel.node.active = false; + }, + + _updateString (text) { + let placeholderLabel = this._placeholderLabel; + let textLabel = this._textLabel; + + let displayText = text; + if (displayText === '') { + placeholderLabel.enabled = true; + textLabel.enabled = false; + } + else { + placeholderLabel.enabled = false; + textLabel.enabled = true; + + displayText = this._updateLabelStringStyle(displayText); + } + + textLabel.string = displayText; + this._impl.setString(text); + }, + + _updateLabelStringStyle (text) { + let inputFlag = this.inputFlag; + if (inputFlag === InputFlag.PASSWORD) { + let passwordString = ''; + let len = text.length; + for (let i = 0; i < len; ++i) { + passwordString += '\u25CF'; + } + text = passwordString; + } + else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { + text = text.toUpperCase(); + } + else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + text = capitalize(text); + } + else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) { + text = capitalizeFirstLetter(text); + } + + return text; + }, + + editBoxEditingDidBegan() { + this._hideLabels(); cc.Component.EventHandler.emitEvents(this.editingDidBegan, this); this.node.emit('editing-did-began', this); }, - editBoxEditingDidEnded: function() { + editBoxEditingDidEnded() { + this._showLabels(); cc.Component.EventHandler.emitEvents(this.editingDidEnded, this); this.node.emit('editing-did-ended', this); }, - editBoxTextChanged: function(editBox, text) { + editBoxTextChanged(text) { + this.string = text; cc.Component.EventHandler.emitEvents(this.textChanged, text, this); this.node.emit('text-changed', this); }, - editBoxEditingReturn: function() { + editBoxEditingReturn() { cc.Component.EventHandler.emitEvents(this.editingReturn, this); this.node.emit('editing-return', this); }, - onDestroy: function () { - return; - this._sgNode.setDelegate(null); + onDestroy () { + this._impl.setDelegate(null); }, - __preload: function() { + __preload() { if (!CC_EDITOR) { this._registerEvent(); } + this._init(); }, - _registerEvent: function () { + _registerEvent () { if(!CC_JSB) { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); } }, - _onTouchBegan: function(event) { - if (this._sgNode) { - this._sgNode._onTouchBegan(event.touch); + _onTouchBegan(event) { + if (this._impl) { + this._impl._onTouchBegan(event.touch); } event.stopPropagation(); }, - _onTouchEnded: function(event) { - if (this._sgNode) { - this._sgNode._onTouchEnded(); + _onTouchEnded(event) { + if (this._impl) { + this._impl._onTouchEnded(); } event.stopPropagation(); }, @@ -556,9 +569,9 @@ var EditBox = cc.Class({ * Note: only available on Web at the moment. * @method setFocus */ - setFocus: function() { - if(this._sgNode) { - this._sgNode.setFocus(); + setFocus() { + if(this._impl) { + this._impl.setFocus(); } }, @@ -568,12 +581,18 @@ var EditBox = cc.Class({ * Note: only available on Web at the moment. * @method isFocused */ - isFocused: function () { + isFocused () { var isFocused = false; - if (this._sgNode) { - isFocused = this._sgNode.isFocused(); + if (this._impl) { + isFocused = this._impl.isFocused(); } return isFocused; + }, + + update () { + if (this._impl) { + this._impl.update(); + } } }); diff --git a/cocos2d/core/components/editbox/CCEditBoxImpl.js b/cocos2d/core/components/editbox/CCEditBoxImpl.js new file mode 100644 index 0000000000..ff31cc710e --- /dev/null +++ b/cocos2d/core/components/editbox/CCEditBoxImpl.js @@ -0,0 +1,582 @@ +/*global _ccsg */ + +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2012 James Chen + Copyright (c) 2011-2012 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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. + ****************************************************************************/ + +const Utils = require('../../platform/utils'); + +const Types = require('./types'); +const InputMode = Types.InputMode; +const InputFlag = Types.InputFlag; +const KeyboardReturnType = Types.KeyboardReturnType; + +// https://segmentfault.com/q/1010000002914610 +let SCROLLY = 40; +let LEFT_PADDING = 2; +let DELAY_TIME = 400; +let FOCUS_DELAY_UC = 400; +let FOCUS_DELAY_FIREFOX = 0; + +let math = cc.vmath; +let _matrix = math.mat4.create(); +let _vec3 = cc.v3(); + +// polyfill +let polyfill = { + zoomInvalid: false +} +if (cc.sys.OS_ANDROID === cc.sys.os && + (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU || + cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { + polyfill.zoomInvalid = true; +} + +let EditBoxImpl = cc.Class({ + ctor () { + this._delegate = null; + this._inputMode = -1; + this._inputFlag = -1; + this._returnType = KeyboardReturnType.DEFAULT; + this._maxLength = 50; + this._text = ''; + this._placeholderText = ''; + this._alwaysOnTop = false; + this._size = cc.size(); + this._node = null; + this._editing = false; + + this.__fullscreen = false; + this.__autoResize = false; + this.__rotateScreen = false; + this.__orientationChanged = null; + }, + + setTabIndex (index) { + if (this._edTxt) { + this._edTxt.tabIndex = index; + } + }, + + setFocus () { + if (this._edTxt) { + this._edTxt.focus(); + } + }, + + isFocused() { + if (this._edTxt) { + return document.activeElement === this._edTxt; + } + cc.warnID(4700); + return false; + }, + + stayOnTop (flag) { + if(this._alwaysOnTop === flag) return; + + this._alwaysOnTop = flag; + + if (flag) { + this._edTxt.style.display = ''; + } else { + this._edTxt.style.display = 'none'; + } + }, + + setMaxLength (maxLength) { + 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; + this._edTxt.maxLength = maxLength; + } + }, + + setString (text) { + this._text = text; + this._edTxt.value = text; + }, + + getString () { + return this._text; + }, + + setDelegate (delegate) { + this._delegate = delegate; + }, + + setInputMode (inputMode) { + if (this._inputMode === inputMode) return; + + this._inputMode = inputMode; + + if (inputMode === InputMode.ANY) { + this._createDomTextArea(); + } + else { + this._createDomInput(); + } + + this._updateDomInputType(); + this._updateSize(this._size.width, this._size.height); + + this._updateMatrix(); + }, + + setInputFlag (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'; + } + + this._edTxt.style.textTransform = textTransform; + }, + + setReturnType (returnType) { + this._returnType = returnType; + this._updateDomInputType(); + }, + + setFontSize (fontSize) { + this._edFontSize = fontSize || this._edFontSize; + this._edTxt.style.fontSize = this._edFontSize + 'px'; + }, + + setFontColor (color) { + this._textColor = color; + this._edTxt.style.color = cc.colorToHex(color); + }, + + setSize (width, height) { + this._size.width = width; + this._size.height = height; + this._updateSize(width, height); + }, + + setNode (node) { + this._node = node; + }, + + update () { + if (this._editing) { + this._updateMatrix(); + } + }, + + _onTouchBegan (touch) { + }, + + _onTouchEnded () { + this._beginEditing(); + }, + + _beginEditing () { + let self = this; + if (!self._alwaysOnTop) { + if (self._edTxt.style.display === 'none') { + self._edTxt.style.display = ''; + + function startFocus () { + self._edTxt.focus(); + } + + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { + setTimeout(startFocus, FOCUS_DELAY_UC); + } + else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) { + setTimeout(startFocus, FOCUS_DELAY_FIREFOX); + } + else { + startFocus(); + } + } + } + + if (cc.sys.isMobile && !self._editing) { + // Pre adaptation and + self._beginEditingOnMobile(self._editBox); + } + self._editing = true; + }, + + _endEditing () { + if (!this._alwaysOnTop) { + this._edTxt.style.display = 'none'; + } + if (cc.sys.isMobile && this._editing) { + let self = this; + // Delay end editing adaptation to ensure virtual keyboard is disapeared + setTimeout(function () { + self._endEditingOnMobile(); + }, DELAY_TIME); + } + this._editing = false; + }, + + _updateDomInputType () { + let inputMode = this._inputMode; + let edTxt = this._edTxt; + + 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'; + } + } + + if (this._inputFlag === InputFlag.PASSWORD) { + type = 'password'; + } + + edTxt.type = type; + }, + + _updateSize (newWidth, newHeight) { + let edTxt = this._edTxt; + if (!edTxt) return; + + edTxt.style.width = newWidth + 'px'; + edTxt.style.height = newHeight + 'px'; + }, + + _updateMatrix () { + if (!this._edTxt) return; + + let node = this._node, + scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; + let dpr = cc.view._devicePixelRatio; + + node.getWorldMatrix(_matrix); + let contentSize = node._contentSize; + _vec3.x = -node._anchorPoint.x * contentSize.width; + _vec3.y = -node._anchorPoint.y * contentSize.height; + + math.mat4.translate(_matrix, _matrix, _vec3); + + scaleX /= dpr; + scaleY /= dpr; + + let container = cc.game.container; + let a = _matrix.m00 * scaleX, b = _matrix.m01, c = _matrix.m04, d = _matrix.m05 * scaleY; + + let offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); + let offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); + let tx = _matrix.m12 * scaleX + offsetX, ty = _matrix.m13 * scaleY + offsetY; + + if (polyfill.zoomInvalid) { + this._updateSize(this._size.width * a, this._size.height * d); + a = 1; + d = 1; + } + + let matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; + this._edTxt.style['transform'] = matrix; + this._edTxt.style['-webkit-transform'] = matrix; + this._edTxt.style['transform-origin'] = '0px 100% 0px'; + this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px'; + }, + + _adjustEditBoxPosition () { + this._node.getWorldMatrix(_matrix); + let y = _matrix.m13; + let windowHeight = cc.visibleRect.height; + let windowWidth = cc.visibleRect.width; + let factor = 0.5; + if (windowWidth > windowHeight) { + factor = 0.7; + } + setTimeout(function() { + 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); + } +}); + +let _p = EditBoxImpl.prototype; + +// Called before editbox focus to register cc.view status +_p._beginEditingOnMobile = function () { + this.__orientationChanged = () => { + this._adjustEditBoxPosition(); + }; + + window.addEventListener('orientationchange', this.__orientationChanged); + + if (cc.view.isAutoFullScreenEnabled()) { + this.__fullscreen = true; + cc.view.enableAutoFullScreen(false); + cc.screen.exitFullScreen(); + } else { + this.__fullscreen = false; + } + this.__autoResize = cc.view.__resizeWithBrowserSize; + cc.view.resizeWithBrowserSize(false); +}; + +// Called after keyboard disappeared to readapte the game view +_p._endEditingOnMobile = function () { + if (this.__rotateScreen) { + cc.container.style['-webkit-transform'] = 'rotate(90deg)'; + cc.container.style.transform = 'rotate(90deg)'; + + let view = cc.view; + let width = view._originalDesignResolutionSize.width; + let height = view._originalDesignResolutionSize.height; + if (width > 0) { + view.setDesignResolutionSize(width, height, view._resolutionPolicy); + } + this.__rotateScreen = false; + } + + window.removeEventListener('orientationchange', this.__orientationChanged); + + window.scrollTo(0, 0); + if(this.__fullscreen) { + cc.view.enableAutoFullScreen(true); + } + if (this.__autoResize) { + cc.view.resizeWithBrowserSize(true); + } +}; + +// Called after editbox focus to readapte the game view +_p._onFocusOnMobile = function (editBox) { + if (cc.view._isRotated) { + cc.container.style['-webkit-transform'] = 'rotate(0deg)'; + cc.container.style.transform = 'rotate(0deg)'; + cc.view._isRotated = false; + let policy = cc.view.getResolutionPolicy(); + policy.apply(cc.view, cc.view.getDesignResolutionSize()); + cc.view._isRotated = true; + //use window scrollTo to adjust the input area + window.scrollTo(35, 35); + this.__rotateScreen = true; + } else { + this.__rotateScreen = false; + } + this._adjustEditBoxPosition(); +}; + +_p._createDomInput = function () { + this.removeDom(); + + let self = this; + let tmpEdTxt = this._edTxt = document.createElement('input'); + 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.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.style.className = "cocosEditBox"; + tmpEdTxt.style.fontFamily = 'Arial'; + + tmpEdTxt.addEventListener('input', function () { + if (this.value.length > this._maxLength) { + this.value = this.value.slice(0, this._maxLength); + } + + if (self._delegate && self._delegate.editBoxTextChanged) { + if (self._text !== this.value) { + self._text = this.value; + self._delegate.editBoxTextChanged(self._text); + } + } + }); + tmpEdTxt.addEventListener('keypress', function (e) { + if (e.keyCode === cc.KEY.enter) { + e.stopPropagation(); + e.preventDefault(); + + self._text = this.value; + + self._endEditing(); + if (self._delegate && self._delegate.editBoxEditingReturn) { + self._delegate.editBoxEditingReturn(); + } + cc._canvas.focus(); + } + }); + + tmpEdTxt.addEventListener('focus', function () { + this.style.fontSize = self._edFontSize + 'px'; + this.style.color = cc.colorToHex(self._textColor); + + if (cc.sys.isMobile) { + self._onFocusOnMobile(); + } + + if (self._delegate && self._delegate.editBoxEditingDidBegan) { + self._delegate.editBoxEditingDidBegan(); + } + }); + tmpEdTxt.addEventListener('blur', function () { + self._text = this.value; + + if (self._delegate && self._delegate.editBoxEditingDidEnded) { + self._delegate.editBoxEditingDidEnded(); + } + + self._endEditing(); + }); + + this._addDomToGameContainer(); + + return tmpEdTxt; +}; + +_p._createDomTextArea = function () { + this.removeDom(); + + let self = this; + let 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.overflow_y = 'scroll'; + tmpEdTxt.style.display = 'none'; + tmpEdTxt.style.position = "absolute"; + tmpEdTxt.style.bottom = "0px"; + tmpEdTxt.style.left = LEFT_PADDING + "px"; + tmpEdTxt.style.className = "cocosEditBox"; + tmpEdTxt.style.fontFamily = 'Arial'; + + tmpEdTxt.addEventListener('input', function () { + if (this.value.length > this._maxLength) { + this.value = this.value.slice(0, this._maxLength); + } + + if (self._delegate && self._delegate.editBoxTextChanged) { + if (self._text !== this.value) { + self._text = this.value; + self._delegate.editBoxTextChanged(self._text); + } + } + }); + + tmpEdTxt.addEventListener('focus', function () { + this.style.fontSize = self._edFontSize + 'px'; + this.style.color = cc.colorToHex(self._textColor); + + if (cc.sys.isMobile) { + self._onFocusOnMobile(); + } + + if (self._delegate && self._delegate.editBoxEditingDidBegan) { + self._delegate.editBoxEditingDidBegan(); + } + + }); + tmpEdTxt.addEventListener('keypress', function (e) { + if (e.keyCode === cc.KEY.enter) { + e.stopPropagation(); + + if (self._delegate && self._delegate.editBoxEditingReturn) { + self._delegate.editBoxEditingReturn(); + } + } + }); + tmpEdTxt.addEventListener('blur', function () { + self._text = this.value; + + if (self._delegate && self._delegate.editBoxEditingDidEnded) { + self._delegate.editBoxEditingDidEnded(); + } + + self._endEditing(); + }); + + this._addDomToGameContainer(); + return tmpEdTxt; +}; + +_p._addDomToGameContainer = function () { + cc.game.container.appendChild(this._edTxt); +}; + +_p.removeDom = function () { + let edTxt = this._edTxt; + if (edTxt) { + let hasChild = Utils.contains(cc.game.container, edTxt); + if (hasChild) { + cc.game.container.removeChild(edTxt); + } + } + this._edTxt = null; +}; + +module.exports = EditBoxImpl; diff --git a/cocos2d/core/components/editbox/types.js b/cocos2d/core/components/editbox/types.js new file mode 100644 index 0000000000..fa331cad75 --- /dev/null +++ b/cocos2d/core/components/editbox/types.js @@ -0,0 +1,157 @@ +/** + * !#en Enum for keyboard return types + * !#zh 键盘的返回键类型 + * @readonly + * @enum EditBox.KeyboardReturnType + */ +let KeyboardReturnType = cc.Enum({ + /** + * !#en TODO + * !#zh 默认 + * @property {Number} DEFAULT + */ + DEFAULT: 0, + /** + * !#en TODO + * !#zh 完成类型 + * @property {Number} DONE + */ + DONE: 1, + /** + * !#en TODO + * !#zh 发送类型 + * @property {Number} SEND + */ + SEND: 2, + /** + * !#en TODO + * !#zh 搜索类型 + * @property {Number} SEARCH + */ + SEARCH: 3, + /** + * !#en TODO + * !#zh 跳转类型 + * @property {Number} GO + */ + GO: 4 +}); + +/** + * !#en The EditBox's InputMode defines the type of text that the user is allowed to enter. + * !#zh 输入模式 + * @readonly + * @enum EditBox.InputMode + */ +let InputMode = cc.Enum({ + /** + * !#en TODO + * !#zh 用户可以输入任何文本,包括换行符。 + * @property {Number} ANY + */ + ANY: 0, + /** + * !#en The user is allowed to enter an e-mail address. + * !#zh 允许用户输入一个电子邮件地址。 + * @property {Number} EMAIL_ADDR + */ + EMAIL_ADDR: 1, + /** + * !#en The user is allowed to enter an integer value. + * !#zh 允许用户输入一个整数值。 + * @property {Number} NUMERIC + */ + NUMERIC: 2, + /** + * !#en The user is allowed to enter a phone number. + * !#zh 允许用户输入一个电话号码。 + * @property {Number} PHONE_NUMBER + */ + PHONE_NUMBER: 3, + /** + * !#en The user is allowed to enter a URL. + * !#zh 允许用户输入一个 URL。 + * @property {Number} URL + */ + URL: 4, + /** + * !#en + * The user is allowed to enter a real number value. + * This extends kEditBoxInputModeNumeric by allowing a decimal point. + * !#zh + * 允许用户输入一个实数。 + * @property {Number} DECIMAL + */ + DECIMAL: 5, + /** + * !#en The user is allowed to enter any text, except for line breaks. + * !#zh 除了换行符以外,用户可以输入任何文本。 + * @property {Number} SINGLE_LINE + */ + SINGLE_LINE: 6 +}); + +/** + * !#en Enum for the EditBox's input flags + * !#zh 定义了一些用于设置文本显示和文本格式化的标志位。 + * @readonly + * @enum EditBox.InputFlag + */ +let InputFlag = cc.Enum({ + /** + * !#en + * Indicates that the text entered is confidential data that should be + * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. + * !#zh + * 表明输入的文本是保密的数据,任何时候都应该隐藏起来,它隐含了 EDIT_BOX_INPUT_FLAG_SENSITIVE。 + * @property {Number} PASSWORD + */ + PASSWORD: 0, + /** + * !#en + * Indicates that the text entered is sensitive data that the + * implementation must never store into a dictionary or table for use + * in predictive, auto-completing, or other accelerated input schemes. + * A credit card number is an example of sensitive data. + * !#zh + * 表明输入的文本是敏感数据,它禁止存储到字典或表里面,也不能用来自动补全和提示用户输入。 + * 一个信用卡号码就是一个敏感数据的例子。 + * @property {Number} SENSITIVE + */ + SENSITIVE: 1, + /** + * !#en + * This flag is a hint to the implementation that during text editing, + * the initial letter of each word should be capitalized. + * !#zh + * 这个标志用来指定在文本编辑的时候,是否把每一个单词的首字母大写。 + * @property {Number} INITIAL_CAPS_WORD + */ + INITIAL_CAPS_WORD: 2, + /** + * !#en + * This flag is a hint to the implementation that during text editing, + * the initial letter of each sentence should be capitalized. + * !#zh + * 这个标志用来指定在文本编辑是否每个句子的首字母大写。 + * @property {Number} INITIAL_CAPS_SENTENCE + */ + INITIAL_CAPS_SENTENCE: 3, + /** + * !#en Capitalize all characters automatically. + * !#zh 自动把输入的所有字符大写。 + * @property {Number} INITIAL_CAPS_ALL_CHARACTERS + */ + INITIAL_CAPS_ALL_CHARACTERS: 4, + /** + * Don't do anything with the input text. + * @property {Number} DEFAULT + */ + DEFAULT: 5 +}); + +module.exports = { + KeyboardReturnType: KeyboardReturnType, + InputMode: InputMode, + InputFlag: InputFlag +} diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index 00ac275bb8..fa3104f8ed 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -43,7 +43,7 @@ var components = [ require('./CCPageView'), require('./CCSlider'), require('./CCLayout'), - // require('./CCEditBox'), + require('./editbox/CCEditBox'), // require('./CCVideoPlayer'), // require('./CCWebView'), require('./CCSpriteDistortion'), diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js deleted file mode 100644 index 1dd914b28f..0000000000 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ /dev/null @@ -1,1248 +0,0 @@ -/*global _ccsg */ - -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2012 James Chen - Copyright (c) 2011-2012 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - 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. - ****************************************************************************/ - -// https://segmentfault.com/q/1010000002914610 -var SCROLLY = 40; -var LEFT_PADDING = 2; -var DELAY_TIME = 400; -var FOCUS_DELAY_UC = 400; -var FOCUS_DELAY_FIREFOX = 0; -var Utils = require('../platform/utils'); - -function adjustEditBoxPosition (editBox) { - var worldPos = editBox.convertToWorldSpace(cc.p(0,0)); - var windowHeight = cc.visibleRect.height; - var windowWidth = cc.visibleRect.width; - var factor = 0.5; - if(windowWidth > windowHeight) { - factor = 0.7; - } - setTimeout(function() { - if(window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) { - var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY; - if (scrollOffset < 35) scrollOffset = 35; - if (scrollOffset > 320) scrollOffset = 320; - window.scrollTo(scrollOffset, scrollOffset); - } - }, DELAY_TIME); -} - -var capitalize = function(string) { - return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); -}; - -function capitalizeFirstLetter(string) { - return string.charAt(0).toUpperCase() + string.slice(1); -} -/** - * Enum for keyboard return types - * @readonly - * @enum cc.EditBox.KeyboardReturnType - */ -var KeyboardReturnType = cc.Enum({ - /** - * @property {Number} DEFAULT - */ - DEFAULT: 0, - /** - * @property {Number} DONE - */ - DONE: 1, - /** - * @property {Number} SEND - */ - SEND: 2, - /** - * @property {Number} SEARCH - */ - SEARCH: 3, - /** - * @property {Number} GO - */ - GO: 4 -}); - -/** - * The EditBox's InputMode defines the type of text that the user is allowed to enter - * @readonly - * @enum {number} - * @memberof cc.EditBox.InputMode - */ -var InputMode = cc.Enum({ - - /** - * @property {Number} ANY - */ - ANY: 0, - - /** - * The user is allowed to enter an e-mail address. - * @property {Number} EMAIL_ADDR - */ - EMAIL_ADDR: 1, - - /** - * The user is allowed to enter an integer value. - * @property {Number} NUMERIC - */ - NUMERIC: 2, - - /** - * The user is allowed to enter a phone number. - * @property {Number} PHONE_NUMBER - */ - PHONE_NUMBER: 3, - - /** - * The user is allowed to enter a URL. - * @property {Number} URL - */ - URL: 4, - - /** - * The user is allowed to enter a real number value. - * This extends kEditBoxInputModeNumeric by allowing a decimal point. - * @property {Number} DECIMAL - */ - DECIMAL: 5, - - /** - * The user is allowed to enter any text, except for line breaks. - * @property {Number} SINGLE_LINE - */ - SINGLE_LINE: 6 -}); - -/** - * Enum for the EditBox's input flags - * @readonly - * @enum cc.EditBox.InputFlag - */ -var InputFlag = cc.Enum({ - /** - * Indicates that the text entered is confidential data that should be - * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. - * - * @property {Number} PASSWORD - */ - PASSWORD: 0, - - /** - * Indicates that the text entered is sensitive data that the - * implementation must never store into a dictionary or table for use - * in predictive, auto-completing, or other accelerated input schemes. - * A credit card number is an example of sensitive data. - * - * @property {Number} SENSITIVE - */ - SENSITIVE: 1, - - /** - * This flag is a hint to the implementation that during text editing, - * the initial letter of each word should be capitalized. - * - * @property {Number} INITIAL_CAPS_WORD - */ - INITIAL_CAPS_WORD: 2, - - /** - * This flag is a hint to the implementation that during text editing, - * the initial letter of each sentence should be capitalized. - * - * @property {Number} INITIAL_CAPS_SENTENCE - */ - INITIAL_CAPS_SENTENCE: 3, - - /** - * Capitalize all characters automatically. - * - * @property {Number} INITIAL_CAPS_ALL_CHARACTERS - */ - INITIAL_CAPS_ALL_CHARACTERS: 4, - - /** - * Don't do anything with the input text. - * @property {Number} DEFAULT - */ - DEFAULT: 5 -}); - -/** - * @class - * @extends cc._Class - */ -cc.EditBoxDelegate = cc._Class.extend({ - /** - * This method is called when an edit box gains focus after keyboard is shown. - * @param {cc.EditBox} sender - */ - editBoxEditingDidBegan: function (sender) { - }, - - /** - * This method is called when an edit box loses focus after keyboard is hidden. - * @param {cc.EditBox} sender - */ - editBoxEditingDidEnded: function (sender) { - }, - - /** - * This method is called when the edit box text was changed. - * @param {cc.EditBox} sender - * @param {String} text - */ - editBoxTextChanged: function (sender, text) { - }, - - /** - * This method is called when the return button was pressed. - * @param {cc.EditBox} sender - */ - editBoxEditingReturn: function (sender) { - } -}); - - -/** - *

cc.EditBox is a brief Class for edit box.
- * You can use this widget to gather small amounts of text from the user.

- * - */ -_ccsg.EditBox = _ccsg.Node.extend({ - _backgroundSprite: null, - _delegate: null, - _editBoxInputMode: InputMode.ANY, - _editBoxInputFlag: InputFlag.DEFAULT, - _keyboardReturnType: KeyboardReturnType.DEFAULT, - _maxLength: 50, - _text: '', - _placeholderText: '', - _alwaysOnTop: false, - _placeholderFontName: '', - _placeholderFontSize: 14, - __fullscreen: false, - __autoResize: false, - _placeholderColor: null, - _className: 'EditBox', - - ctor: function (size, normal9SpriteBg) { - _ccsg.Node.prototype.ctor.call(this); - - this._textColor = cc.Color.WHITE; - this._placeholderColor = cc.Color.GRAY; - - this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg); - this._renderCmd._createLabels(); - }, - - _createRenderCmd: function () { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - return new _ccsg.EditBox.CanvasRenderCmd(this); - } else { - return new _ccsg.EditBox.WebGLRenderCmd(this); - } - }, - - setContentSize: function (width, height) { - if (width.width !== undefined && width.height !== undefined) { - height = width.height; - width = width.width; - } - _ccsg.Node.prototype.setContentSize.call(this, width, height); - this._updateEditBoxSize(width, height); - }, - - setVisible: function ( visible ) { - _ccsg.Node.prototype.setVisible.call(this, visible); - this._renderCmd.updateVisibility(); - }, - - createDomElementIfNeeded: function () { - if(!this._renderCmd._edTxt) { - this._renderCmd._createDomTextArea(); - } - }, - - setTabIndex: function(index) { - if(this._renderCmd._edTxt) { - this._renderCmd._edTxt.tabIndex = index; - } - }, - - getTabIndex: function() { - if(this._renderCmd._edTxt) { - return this._renderCmd._edTxt.tabIndex; - } - cc.warnID(4700); - return -1; - }, - - setFocus: function() { - if(this._renderCmd._edTxt) { - this._renderCmd._edTxt.focus(); - } - }, - - isFocused: function() { - if(this._renderCmd._edTxt) { - return document.activeElement === this._renderCmd._edTxt; - } - cc.warnID(4700); - return false; - }, - - stayOnTop: function (flag) { - if(this._alwaysOnTop === flag) return; - - this._alwaysOnTop = flag; - this._renderCmd.stayOnTop(this._alwaysOnTop); - }, - - cleanup: function () { - this._super(); - this._renderCmd.removeDom(); - }, - - _onTouchBegan: function (touch) { - var touchPoint = touch.getLocation(); - var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height); - var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint)); - if(hitted) { - return true; - } - else { - this._renderCmd._endEditing(); - return false; - } - }, - - _onTouchEnded: function () { - this._renderCmd._beginEditing(); - }, - - _updateBackgroundSpriteSize: function (width, height) { - if(this._backgroundSprite) { - this._backgroundSprite.setContentSize(width, height); - } - }, - - _updateEditBoxSize: function(size, height) { - var newWidth = (typeof size.width === 'number') ? size.width : size; - var newHeight = (typeof size.height === 'number') ? size.height : height; - - this._updateBackgroundSpriteSize(newWidth, newHeight); - this._renderCmd.updateSize(newWidth, newHeight); - }, - - setLineHeight: function (lineHeight) { - this._renderCmd.setLineHeight(lineHeight); - }, - - setFont: function (fontName, fontSize) { - this._renderCmd.setFont(fontName, fontSize); - }, - - _setFont: function (fontStyle) { - this._renderCmd._setFont(fontStyle); - }, - - getBackgroundSprite: function() { - return this._backgroundSprite; - }, - - setFontName: function (fontName) { - this._renderCmd.setFontName(fontName); - }, - - setFontSize: function (fontSize) { - this._renderCmd.setFontSize(fontSize); - }, - - setString: function (text) { - if (text.length >= this._maxLength) { - text = text.slice(0, this._maxLength); - } - this._text = text; - this._renderCmd.setString(text); - }, - - setFontColor: function (color) { - this._textColor = color; - this._renderCmd.setFontColor(color); - }, - - setMaxLength: function (maxLength) { - 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; - this._renderCmd.setMaxLength(maxLength); - } - }, - - getMaxLength: function () { - return this._maxLength; - }, - - setPlaceHolder: function (text) { - if (text !== null) { - this._renderCmd.setPlaceHolder(text); - this._placeholderText = text; - } - }, - - setPlaceholderFont: function (fontName, fontSize) { - this._placeholderFontName = fontName; - this._placeholderFontSize = fontSize; - this._renderCmd._updateDOMPlaceholderFontStyle(); - }, - - _setPlaceholderFont: function (fontStyle) { - var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); - if (res) { - this._placeholderFontName = res[2]; - this._placeholderFontSize = parseInt(res[1]); - this._renderCmd._updateDOMPlaceholderFontStyle(); - } - }, - - setPlaceholderFontName: function (fontName) { - this._placeholderFontName = fontName; - this._renderCmd._updateDOMPlaceholderFontStyle(); - }, - - setPlaceholderFontSize: function (fontSize) { - this._placeholderFontSize = fontSize; - this._renderCmd._updateDOMPlaceholderFontStyle(); - }, - - setPlaceholderFontColor: function (color) { - this._placeholderColor = color; - this._renderCmd.setPlaceholderFontColor(color); - }, - - setInputFlag: function (inputFlag) { - this._editBoxInputFlag = inputFlag; - this._renderCmd.setInputFlag(inputFlag); - }, - - getString: function () { - return this._text; - }, - - initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) { - if(this._backgroundSprite) { - this._backgroundSprite.removeFromParent(); - } - this._backgroundSprite = normal9SpriteBg; - _ccsg.Node.prototype.setContentSize.call(this, size); - - if(this._backgroundSprite && !this._backgroundSprite.parent) { - this._backgroundSprite.setAnchorPoint(cc.p(0, 0)); - this.addChild(this._backgroundSprite); - - this._updateBackgroundSpriteSize(size.width, size.height); - } - - - this.x = 0; - this.y = 0; - return true; - }, - - setDelegate: function (delegate) { - this._delegate = delegate; - }, - - getPlaceHolder: function () { - return this._placeholderText; - }, - - setInputMode: function (inputMode) { - if (this._editBoxInputMode === inputMode) return; - - var oldText = this.getString(); - this._editBoxInputMode = inputMode; - - this._renderCmd.setInputMode(inputMode); - this._renderCmd.transform(); - - this.setString(oldText); - this._renderCmd._updateLabelPosition(this.getContentSize()); - }, - - setReturnType: function (returnType) { - this._keyboardReturnType = returnType; - this._renderCmd._updateDomInputType(); - }, - - initWithBackgroundColor: function (size, bgColor) { - this._edWidth = size.width; - this.dom.style.width = this._edWidth.toString() + 'px'; - this._edHeight = size.height; - this.dom.style.height = this._edHeight.toString() + 'px'; - this.dom.style.backgroundColor = cc.colorToHex(bgColor); - } -}); - -var _p = _ccsg.EditBox.prototype; - -// Extended properties -cc.defineGetterSetter(_p, 'font', null, _p._setFont); -cc.defineGetterSetter(_p, 'fontName', null, _p.setFontName); -cc.defineGetterSetter(_p, 'fontSize', null, _p.setFontSize); -cc.defineGetterSetter(_p, 'fontColor', null, _p.setFontColor); -cc.defineGetterSetter(_p, 'string', _p.getString, _p.setString); -cc.defineGetterSetter(_p, 'maxLength', _p.getMaxLength, _p.setMaxLength); -cc.defineGetterSetter(_p, 'placeholder', _p.getPlaceHolder, _p.setPlaceHolder); -cc.defineGetterSetter(_p, 'placeholderFont', null, _p._setPlaceholderFont); -cc.defineGetterSetter(_p, 'placeholderFontName', null, _p.setPlaceholderFontName); -cc.defineGetterSetter(_p, 'placeholderFontSize', null, _p.setPlaceholderFontSize); -cc.defineGetterSetter(_p, 'placeholderFontColor', null, _p.setPlaceholderFontColor); -cc.defineGetterSetter(_p, 'inputFlag', null, _p.setInputFlag); -cc.defineGetterSetter(_p, 'delegate', null, _p.setDelegate); -cc.defineGetterSetter(_p, 'inputMode', null, _p.setInputMode); -cc.defineGetterSetter(_p, 'returnType', null, _p.setReturnType); - -_p = null; - -_ccsg.EditBox.InputMode = InputMode; -_ccsg.EditBox.InputFlag = InputFlag; -_ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; - -(function (editbox) { - editbox._polyfill = { - zoomInvalid: false - }; - - if (cc.sys.OS_ANDROID === cc.sys.os - && (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU - || cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { - editbox._polyfill.zoomInvalid = true; - } -})(_ccsg.EditBox); - -(function (polyfill) { - var EditBoxImpl = function () { - }; - - var proto = EditBoxImpl.prototype = Object.create(Object.prototype); - - proto.updateMatrix = function () { - if (!this._edTxt) return; - - var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; - var dpr = cc.view._devicePixelRatio; - var t = this._worldTransform; - - scaleX /= dpr; - scaleY /= dpr; - - var container = cc.game.container; - var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY; - - var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); - var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); - var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY; - - if (polyfill.zoomInvalid) { - this.updateSize(node._contentSize.width * a, node._contentSize.height * d); - a = 1; - d = 1; - } - - var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; - this._edTxt.style['transform'] = matrix; - this._edTxt.style['-webkit-transform'] = matrix; - this._edTxt.style['transform-origin'] = '0px 100% 0px'; - this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px'; - }; - - proto.updateVisibility = function () { - if (!this._edTxt) return; - - if (this._node.visible) { - this._edTxt.style.visibility = 'visible'; - } else { - this._edTxt.style.visibility = 'hidden'; - } - }; - - proto.stayOnTop = function (flag) { - if(flag) { - this._removeLabels(); - this._edTxt.style.display = ''; - } else { - this._createLabels(); - this._edTxt.style.display = 'none'; - this._showLabels(); - } - }; - - // Called before editbox focus to register cc.view status - proto._beginEditingOnMobile = function (editBox) { - this.__orientationChanged = function () { - adjustEditBoxPosition(editBox); - }; - - window.addEventListener('orientationchange', this.__orientationChanged); - - if (cc.view.isAutoFullScreenEnabled()) { - this.__fullscreen = true; - cc.view.enableAutoFullScreen(false); - cc.screen.exitFullScreen(); - } else { - this.__fullscreen = false; - } - this.__autoResize = cc.view.__resizeWithBrowserSize; - cc.view.resizeWithBrowserSize(false); - }; - // Called after keyboard disappeared to readapte the game view - proto._endEditingOnMobile = function () { - if (this.__rotateScreen) { - cc.container.style['-webkit-transform'] = 'rotate(90deg)'; - cc.container.style.transform = 'rotate(90deg)'; - - var view = cc.view; - var width = view._originalDesignResolutionSize.width; - var height = view._originalDesignResolutionSize.height; - if (width > 0) { - view.setDesignResolutionSize(width, height, view._resolutionPolicy); - } - this.__rotateScreen = false; - } - - window.removeEventListener('orientationchange', this.__orientationChanged); - - window.scrollTo(0, 0); - if(this.__fullscreen) { - cc.view.enableAutoFullScreen(true); - } - if (this.__autoResize) { - cc.view.resizeWithBrowserSize(true); - } - }; - // Called after editbox focus to readapte the game view - proto._onFocusOnMobile = function (editBox) { - if (cc.view._isRotated) { - cc.container.style['-webkit-transform'] = 'rotate(0deg)'; - cc.container.style.transform = 'rotate(0deg)'; - cc.view._isRotated = false; - var policy = cc.view.getResolutionPolicy(); - policy.apply(cc.view, cc.view.getDesignResolutionSize()); - cc.view._isRotated = true; - //use window scrollTo to adjust the input area - window.scrollTo(35, 35); - this.__rotateScreen = true; - } else { - this.__rotateScreen = false; - } - adjustEditBoxPosition(editBox); - }; - - - - proto._createDomInput = function () { - this.removeDom(); - - var thisPointer = this; - var tmpEdTxt = this._edTxt = document.createElement('input'); - 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.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.style.className = "cocosEditBox"; - - tmpEdTxt.addEventListener('input', function () { - var editBox = thisPointer._editBox; - - - if (this.value.length > this.maxLength) { - this.value = this.value.slice(0, this.maxLength); - } - - if (editBox._delegate && editBox._delegate.editBoxTextChanged) { - if (editBox._text !== this.value) { - editBox._text = this.value; - thisPointer._updateDomTextCases(); - editBox._delegate.editBoxTextChanged(editBox, editBox._text); - } - } - }); - tmpEdTxt.addEventListener('keypress', function (e) { - var editBox = thisPointer._editBox; - - if (e.keyCode === cc.KEY.enter) { - e.stopPropagation(); - e.preventDefault(); - if(this.value === '') { - this.style.fontSize = editBox._placeholderFontSize + 'px'; - this.style.color = cc.colorToHex(editBox._placeholderColor); - } - - editBox._text = this.value; - thisPointer._updateDomTextCases(); - - thisPointer._endEditing(); - if (editBox._delegate && editBox._delegate.editBoxEditingReturn) { - editBox._delegate.editBoxEditingReturn(editBox); - } - cc._canvas.focus(); - } - }); - - tmpEdTxt.addEventListener('focus', function () { - var editBox = thisPointer._editBox; - this.style.fontSize = thisPointer._edFontSize + 'px'; - this.style.color = cc.colorToHex(editBox._textColor); - thisPointer._hiddenLabels(); - - if (cc.sys.isMobile) { - thisPointer._onFocusOnMobile(editBox); - } - - if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { - editBox._delegate.editBoxEditingDidBegan(editBox); - } - }); - tmpEdTxt.addEventListener('blur', function () { - var editBox = thisPointer._editBox; - editBox._text = this.value; - thisPointer._updateDomTextCases(); - - if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { - editBox._delegate.editBoxEditingDidEnded(editBox); - } - - if (this.value === '') { - this.style.fontSize = editBox._placeholderFontSize + 'px'; - this.style.color = cc.colorToHex(editBox._placeholderColor); - } - thisPointer._endEditing(); - }); - - this._addDomToGameContainer(); - - return tmpEdTxt; - }; - - proto._createDomTextArea = function () { - this.removeDom(); - - var thisPointer = this; - var 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.overflow_y = 'scroll'; - tmpEdTxt.style.display = 'none'; - tmpEdTxt.style.position = "absolute"; - tmpEdTxt.style.bottom = "0px"; - tmpEdTxt.style.left = LEFT_PADDING + "px"; - tmpEdTxt.style.className = "cocosEditBox"; - - tmpEdTxt.addEventListener('input', function () { - if (this.value.length > this.maxLength) { - this.value = this.value.slice(0, this.maxLength); - } - - var editBox = thisPointer._editBox; - if (editBox._delegate && editBox._delegate.editBoxTextChanged) { - if(editBox._text.toLowerCase() !== this.value.toLowerCase()) { - editBox._text = this.value; - thisPointer._updateDomTextCases(); - editBox._delegate.editBoxTextChanged(editBox, editBox._text); - } - } - }); - - tmpEdTxt.addEventListener('focus', function () { - var editBox = thisPointer._editBox; - thisPointer._hiddenLabels(); - - this.style.fontSize = thisPointer._edFontSize + 'px'; - this.style.color = cc.colorToHex(editBox._textColor); - - if (cc.sys.isMobile) { - thisPointer._onFocusOnMobile(editBox); - } - - if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { - editBox._delegate.editBoxEditingDidBegan(editBox); - } - - }); - tmpEdTxt.addEventListener('keypress', function (e) { - var editBox = thisPointer._editBox; - - if (e.keyCode === cc.KEY.enter) { - e.stopPropagation(); - - if (editBox._delegate && editBox._delegate.editBoxEditingReturn) { - editBox._delegate.editBoxEditingReturn(editBox); - } - } - }); - tmpEdTxt.addEventListener('blur', function () { - var editBox = thisPointer._editBox; - editBox._text = this.value; - thisPointer._updateDomTextCases(); - - if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { - editBox._delegate.editBoxEditingDidEnded(editBox); - } - - if (this.value === '') { - this.style.fontSize = editBox._placeholderFontSize + 'px'; - this.style.color = cc.colorToHex(editBox._placeholderColor); - } - - thisPointer._endEditing(); - }); - - this._addDomToGameContainer(); - return tmpEdTxt; - }; - - proto._createLabels = function () { - var editBoxSize = this._editBox.getContentSize(); - if(!this._textLabel) { - this._textLabel = _ccsg.Label.pool.get(); - this._textLabel.setAnchorPoint(cc.p(0, 1)); - this._textLabel.setOverflow(_ccsg.Label.Overflow.CLAMP); - this._editBox.addChild(this._textLabel, 100); - } - - if(!this._placeholderLabel) { - this._placeholderLabel = _ccsg.Label.pool.get(); - this._placeholderLabel.setAnchorPoint(cc.p(0, 1)); - this._placeholderLabel.setColor(cc.Color.GRAY); - this._editBox.addChild(this._placeholderLabel, 100); - } - - this._updateLabelPosition(editBoxSize); - }; - - proto._removeLabels = function () { - if(!this._textLabel) return; - - this._editBox.removeChild(this._textLabel); - this._textLabel = null; - }; - - proto._updateLabelPosition = function (editBoxSize) { - if(!this._textLabel || !this._placeholderLabel) return; - - var labelContentSize = cc.size(editBoxSize.width - LEFT_PADDING, editBoxSize.height); - this._textLabel.setContentSize(labelContentSize); - this._placeholderLabel.setLineHeight(editBoxSize.height); - var placeholderLabelSize = this._placeholderLabel.getContentSize(); - - if (this._editBox._editBoxInputMode === InputMode.ANY){ - this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height); - this._placeholderLabel.setPosition(LEFT_PADDING, editBoxSize.height); - this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP); - this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP); - this._textLabel.enableWrapText(true); - } - else { - this._textLabel.enableWrapText(false); - this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height); - this._placeholderLabel.setPosition(LEFT_PADDING, (editBoxSize.height + placeholderLabelSize.height) / 2); - this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER); - this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER); - } - - }; - - proto.setLineHeight = function (lineHeight) { - if(this._textLabel) { - this._textLabel.setLineHeight(lineHeight); - } - }; - - proto._hiddenLabels = function () { - if(this._textLabel) { - this._textLabel.setVisible(false); - } - - if(this._placeholderLabel) { - this._placeholderLabel.setVisible(false); - } - }; - - proto._updateDomTextCases = function() { - var inputFlag = this._editBox._editBoxInputFlag; - if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { - this._editBox._text = this._editBox._text.toUpperCase(); - } - else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { - this._editBox._text = capitalize(this._editBox._text); - } - else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) { - this._editBox._text = capitalizeFirstLetter(this._editBox._text); - } - }; - - proto._updateLabelStringStyle = function() { - if (this._edTxt.type === 'password') { - var passwordString = ''; - var len = this._editBox._text.length; - for (var i = 0; i < len; ++i) { - passwordString += '\u25CF'; - } - if(this._textLabel) { - this._textLabel.setString(passwordString); - } - } else { - this._updateDomTextCases(); - if(this._textLabel) { - this._textLabel.setString(this._editBox._text); - } - } - }; - - proto._showLabels = function () { - this._hiddenLabels(); - if (this._edTxt.value === '') { - if(this._placeholderLabel) { - this._placeholderLabel.setVisible(true); - this._placeholderLabel.setString(this._editBox._placeholderText); - } - } - else { - if(this._textLabel) { - this._textLabel.setVisible(true); - this._textLabel.setString(this._editBox._text); - } - } - this._updateLabelStringStyle(); - }; - - proto._beginEditing = function () { - var self = this; - if (!self._editBox._alwaysOnTop) { - if (self._edTxt.style.display === 'none') { - self._edTxt.style.display = ''; - - function startFocus () { - self._edTxt.focus(); - } - - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { - setTimeout(startFocus, FOCUS_DELAY_UC); - } - else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) { - setTimeout(startFocus, FOCUS_DELAY_FIREFOX); - } - else { - startFocus(); - } - } - } - - if (cc.sys.isMobile && !self._editingMode) { - // Pre adaptation and - self._beginEditingOnMobile(self._editBox); - } - self._editingMode = true; - }; - - proto._endEditing = function() { - if (!this._editBox._alwaysOnTop) { - this._edTxt.style.display = 'none'; - } - this._showLabels(); - if (cc.sys.isMobile && this._editingMode) { - var self = this; - // Delay end editing adaptation to ensure virtual keyboard is disapeared - setTimeout(function () { - self._endEditingOnMobile(); - }, DELAY_TIME); - } - this._editingMode = false; - }; - - proto._setFont = function (fontStyle) { - var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); - var textFontName = res[2]; - var textFontSize = parseInt(res[1]); - if (res) { - this.setFont(textFontName, textFontSize); - } - }; - - proto.setFont = function (fontName, fontSize) { - this._edFontName = fontName || this._edFontName; - this._edFontSize = fontSize || this._edFontSize; - this._updateDOMFontStyle(); - }; - - proto.setFontName = function (fontName) { - this._edFontName = fontName || this._edFontName; - this._updateDOMFontStyle(); - }; - - proto.setFontSize = function (fontSize) { - this._edFontSize = fontSize || this._edFontSize; - this._updateDOMFontStyle(); - }; - - proto.setFontColor = function (color) { - if(!this._edTxt) return; - - if (this._edTxt.value !== this._editBox._placeholderText) { - this._edTxt.style.color = cc.colorToHex(color); - } - if(this._textLabel) { - this._textLabel.setColor(color); - } - }; - - proto.setPlaceHolder = function (text) { - this._placeholderLabel.setString(text); - }; - - proto.setMaxLength = function (maxLength) { - if(!this._edTxt) return; - this._edTxt.maxLength = maxLength; - }; - - proto._updateDOMPlaceholderFontStyle = function () { - this._placeholderLabel.setFontFamily(this._editBox._placeholderFontName); - this._placeholderLabel.setFontSize(this._editBox._placeholderFontSize); - }; - - proto.setPlaceholderFontColor = function (color) { - this._placeholderLabel.setColor(color); - }; - - proto._updateDomInputType = function () { - var inputMode = this._editBox._editBoxInputMode; - if(inputMode === InputMode.EMAIL_ADDR) { - this._edTxt.type = 'email'; - } else if(inputMode === InputMode.NUMERIC || - inputMode === InputMode.DECIMAL) { - this._edTxt.type = 'number'; - } else if(inputMode === InputMode.PHONE_NUMBER) { - this._edTxt.type = 'number'; - this._edTxt.pattern = '[0-9]*'; - } else if(inputMode === InputMode.URL) { - this._edTxt.type = 'url'; - } else { - this._edTxt.type = 'text'; - - if(this._editBox._keyboardReturnType === KeyboardReturnType.SEARCH) { - this._edTxt.type = 'search'; - } - } - - - if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD) { - this._edTxt.type = 'password'; - } - }; - - proto.setInputFlag = function (inputFlag) { - if(!this._edTxt) return; - - this._updateDomInputType(); - - this._edTxt.style.textTransform = 'none'; - - if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { - this._edTxt.style.textTransform = 'uppercase'; - } - else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { - this._edTxt.style.textTransform = 'capitalize'; - } - this._updateLabelStringStyle(); - }; - - proto.setInputMode = function (inputMode) { - if (inputMode === InputMode.ANY) { - this._createDomTextArea(); - } - else { - this._createDomInput(); - } - - this._updateDomInputType(); - var contentSize = this._node.getContentSize(); - this.updateSize(contentSize.width, contentSize.height); - }; - - proto.setString = function (text) { - if(!this._edTxt) return; - - if (text !== null) { - this._edTxt.value = text; - - if (text === '') { - if(this._placeholderLabel) { - this._placeholderLabel.setString(this._editBox._placeholderText); - this._placeholderLabel.setColor(this._editBox._placeholderColor); - } - if(!this._editingMode) { - if (this._placeholderLabel) { - this._placeholderLabel.setVisible(true); - } - if (this._textLabel) { - this._textLabel.setVisible(false); - } - } - } - else { - this._edTxt.style.color = cc.colorToHex(this._editBox._textColor); - if(this._textLabel) { - this._textLabel.setColor(this._editBox._textColor); - } - if (!this._editingMode) { - if(this._placeholderLabel) { - this._placeholderLabel.setVisible(false); - } - if(this._textLabel) { - this._textLabel.setVisible(true); - } - } - - this._updateLabelStringStyle(); - } - } - }; - - proto._updateDOMFontStyle = function() { - if(!this._edTxt) return; - - if (this._edTxt.value !== '') { - this._edTxt.style.fontFamily = this._edFontName; - this._edTxt.style.fontSize = this._edFontSize + 'px'; - } - if(this._textLabel) { - this._textLabel.setFontSize(this._edFontSize); - this._textLabel.setFontFamily(this._edFontName); - } - }; - - - proto.updateSize = function(newWidth, newHeight) { - var editboxDomNode = this._edTxt; - if (!editboxDomNode) return; - - editboxDomNode.style['width'] = newWidth + 'px'; - editboxDomNode.style['height'] = newHeight + 'px'; - - this._updateLabelPosition(cc.size(newWidth, newHeight)); - }; - - proto._addDomToGameContainer = function () { - cc.game.container.appendChild(this._edTxt); - }; - - proto.removeDom = function () { - var editBox = this._edTxt; - if(editBox){ - var hasChild = Utils.contains(cc.game.container, editBox); - if(hasChild) { - cc.game.container.removeChild(editBox); - } - } - this._edTxt = null; - }; - - proto.initializeRenderCmd = function (node) { - this._editBox = node; - - //it's a dom node, may be assigned with Input or TextArea. - this._edFontSize = 14; - this._edFontName = 'Arial'; - this._textLabel = null; - this._placeholderLabel = null; - this._editingMode = false; - - this.__fullscreen = false; - this.__autoResize = false; - this.__rotateScreen = false; - this.__orientationChanged = null; - }; - - //define the canvas render command - _ccsg.EditBox.CanvasRenderCmd = function (node) { - this._rootCtor(node); - this.initializeRenderCmd(node); - }; - - var canvasRenderCmdProto = _ccsg.EditBox.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); - cc.js.mixin(canvasRenderCmdProto, proto); - canvasRenderCmdProto.constructor = _ccsg.EditBox.CanvasRenderCmd; - - canvasRenderCmdProto.transform = function (parentCmd, recursive) { - this.originTransform(parentCmd, recursive); - this.updateMatrix(); - }; - - //define the webgl render command - _ccsg.EditBox.WebGLRenderCmd = function (node) { - this._rootCtor(node); - this.initializeRenderCmd(node); - }; - - var webGLRenderCmdProto = _ccsg.EditBox.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); - cc.js.mixin(webGLRenderCmdProto, proto); - webGLRenderCmdProto.constructor = _ccsg.EditBox.WebGLRenderCmd; - - webGLRenderCmdProto.transform = function (parentCmd, recursive) { - this.originTransform(parentCmd, recursive); - this.updateMatrix(); - }; - -}(_ccsg.EditBox._polyfill)); diff --git a/cocos2d/core/renderer/assemblers/label/ttf-assembler.js b/cocos2d/core/renderer/assemblers/label/ttf-assembler.js index f2b0f94522..d25518cf6b 100644 --- a/cocos2d/core/renderer/assemblers/label/ttf-assembler.js +++ b/cocos2d/core/renderer/assemblers/label/ttf-assembler.js @@ -87,7 +87,36 @@ module.exports = { return renderData; }, - fillVertexBuffer: spriteAssembler.fillVertexBuffer, + fillVertexBuffer (comp, index, vbuf, uintbuf) { + let off = index * comp._vertexFormat._bytes / 4; + let node = comp.node; + let renderData = comp._renderData; + let data = renderData._data; + let z = node._position.z; + let color = cc.Color.WHITE._val; + + node._updateWorldMatrix(); + let matrix = node._worldMatrix; + let a = matrix.m00, + b = matrix.m01, + c = matrix.m04, + d = matrix.m05, + tx = matrix.m12, + ty = matrix.m13; + + let vert; + let length = renderData.dataLength; + for (let i = 0; i < length; i++) { + vert = data[i]; + vbuf[off + 0] = vert.x * a + vert.y * c + tx; + vbuf[off + 1] = vert.x * b + vert.y * d + ty; + vbuf[off + 2] = z; + vbuf[off + 4] = vert.u; + vbuf[off + 5] = vert.v; + uintbuf[off + 3] = color; + off += 6; + } + }, fillIndexBuffer (comp, offset, vertexId, ibuf) { ibuf[offset + 0] = vertexId; @@ -239,7 +268,7 @@ module.exports = { var lineHeight = this._getLineHeight(); //use round for line join to avoid sharp intersect point _context.lineJoin = 'round'; - _context.fillStyle = 'rgb(' + _color.r + ',' + _color.g + ',' + _color.b + ')'; + _context.fillStyle = `rgba(${_color.r}, ${_color.g}, ${_color.b}, ${_color.a/255})`; var underlineStartPosition; //do real rendering @@ -247,7 +276,7 @@ module.exports = { if (_isOutlined) { var strokeColor = _outlineColor || cc.color(255,255,255,255); _context.globalCompositeOperation = 'source-over'; - _context.strokeStyle = 'rgb(' + strokeColor.r + ',' + strokeColor.g + ',' + strokeColor.b + ')'; + _context.strokeStyle = `rgba(${strokeColor.r}, ${strokeColor.g}, ${strokeColor.b}, ${strokeColor.a/255})`; _context.lineWidth = _outlineWidth * 2; _context.strokeText(_splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); } @@ -267,7 +296,7 @@ module.exports = { _context.save(); _context.beginPath(); _context.lineWidth = _fontSize / 8; - _context.strokeStyle = 'rgb(' + _color.r + ',' + _color.g + ',' + _color.b + ')'; + _context.strokeStyle = `rgba(${_color.r}, ${_color.g}, ${_color.b}, ${_color.a/255})`; _context.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 1); _context.lineTo(underlineStartPosition.x + _canvas.width, underlineStartPosition.y + i * lineHeight - 1); _context.stroke();