Files
cocos4/cocos/ui/components/editbox/edit-box-impl.ts
T
2019-12-28 15:57:42 +08:00

710 lines
22 KiB
TypeScript

/*
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.
http://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.
*/
/**
* @hidden
*/
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 { LabelComponent } from '../label-component';
import { EditBoxComponent} from './edit-box-component';
import { tabIndexUtil } from './tabIndexUtil';
import { InputFlag, InputMode, KeyboardReturnType } from './types';
import sys from '../../../core/platform/sys';
import visibleRect from '../../../core/platform/visible-rect';
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 _matrix = new Mat4();
const _matrix_temp = new Mat4();
const _vec3 = new Vec3();
let _currentEditBoxImpl: EditBoxImpl | null = null;
let _domCount = 0;
// polyfill
const polyfill = {
zoomInvalid: false,
};
if (sys.OS_ANDROID === sys.os &&
(sys.browserType === sys.BROWSER_TYPE_SOUGOU ||
sys.browserType === sys.BROWSER_TYPE_360)) {
polyfill.zoomInvalid = true;
}
export class EditBoxImpl extends EditBoxImplBase {
public _delegate: EditBoxComponent | null = null;
public _inputMode = InputMode.ANY;
public _inputFlag = InputFlag.DEFAULT;
public _returnType = KeyboardReturnType.DEFAULT;
public _maxLength = 50;
public _placeholderText = '';
public _alwaysOnTop = false;
public _size: Size = new Size();
public _node: Node | null = null;
public _editing = false;
public __eventListeners: any = {};
public __fullscreen = false;
public __autoResize = false;
public __rotateScreen = false;
public __orientationChanged: any;
public _edTxt: HTMLInputElement | HTMLTextAreaElement | null = null;
public _textColor: Color = Color.WHITE.clone();
public _edFontSize = 14;
private _isTextArea = false;
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}`;
public init (delegate: EditBoxComponent) {
if (!delegate){
return;
}
this._delegate = delegate;
if (delegate.inputMode === InputMode.ANY){
this._createTextArea();
} else {
this._createInput();
}
tabIndexUtil.add(this);
this.setTabIndex(delegate.tabIndex);
this._initStyleSheet();
this._registerEventListeners();
this._addDomToGameContainer();
this.__fullscreen = view.isAutoFullScreenEnabled();
this.__autoResize = view._resizeWithBrowserSize;
}
public onEnable () {
// Do nothing
}
public onDisable () {
if (this._editing && this._edTxt) {
this._edTxt.blur();
}
}
public clear () {
this._removeEventListeners();
this._removeDomFromGameContainer();
tabIndexUtil.remove(this);
// clear while editing
if (_currentEditBoxImpl === this) {
_currentEditBoxImpl = null;
}
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';
}
}
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 () {
// 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;
setTimeout(() => {
if (window.scrollY < SCROLLY) {
self._edTxt!.scrollIntoView({block: 'start', inline: 'nearest', behavior: 'smooth'});
}
}, DELAY_TIME);
}
private _scrollBackWindow () {
setTimeout(() => {
if (sys.browserType === sys.BROWSER_TYPE_WECHAT && sys.os === sys.OS_IOS) {
if (window.top) {
window.top.scrollTo(0, 0);
}
return;
}
window.scrollTo(0, 0);
}, DELAY_TIME);
}
private _updateMatrix () {
if (!this._edTxt) {
return;
}
const node = this._delegate!.node;
let scaleX = view.getScaleX();
let scaleY = view.getScaleY();
const viewport = view.getViewportRect();
const dpr = view.getDevicePixelRatio();
node.getWorldMatrix(_matrix);
const transform = node!._uiProps.uiTransformComp;
if (transform) {
Vec3.set(_vec3, -transform.anchorX * transform.width, -transform.anchorY * transform.height, _vec3.z);
}
Mat4.transform(_matrix, _matrix, _vec3);
if (!node._uiProps.uiTransformComp) {
return false;
}
const canvas = director.root!.ui.getScreen(node._uiProps.uiTransformComp.visibility);
if (!canvas) {
return;
}
// camera.getWorldToCameraMatrix(_matrix_temp);
canvas.node.getWorldRT(_matrix_temp);
const m12 = _matrix_temp.m12;
const m13 = _matrix_temp.m13;
const center = visibleRect.center;
_matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13);
_matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13);
Mat4.multiply(_matrix_temp, _matrix_temp, _matrix);
scaleX /= dpr;
scaleY /= dpr;
const container = game.container;
let a = _matrix_temp.m00 * scaleX;
const b = _matrix.m01;
const c = _matrix.m04;
let d = _matrix_temp.m05 * scaleY;
let offsetX = parseInt((container && container.style.paddingLeft) || '0');
offsetX += viewport.x / dpr;
let offsetY = parseInt((container && container.style.paddingBottom) || '0');
offsetY += viewport.y / dpr;
const tx = _matrix_temp.m12 * scaleX + offsetX;
const ty = _matrix_temp.m13 * scaleY + offsetY;
if (polyfill.zoomInvalid) {
this.setSize(this._size.width * a, this._size.height * d);
a = 1;
d = 1;
}
const 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';
}
private _updateInputType () {
const delegate = this._delegate;
const inputMode = delegate!.inputMode;
const inputFlag = delegate!.inputFlag;
const returnType = delegate!.returnType;
let elem = this._edTxt;
if (this._inputMode === inputMode &&
this._inputFlag === inputFlag &&
this._returnType === returnType) {
return;
}
// update cache
this._inputMode = inputMode;
this._inputFlag = inputFlag;
this._returnType = returnType;
// 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';
}
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';
}
}
elem!.type = type;
// 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;
}
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;
}
}