From e2fbf3de2c784c91e992317f0caf5f7e916cbe1f Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 16 Aug 2016 16:36:05 +0800 Subject: [PATCH 01/11] add bbcode parser commit 98767c294a5b5ac1272d320358a65821b8adbbe4 Author: zilongshanren Date: Fri Aug 12 18:41:16 2016 +0800 fix tag commit 4f6bde4e147b69d8c4c91f149140be6e81a41bbd Author: zilongshanren Date: Fri Aug 12 18:11:40 2016 +0800 add bold/italic/underline commit 69a498c44b38f302c448f23e6e544a13e419c2ea Author: zilongshanren Date: Fri Aug 12 17:31:07 2016 +0800 finish nested tag test commit 0a7328a8cf9752612de4f8a4cababf00c8e74427 Author: zilongshanren Date: Fri Aug 12 15:44:08 2016 +0800 finish tag parsing commit d375700850ea52e18710d44d39626f8f22d677ba Author: zilongshanren Date: Fri Aug 12 11:53:16 2016 +0800 refactoring done commit 38b567c3439a8b0858b59645ff81cd458ce235a9 Merge: a30fa24 c6cab77 Author: zilongshanren Date: Fri Aug 12 11:49:44 2016 +0800 Merge branch 'master' into add-rich-text-support commit a30fa24f7127a3cae3945ad994458744766894dc Author: zilongshanren Date: Fri Aug 12 11:48:30 2016 +0800 refactor tag parsing commit f123f52c24b3c994769f8c17de1b3a4099af72cd Merge: ad6e15b f8f9f72 Author: zilongshanren Date: Fri Aug 12 09:56:44 2016 +0800 Merge branch 'master' into add-rich-text-support commit ad6e15b0124c93fa51c551a9d25d71e2d08c85da Author: zilongshanren Date: Fri Aug 12 09:50:42 2016 +0800 parse event tag commit 88cf8a900318408da6f1efba9660efebb2f7469f Author: zilongshanren Date: Wed Aug 10 15:11:03 2016 +0800 add event handler commit a409e294b8b39c0bfc79c1e9872bca7339d06e93 Author: zilongshanren Date: Wed Aug 10 11:30:53 2016 +0800 add size parser commit 15406e1884da24f1d9aade74664f18ce055c91cd Author: zilongshanren Date: Wed Aug 10 10:22:58 2016 +0800 make color parsing works commit 6a5e1966e33ed6bf7aa253c1c4d8df52c5906d4c Author: zilongshanren Date: Tue Aug 9 18:31:20 2016 +0800 support color value commit 5ee73d1fbbaac7b2e2183182dd095ec3ffa76c20 Author: zilongshanren Date: Tue Aug 9 18:21:38 2016 +0800 add basic tag parser commit 05a4de6da69a7101376432e19b4a28c098db22ac Author: zilongshanren Date: Thu Jul 14 14:37:09 2016 +0800 add escape symbol test --- cocos2d/core/index.js | 1 + cocos2d/core/label/CCHtmlTextParser.js | 219 +++++++++++++++++++ test/qunit/run.sh | 0 test/qunit/unit/test-html-text-parser.js | 262 +++++++++++++++++++++++ 4 files changed, 482 insertions(+) create mode 100644 cocos2d/core/label/CCHtmlTextParser.js mode change 100644 => 100755 test/qunit/run.sh create mode 100644 test/qunit/unit/test-html-text-parser.js diff --git a/cocos2d/core/index.js b/cocos2d/core/index.js index 084e855a61..d9eead82ee 100644 --- a/cocos2d/core/index.js +++ b/cocos2d/core/index.js @@ -37,6 +37,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) { require('./components'); require('./graphics'); require('./collider'); + require('./label/CCHtmlTextParser.js'); } require('./base-ui/CCWidgetManager'); diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js new file mode 100644 index 0000000000..cb7c574303 --- /dev/null +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -0,0 +1,219 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + 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. + ****************************************************************************/ + +/** + * A utils class for parsing HTML texts. The parsed results will be an object array. + */ +cc.HtmlTextParser = function() { + this._parsedObject = {}; + this._specialSymbolArray = []; + this._specialSymbolArray.push([/</g, '<']); + this._specialSymbolArray.push([/>/g, '>']); + this._specialSymbolArray.push([/&/g, '&']); + this._specialSymbolArray.push([/"/g, '"']); + this._specialSymbolArray.push([/'/g, '\'']); +}; + +cc.HtmlTextParser.prototype = { + constructor: cc.HtmlTextParser, + parse: function(htmlString) { + this._resultObjectArray = []; + this._stack = []; + + var startIndex = 0; + var length = htmlString.length; + while (startIndex < length) { + var tagBeginIndex = htmlString.indexOf('<', startIndex); + if (tagBeginIndex < 0) { + this._stack.pop(); + this._processResult(htmlString.substring(startIndex)); + startIndex = length; + } else { + this._processResult(htmlString.substring(startIndex, tagBeginIndex)); + + var tagEndIndex = htmlString.indexOf('>', startIndex); + if (tagEndIndex === -1) { + cc.error('The tag is invalid!'); + tagEndIndex = tagBeginIndex; + } else if (htmlString.charAt(tagBeginIndex + 1) === '\/'){ + this._stack.pop(); + } else { + this._addToStack(htmlString.substring(tagBeginIndex + 1, tagEndIndex)); + } + startIndex = tagEndIndex + 1; + + } + } + + + return this._resultObjectArray; + }, + + _attributeToObject: function (attribute) { + attribute = attribute.trim(); + + var obj = {}; + var header = attribute.match(/^(color|size)(\s)*=/); + var tagName; + var nextSpace; + var eventObj; + if (header) { + tagName = header[0]; + attribute = attribute.substring(tagName.length).trim(); + if(attribute === "") return obj; + + //parse color + nextSpace = attribute.indexOf(' '); + switch(tagName[0]){ + case 'c': + if (nextSpace > -1) { + obj.color = attribute.substring(0, nextSpace).trim(); + } else { + obj.color = attribute; + } + break; + case 's': + obj.size = parseInt(attribute); + break; + } + + //tag has event arguments + if(nextSpace > -1) { + var eventHanlderString = attribute.substring(nextSpace+1).trim(); + eventObj = this._processEventHandler(eventHanlderString); + obj.event = eventObj; + } + } + + header = attribute.match(/^(on|u|b|i)(\s)*/); + if(header && header[0].length > 0) { + tagName = header[0]; + attribute = attribute.substring(tagName.length).trim(); + switch(tagName[0]){ + case 'u': + obj.underline = true; + break; + case 'i': + obj.italic = true; + break; + case 'b': + obj.bold = true; + break; + } + if(attribute === "") { + return obj; + } + eventObj = this._processEventHandler(attribute); + obj.event = eventObj; + } + + return obj; + }, + + _processEventHandler: function (eventString) { + var index = 0; + var obj = {}; + var eventNames = eventString.match(this._getEventRegx()); + var isValidTag = false; + while(eventNames) { + var eventName = eventNames[0]; + var eventValue = ""; + isValidTag = false; + eventString = eventString.substring(eventName.length).trim(); + if(eventString.charAt(0) === "\"") { + index = eventString.indexOf("\"", 1); + if (index > -1) { + eventValue = eventString.substring(1, index).trim(); + isValidTag = true; + } + index++; + } else if(eventString.charAt(0) === "\'") { + index = eventString.indexOf('\'', 1); + if(index > -1) { + eventValue = eventString.substring(1, index).trim(); + isValidTag = true; + } + index++; + } else { + //skip the invalid attribute value + eventValue = eventString.match(/(\S)+/)[0]; + index = eventValue.length; + } + + if(isValidTag) { + eventName = eventName.substring(0, eventName.length-1).trim(); + obj[eventName] = eventValue; + } + + eventString = eventString.substring(index).trim(); + eventNames = eventString.match(this._getEventRegx()); + } + + return obj; + }, + + _addToStack: function(attribute) { + var obj = this._attributeToObject(attribute); + + if (this._stack.length === 0){ + this._stack.push(obj); + } else { + //for nested tags + var previousTagObj = this._stack[this._stack.length - 1]; + for (var key in previousTagObj) { + if (!(obj[key])) { + obj[key] = previousTagObj[key]; + } + } + this._stack.push(obj); + } + }, + + _processResult: function(value) { + if (value === "") { + return; + } + + value = this._escapeSpecialSymbol(value); + if (this._stack.length > 0) { + this._resultObjectArray.push({text: value, style: this._stack[this._stack.length - 1]}); + } else { + this._resultObjectArray.push({text: value}); + } + }, + + _getEventRegx: function () { + return /^(click|hoverin|hoverout)(\s)*=/; + }, + + _escapeSpecialSymbol: function(str) { + for(var i = 0; i < this._specialSymbolArray.length; ++i) { + var key = this._specialSymbolArray[i][0]; + var value = this._specialSymbolArray[i][1]; + + str = str.replace(key, value); + } + return str; + } +}; diff --git a/test/qunit/run.sh b/test/qunit/run.sh old mode 100644 new mode 100755 diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js new file mode 100644 index 0000000000..f94a556292 --- /dev/null +++ b/test/qunit/unit/test-html-text-parser.js @@ -0,0 +1,262 @@ +/*global test, deepEqual, largeModule, strictEqual */ + +largeModule('HtmlTextParser'); + +var parser = new cc.HtmlTextParser(); + +test('Basic Test', function() { + + var testStr1 = "hello world"; + deepEqual(parser.parse(testStr1), + [{text: "hello world"}], + 'No Html string should be equal to original.'); + + var testInvalidStr2 = "Super weapon"; + + deepEqual(parser.parse(eventTestString2), + [{text: "Super weapon", style: { + color: "#0xff0000", + event: { + click : "event1", + } + }}], "Color with event"); + + var eventTestString3 = "hello world"; + deepEqual(parser.parse(eventTestString3), + [{text: "hello world", + style: { + size: 20, + event: { + click : "event1", + hoverin : "event2" + } + }}], "Size with event"); + + var eventTestString4 = "hello world"; + deepEqual(parser.parse(eventTestString4), + [{text: "hello world", + style: {} + }], "Failed path: Size with event"); + + +}); + +test('Test special symbol escape', function() { + var testLessThan = "hello<world"; + + deepEqual(parser.parse(testLessThan), + [ {text: "helloworld", + style: { + event: { + click: 'event1' + } + }}], + "The > symbol should be correctly escaped."); + + var testAmp = "hello&world"; + deepEqual(parser.parse(testAmp), + [{text: "hello&world", + style: { + color: "#0xff00" + }}], + "The amp symbol should be correctly escaped."); + + var testQuot = "hello"world"; + deepEqual(parser.parse(testQuot), + [{text: "hello\"world", + style: {}}], + "The quot symbol should be correctly escaped."); + + var testApos = "Hi, hello'world"; + deepEqual(parser.parse(testApos), + [{text: "Hi, ", + style: { + color: "#0xffee" + }}, + {text: "hello'world", + style: { + color: "#0xffee", + size: 20 + }}], + "The apos symbol should be correctly escaped."); +}); + + +test('Integrate test', function() { + var eventTestString = "hello world, Ni hao "; + + deepEqual(parser.parse(eventTestString), + [{text: "hello "}, {text: "world", style: {bold: true}}, + {text: ", "}, + {text: " Ni hao ", style : {color: "#0xff0000"}}], "Happy path 1"); + + var moreComplexString = "大小不一,颜色不同可点击"; + deepEqual(parser.parse(moreComplexString), + [{text: "大小", style: {size: 20}}, {text: "不一", style: {size: 10}}, {text:","}, + {text: "颜色", style: {color: "#0xffeeaa"}}, {text: "不同", style: {color: "#0xffaaee"}}, + {text: "可点击", style: {event: {click: 'event1'}}}], "more complex test"); + + +}); + +test('bold/italic/underline test', function () { + var stringWithBold = "hello world"; + + deepEqual(parser.parse(stringWithBold), + [{text: "hello world", style: {bold: true}}], "bold test"); + + var stringWithItalic = "hello world"; + + deepEqual(parser.parse(stringWithItalic), + [{text: "hello world", style: {italic: true}}], "italic test"); + + var stringWithUnderline = "hello world"; + + deepEqual(parser.parse(stringWithUnderline), + [{text: "hello world", style: {underline: true}}], "underline test"); +}); From feca3e5780fa5ad377b614ebbb59ac7fc3488699 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 17 Aug 2016 14:28:39 +0800 Subject: [PATCH 02/11] add more tests --- test/qunit/unit/test-html-text-parser.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js index f94a556292..29b4defde3 100644 --- a/test/qunit/unit/test-html-text-parser.js +++ b/test/qunit/unit/test-html-text-parser.js @@ -174,6 +174,20 @@ test('Event test', function() { style: {} }], "Failed path: Size with event"); + var invalidEventTestString4 = "hello world"; + deepEqual(parser.parse(invalidEventTestString5), + [{text: "hello world", + style: {size: 20, + event: {}} + }], "Failed path: event name quote not match."); + }); @@ -245,7 +259,7 @@ test('Integrate test', function() { }); test('bold/italic/underline test', function () { - var stringWithBold = "hello world"; + var stringWithBold = "hello world"; deepEqual(parser.parse(stringWithBold), [{text: "hello world", style: {bold: true}}], "bold test"); From 57e17c73b9ee52dbade133f67bd0773e46050f63 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 18 Aug 2016 14:32:34 +0800 Subject: [PATCH 03/11] add RichText component A minimal working prototype try and fix fix richtext color make richtext properties tweakable temp refine add measure text fix fragment text finish non \n case make non maxWidth working adjust calling order fix wired bugs get first word still one bug remained fix wrap error refactoring update lineOffsetX refactoring refactoring fix a return issue don't display vertical alignment improve performance refactoring almost done refactoring refactoring improve setColor use shared htmlTextParser fix contentSize change issue add click event handler add hoverin and hoverout event handler fix a issue remove mousein and mouseover done --- cocos2d/core/components/CCLabel.js | 3 +- cocos2d/core/components/CCRichText.js | 605 +++++++++++++++++++++++ cocos2d/core/components/index.js | 1 + cocos2d/core/index.js | 2 +- cocos2d/core/label/CCHtmlTextParser.js | 14 +- cocos2d/core/label/CCSGLabel.js | 4 +- test/qunit/unit/test-html-text-parser.js | 10 +- 7 files changed, 624 insertions(+), 15 deletions(-) create mode 100644 cocos2d/core/components/CCRichText.js diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index bb31dbb0ce..abafc3fe0f 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -114,7 +114,6 @@ var Overflow = _ccsg.Label.Overflow; * !#zh 系统字体 * @property {Number} SystemFont */ -var LabelType = _ccsg.Label.Type; // Returns a function, that, as long as it continues to be invoked, will not @@ -134,7 +133,7 @@ function debounce(func, wait, immediate) { timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; -}; +} /** diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js new file mode 100644 index 0000000000..b74df92102 --- /dev/null +++ b/cocos2d/core/components/CCRichText.js @@ -0,0 +1,605 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + 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. + Chukong Aipu 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. + ****************************************************************************/ +var HorizontalAlign = cc.TextAlignment; +var VerticalAlign = cc.VerticalTextAlignment; + +var label_wrapinspection = true; +var label_wordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)/; +var label_symbolRex = /^[!,.:;}\]%\?>、‘“》?。,!]/; +var label_lastWordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)$/; +var label_lastEnglish = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+$/; +var label_firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; + +// Returns a function, that, as long as it continues to be invoked, will not +// be triggered. The function will be called after it stops being called for +// N milliseconds. If `immediate` is passed, trigger the function on the +// leading edge, instead of the trailing. +function debounce(func, wait, immediate) { + var timeout; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; +} + +/** + * !#en The RichText Component. + * !#zh 富文本组件 + * @class RichText + * @extends Component + */ +var RichText = cc.Class({ + name: 'cc.RichText', + extends: cc._RendererUnderSG, + + ctor: function() { + this._textArray = null; + + this._resetState(); + }, + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.renderers/RichText', + }, + + + properties: { + _useOriginalSize: true, + /** + * !#en Content string of RichText. + * !#zh 富文本显示的文本内容。 + * @property {String} string + */ + string: { + default: 'Label', + multiline: true, + tooltip: 'i18n:COMPONENT.label.string', + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en Horizontal Alignment of label. + * !#zh 文本内容的水平对齐方式。 + * @property {RichText.HorizontalAlign} horizontalAlign + */ + horizontalAlign: { + default: HorizontalAlign.LEFT, + type: HorizontalAlign, + tooltip: 'i18n:COMPONENT.label.horizontal_align', + animatable: false, + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en Font size of label. + * !#zh 文本字体大小。 + * @property {Number} fontSize + */ + fontSize: { + default: 40, + tooltip: 'i18n:COMPONENT.label.font_size', + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en The maximize width of the RichText + * !#zh 富文本的最大宽度 + * @property {Number} maxWidth + */ + maxWidth: { + default: 0, + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en Line Height of label. + * !#zh 文本行高。 + * @property {Number} lineHeight + */ + lineHeight: { + default: 40, + tooltip: 'i18n:COMPONENT.label.line_height', + notify: function () { + this._updateRichTextStatus(); + } + } + }, + + _updateRichTextStatus: function () { + if(this._sgNode) { + if(CC_EDITOR) { + this._debouncedUpdateRichText(); + } else { + this._updateRichText(); + } + } + }, + + statics: { + HorizontalAlign: HorizontalAlign, + VerticalAlign: VerticalAlign + }, + + _createSgNode: function () { + return null; + }, + + __preload: function () { + this._super(); + if(CC_EDITOR) { + this._debouncedUpdateRichText = debounce(this._updateRichText, 200); + } else { + this._registerEvents(); + } + + }, + + _updateLabelSegmentColor: function() { + this._labelSegments.forEach(function(item) { + this._applyTextAttribute(item); + }.bind(this)); + }, + + _initSgNode: function () { + + var sgNode = this._sgNode = new _ccsg.Node(); + sgNode.setCascadeOpacityEnabled(true); + + if (this.enabledInHierarchy && !sgNode.isVisible()) { + sgNode.setVisible(true); + } + + if ( !this.enabledInHierarchy ) { + sgNode.setVisible(false); + } + + var self = this; + sgNode.setColor = function () { + self._updateLabelSegmentColor(); + }; + + sgNode._setContentSize = sgNode.setContentSize; + sgNode.setContentSize = function () {}; + + this._updateRichText(); + + if(CC_JSB) { + sgNode.retain(); + } + }, + + _computeAlignmentOffset: function() { + this._linesOffsetX = []; + switch (this.horizontalAlign) { + case cc.TextAlignment.LEFT: + for (var i = 0; i < this._lineCount; ++i) { + this._linesOffsetX.push(0); + } + break; + case cc.TextAlignment.CENTER: + this._linesWidth.forEach(function(lineWidth) { + this._linesOffsetX.push((this._labelWidth - lineWidth) / 2); + }.bind(this)); + break; + case cc.TextAlignment.RIGHT: + this._linesWidth.forEach(function(lineWidth) { + this._linesOffsetX.push(this._labelWidth - lineWidth); + }.bind(this)); + break; + default: + break; + } + }, + + _measureText: function (string, styleIndex) { + var label = new _ccsg.Label(string); + label._styleIndex = styleIndex; + this._applyTextAttribute(label); + var labelSize = label.getContentSize(); + return labelSize.width; + }, + + + _onTouchEnded: function (event) { + if(!this.enabledInHierarchy) return; + + var components = this.node.getComponents(cc.Component); + + for (var i = 0; i < this._labelSegments.length; ++i ) { + var labelSegment = this._labelSegments[i]; + var clickHandler = labelSegment._clickHandler; + if (clickHandler && this._containsTouchLocation(labelSegment, event.touch.getLocation())) { + components.forEach(function(component) { + if(component.enabledInHierarchy && component[clickHandler]) { + component[clickHandler](event); + } + }); + } + } + }, + + _containsTouchLocation:function (label, point) { + var myRect = label.getBoundingBoxToWorld(); + + return cc.rectContainsPoint(myRect, point); + }, + + _registerEvents: function () { + this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + }, + + _fragmentText: function (stringToken, allWidth, styleIndex) { + //check the first character + var wrappedWords = []; + //fast return if strArr is empty + if(stringToken.length === 0 || this.maxWidth < 0) { + wrappedWords.push(''); + return wrappedWords; + } + + var text = stringToken; + while (allWidth > this.maxWidth && text.length > 1) { + + var fuzzyLen = text.length * ( this.maxWidth / allWidth ) | 0; + var tmpText = text.substr(fuzzyLen); + var width = allWidth - this._measureText(tmpText, styleIndex); + var sLine = tmpText; + var pushNum = 0; + + var checkWhile = 0; + var checkCount = 10; + + //Exceeded the size + while (width > this.maxWidth && checkWhile++ < checkCount) { + fuzzyLen *= this.maxWidth / width; + fuzzyLen = fuzzyLen | 0; + tmpText = text.substr(fuzzyLen); + width = allWidth - this._measureText(tmpText, styleIndex); + } + + checkWhile = 0; + + //Find the truncation point + while (width < this.maxWidth && checkWhile++ < checkCount) { + if (tmpText) { + var exec = label_wordRex.exec(tmpText); + pushNum = exec ? exec[0].length : 1; + sLine = tmpText; + } + + fuzzyLen = fuzzyLen + pushNum; + tmpText = text.substr(fuzzyLen); + width = allWidth - this._measureText(tmpText, styleIndex); + } + + fuzzyLen -= pushNum; + if (fuzzyLen === 0) { + fuzzyLen = 1; + sLine = sLine.substr(1); + } + + var sText = text.substr(0, fuzzyLen), result; + + //symbol in the first + if (label_wrapinspection) { + if (label_symbolRex.test(sLine || tmpText)) { + result = label_lastWordRex.exec(sText); + fuzzyLen -= result ? result[0].length : 0; + if (fuzzyLen === 0) fuzzyLen = 1; + + sLine = text.substr(fuzzyLen); + sText = text.substr(0, fuzzyLen); + } + } + + //To judge whether a English words are truncated + if (label_firsrEnglish.test(sLine)) { + result = label_lastEnglish.exec(sText); + if (result && sText !== result[0]) { + fuzzyLen -= result[0].length; + sLine = text.substr(fuzzyLen); + sText = text.substr(0, fuzzyLen); + } + } + if (sText.trim().length > 0) { + wrappedWords.push(sText); + } + text = sLine || tmpText; + allWidth = this._measureText(text, styleIndex); + } + if (text.length > 0) { + wrappedWords.push(text); + } + + return wrappedWords; + }, + + _resetState: function () { + var sgNode = this._sgNode; + if(sgNode) { + sgNode.removeAllChildren(); + } + + this._labelSegments = []; + this._linesWidth = []; + this._lineOffsetX = 0; + this._lineCount = 1; + this._labelWidth = 0; + this._labelHeight = 0; + }, + + _addLabelSegment: function(stringToken, styleIndex) { + var labelSegment = new _ccsg.Label(stringToken); + labelSegment._styleIndex = styleIndex; + labelSegment._lineCount = this._lineCount; + + this._applyTextAttribute(labelSegment); + + labelSegment.setAnchorPoint(cc.p(0, 0)); + this._sgNode.addChild(labelSegment); + this._labelSegments.push(labelSegment); + + return labelSegment; + }, + + _updateRichTextWithMaxWidth: function (labelString, labelWidth, styleIndex) { + var fragmentWidth = labelWidth; + var labelSegment; + + if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this.maxWidth) { + //concat previous line + var checkStartIndex = 0; + while (this._lineOffsetX < this.maxWidth) { + var checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length); + var checkString = labelString.substr(checkStartIndex, checkEndIndex); + var checkStringWidth = this._measureText(checkString, styleIndex); + + if(this._lineOffsetX + checkStringWidth < this.maxWidth) { + this._lineOffsetX += checkStringWidth; + checkStartIndex += checkEndIndex; + } else { + + if(checkStartIndex > 0) { + var remainingString = labelString.substr(0, checkStartIndex); + + this._addLabelSegment(remainingString, styleIndex); + + labelString = labelString.substr(checkStartIndex, labelString.length); + fragmentWidth = this._measureText(labelString, styleIndex); + } + this._updateLineInfo(); + break; + } + } + } + if(fragmentWidth > this.maxWidth) { + var fragments = this._fragmentText(labelString, fragmentWidth, styleIndex); + for(var k = 0; k < fragments.length; ++k) { + var splitString = fragments[k]; + + labelSegment = this._addLabelSegment(splitString, styleIndex); + + var labelSize = labelSegment.getContentSize(); + + this._lineOffsetX += labelSize.width; + + if(fragments.length > 1 && k < fragments.length - 1) { + this._updateLineInfo(); + } + } + } else { + this._lineOffsetX += fragmentWidth; + + this._addLabelSegment(labelString, styleIndex); + } + + }, + + _isLastComponentCR: function(stringToken) { + return stringToken.length -1 === stringToken.lastIndexOf("\n"); + }, + + _updateLineInfo: function () { + this._linesWidth.push(this._lineOffsetX); + this._lineOffsetX = 0; + this._lineCount++; + }, + + _updateRichText: function () { + this._textArray = cc.htmlTextParser.parse(this.string); + var sgNode = this._sgNode; + this._resetState(); + + var lastEmptyLine = false; + var label; + var labelSize; + + for (var i = 0; i < this._textArray.length; ++i) { + var text = this._textArray[i].text; + var multilineTexts = text.split("\n"); + + for (var j = 0; j < multilineTexts.length; ++j) { + var labelString = multilineTexts[j]; + if(labelString === "") { + //for continues \n + if(this._isLastComponentCR(text) && j == multilineTexts.length - 1) { + continue; + } + this._updateLineInfo(); + lastEmptyLine = true; + continue; + } + lastEmptyLine = false; + + if(this.maxWidth > 0) { + var labelWidth = this._measureText(labelString, i); + this._updateRichTextWithMaxWidth(labelString, labelWidth, i); + + if(multilineTexts.length > 1 && j < multilineTexts.length - 1) { + this._updateLineInfo(); + } + } else { + label = this._addLabelSegment(labelString, i); + labelSize = label.getContentSize(); + + this._lineOffsetX += labelSize.width; + if(this._lineOffsetX > this._labelWidth) { + this._labelWidth = this._lineOffsetX; + } + + if(multilineTexts.length > 1 && j < multilineTexts.length - 1) { + this._updateLineInfo(); + } + } + } + } + if(!lastEmptyLine) { + this._linesWidth.push(this._lineOffsetX); + } + + if(this.maxWidth > 0) { + this._labelWidth = this.maxWidth; + } + this._labelHeight =this._lineCount * this.lineHeight; + + sgNode._setContentSize(cc.size(this._labelWidth, this._labelHeight)); + + this._updateRichTextPosition(); + }, + + _isCJK_unicode: function(ch) { + var __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/; + var __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g; + var __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/; + return __CHINESE_REG.test(ch) || __JAPANESE_REG.test(ch) || __KOREAN_REG.test(ch); + }, + + //Checking whether the character is a whitespace + _isspace_unicode: function(ch) { + ch = ch.charCodeAt(0); + return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760 || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239 || ch === 8287 || ch === 12288); + }, + + _getFirstWordLen: function(text, startIndex, textLen) { + var character = text.charAt(startIndex); + if (this._isCJK_unicode(character) || this._isspace_unicode(character)) { + return 1; + } + + var len = 1; + for (var index = startIndex + 1; index < textLen; ++index) { + character = text.charAt(index); + if (this._isspace_unicode(character) || this._isCJK_unicode(character)) { + break; + } + len++; + } + + return len; + }, + + _updateRichTextPosition: function () { + this._computeAlignmentOffset(); + + var nextTokenX = 0; + var nextLineIndex = 1; + var totalLineCount = this._lineCount; + for(var i = 0; i < this._labelSegments.length; ++i) { + var label = this._labelSegments[i]; + var lineCount = label._lineCount; + if (lineCount > nextLineIndex) { + nextTokenX = 0; + nextLineIndex = lineCount; + } + var lineOffsetX = this._linesOffsetX[lineCount - 1]; + label.setPositionX(nextTokenX + lineOffsetX); + + var labelSize = label.getContentSize(); + + var positionY = (totalLineCount - lineCount) * this.lineHeight; + + label.setPositionY(positionY); + + if (lineCount === nextLineIndex) { + nextTokenX += labelSize.width; + } + + } + }, + + _applyTextAttribute: function (label) { + var index = label._styleIndex; + label.setLineHeight(this.lineHeight); + label.setVerticalAlign(VerticalAlign.CENTER); + + var textStyle = null; + if(this._textArray[index]) { + textStyle = this._textArray[index].style; + } + if(textStyle && textStyle.color) { + label.setColor(cc.hexToColor(textStyle.color)); + } else { + label.setColor(this.node.color); + } + + if(textStyle && textStyle.size) { + label.setFontSize(textStyle.size); + } else { + label.setFontSize(this.fontSize); + } + + if(textStyle && textStyle.event) { + if(textStyle.event.click) { + label._clickHandler = textStyle.event.click; + } + + if(textStyle.event.hoverin) { + label._hoverinHandler = textStyle.event.hoverin; + } + + if(textStyle.event.hoverout) { + label._hoveroutHandler = textStyle.event.hoverout; + } + } + } + + }); + + cc.RichText = module.exports = RichText; diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index cf89692912..49d5614db4 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -47,4 +47,5 @@ module.exports = [ require('./CCWebView'), require('./CCSpriteDistortion'), require('./CCLabelOutline'), + require('./CCRichText'), ]; diff --git a/cocos2d/core/index.js b/cocos2d/core/index.js index d9eead82ee..fdf6acf4c7 100644 --- a/cocos2d/core/index.js +++ b/cocos2d/core/index.js @@ -34,10 +34,10 @@ if (!CC_EDITOR || !Editor.isMainProcess) { require('./CCNode'); require('./CCScene'); + require('./label/CCHtmlTextParser.js'); require('./components'); require('./graphics'); require('./collider'); - require('./label/CCHtmlTextParser.js'); } require('./base-ui/CCWidgetManager'); diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js index cb7c574303..92f57fc040 100644 --- a/cocos2d/core/label/CCHtmlTextParser.js +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -54,7 +54,7 @@ cc.HtmlTextParser.prototype = { var tagEndIndex = htmlString.indexOf('>', startIndex); if (tagEndIndex === -1) { - cc.error('The tag is invalid!'); + // cc.error('The HTML tag is invalid!'); tagEndIndex = tagBeginIndex; } else if (htmlString.charAt(tagBeginIndex + 1) === '\/'){ this._stack.pop(); @@ -157,7 +157,12 @@ cc.HtmlTextParser.prototype = { index++; } else { //skip the invalid attribute value - eventValue = eventString.match(/(\S)+/)[0]; + var match = eventString.match(/(\S)+/); + if(match) { + eventValue = match[0]; + } else { + eventValue = ""; + } index = eventValue.length; } @@ -204,7 +209,7 @@ cc.HtmlTextParser.prototype = { }, _getEventRegx: function () { - return /^(click|hoverin|hoverout)(\s)*=/; + return /^(click)(\s)*=/; }, _escapeSpecialSymbol: function(str) { @@ -217,3 +222,6 @@ cc.HtmlTextParser.prototype = { return str; } }; + + +cc.htmlTextParser = new cc.HtmlTextParser(); diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 9140092841..12942e0326 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -1120,7 +1120,7 @@ cc.BMFontHelper = { } }, - _computeHorizontalKerningForText: function(text) { + _computeHorizontalKerningForText: function() { var stringLen = this.getStringLength(); var locKerningDict = this._config.kerningDict; @@ -1155,7 +1155,7 @@ cc.BMFontHelper = { var locIsLoaded = texture.isLoaded(); self._textureLoaded = locIsLoaded; if (!locIsLoaded) { - texture.once("load", function(event) { + texture.once("load", function() { var self = this; if (!self._spriteBatchNode) { diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js index 29b4defde3..353d9a41f9 100644 --- a/test/qunit/unit/test-html-text-parser.js +++ b/test/qunit/unit/test-html-text-parser.js @@ -115,9 +115,7 @@ test('Event test', function() { deepEqual(parser.parse(eventTestString), [{text: "hello world", style: { event: { - click : "event1", - hoverin : "event2", - hoverout : "event3" + click : "event1" }}}], "Happy path 1"); var eventTestStringFail1 = "hello world"; @@ -143,7 +141,6 @@ test('Event test', function() { [{text: "hello world", style: { size: 20, event: { - hoverin : "event2", }}}], "Fail path 3"); @@ -164,7 +161,6 @@ test('Event test', function() { size: 20, event: { click : "event1", - hoverin : "event2" } }}], "Size with event"); @@ -259,10 +255,10 @@ test('Integrate test', function() { }); test('bold/italic/underline test', function () { - var stringWithBold = "hello world"; + var stringWithBold = "hello \n world"; deepEqual(parser.parse(stringWithBold), - [{text: "hello world", style: {bold: true}}], "bold test"); + [{text: "hello \n world", style: {bold: true}}], "bold test"); var stringWithItalic = "hello world"; From 9f83695250f447d0f957cc96a55868af0a3f53fb Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 25 Aug 2016 16:47:00 +0800 Subject: [PATCH 04/11] improve performance --- cocos2d/core/components/CCRichText.js | 61 +++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index b74df92102..323ea33b4e 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -89,7 +89,7 @@ var RichText = cc.Class({ }, /** - * !#en Horizontal Alignment of label. + * !#en Horizontal Alignment of each line in RichText. * !#zh 文本内容的水平对齐方式。 * @property {RichText.HorizontalAlign} horizontalAlign */ @@ -104,8 +104,8 @@ var RichText = cc.Class({ }, /** - * !#en Font size of label. - * !#zh 文本字体大小。 + * !#en Font size of RichText. + * !#zh 富文本字体大小。 * @property {Number} fontSize */ fontSize: { @@ -129,8 +129,8 @@ var RichText = cc.Class({ }, /** - * !#en Line Height of label. - * !#zh 文本行高。 + * !#en Line Height of RichText. + * !#zh 富文本行高。 * @property {Number} lineHeight */ lineHeight: { @@ -171,7 +171,7 @@ var RichText = cc.Class({ }, - _updateLabelSegmentColor: function() { + _updateLabelSegmentTextAttributes: function() { this._labelSegments.forEach(function(item) { this._applyTextAttribute(item); }.bind(this)); @@ -192,7 +192,7 @@ var RichText = cc.Class({ var self = this; sgNode.setColor = function () { - self._updateLabelSegmentColor(); + self._updateLabelSegmentTextAttributes(); }; sgNode._setContentSize = sgNode.setContentSize; @@ -442,8 +442,53 @@ var RichText = cc.Class({ this._lineCount++; }, + _needsUpdateTextLayout: function (newTextArray) { + if(!this._textArray || !newTextArray) { + return true; + } + + if(this._textArray.length !== newTextArray.length) { + return true; + } + + for(var i = 0; i < this._textArray.length; ++i) { + var oldItem = this._textArray[i]; + var newItem = newTextArray[i]; + if(oldItem.text != newItem.text) { + return true; + } else { + if (oldItem.style) { + if (newItem.style) { + //TODO: add more when adding bold/italic/underline + if(oldItem.style.size != newItem.style.size) { + return true; + } + } else { + if(oldItem.style.size) { + return true; + } + } + } else { + if (newItem.style) { + if(newItem.style.size) { + return true; + } + } + } + } + } + return false; + }, + _updateRichText: function () { - this._textArray = cc.htmlTextParser.parse(this.string); + var newTextArray = cc.htmlTextParser.parse(this.string); + if(!this._needsUpdateTextLayout(newTextArray)) { + this._textArray = newTextArray; + this._updateLabelSegmentTextAttributes(); + return; + } + + this._textArray = newTextArray; var sgNode = this._sgNode; this._resetState(); From e2de6a3f2ad415d60d491f718c77a5dbb7ae9a31 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 25 Aug 2016 17:40:00 +0800 Subject: [PATCH 05/11] fix layout issue --- cocos2d/core/components/CCRichText.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 323ea33b4e..295bd6bda3 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -99,6 +99,7 @@ var RichText = cc.Class({ tooltip: 'i18n:COMPONENT.label.horizontal_align', animatable: false, notify: function () { + this._layoutDirty = true; this._updateRichTextStatus(); } }, @@ -112,6 +113,7 @@ var RichText = cc.Class({ default: 40, tooltip: 'i18n:COMPONENT.label.font_size', notify: function () { + this._layoutDirty = true; this._updateRichTextStatus(); } }, @@ -124,6 +126,7 @@ var RichText = cc.Class({ maxWidth: { default: 0, notify: function () { + this._layoutDirty = true; this._updateRichTextStatus(); } }, @@ -137,6 +140,7 @@ var RichText = cc.Class({ default: 40, tooltip: 'i18n:COMPONENT.label.line_height', notify: function () { + this._layoutDirty = true; this._updateRichTextStatus(); } } @@ -363,6 +367,7 @@ var RichText = cc.Class({ this._lineCount = 1; this._labelWidth = 0; this._labelHeight = 0; + this._layoutDirty = true; }, _addLabelSegment: function(stringToken, styleIndex) { @@ -443,7 +448,7 @@ var RichText = cc.Class({ }, _needsUpdateTextLayout: function (newTextArray) { - if(!this._textArray || !newTextArray) { + if(this._layoutDirty || !this._textArray || !newTextArray) { return true; } @@ -547,6 +552,7 @@ var RichText = cc.Class({ sgNode._setContentSize(cc.size(this._labelWidth, this._labelHeight)); this._updateRichTextPosition(); + this._layoutDirty = false; }, _isCJK_unicode: function(ch) { From 71aa9aaea187367e2f93c9965148073162e99d97 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 25 Aug 2016 18:28:18 +0800 Subject: [PATCH 06/11] fix jsb effect --- cocos2d/core/components/CCRichText.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 295bd6bda3..c5da2965ab 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -381,6 +381,12 @@ var RichText = cc.Class({ this._sgNode.addChild(labelSegment); this._labelSegments.push(labelSegment); + if(CC_JSB) { + labelSegment.setOverflow(1); + var size = labelSegment.getContentSize(); + labelSegment.setContentSize(size.width, this.lineHeight); + } + return labelSegment; }, From 2f4da7092e2ffbbbce93c35af96c9162d6339c66 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 10:07:08 +0800 Subject: [PATCH 07/11] add RichText to modules.json --- modules.json | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/modules.json b/modules.json index 24fec2d2d5..e3b84c5db5 100644 --- a/modules.json +++ b/modules.json @@ -108,6 +108,12 @@ "./cocos2d/core/components/CCVideoPlayer.js" ] }, + { + "name": "RichText", + "entries": [ + "./cocos2d/core/components/CCRichText.js" + ] + }, { "name": "AudioSource", "entries": [ @@ -153,4 +159,4 @@ "./cocos2d/core/graphics/index.js" ] } -] \ No newline at end of file +] From 5c95065551642ff0f39f5085d3b0ede406d2d180 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 11:50:56 +0800 Subject: [PATCH 08/11] update i18n and fix some minor issues --- cocos2d/core/components/CCRichText.js | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index c5da2965ab..ce92bff21f 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -69,6 +69,7 @@ var RichText = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/RichText', + help: 'i18n:COMPONENT.help_url.richtext', }, @@ -80,9 +81,9 @@ var RichText = cc.Class({ * @property {String} string */ string: { - default: 'Label', + default: 'RichText', multiline: true, - tooltip: 'i18n:COMPONENT.label.string', + tooltip: 'i18n:COMPONENT.richtext.string', notify: function () { this._updateRichTextStatus(); } @@ -96,7 +97,7 @@ var RichText = cc.Class({ horizontalAlign: { default: HorizontalAlign.LEFT, type: HorizontalAlign, - tooltip: 'i18n:COMPONENT.label.horizontal_align', + tooltip: 'i18n:COMPONENT.richtext.horizontal_align', animatable: false, notify: function () { this._layoutDirty = true; @@ -111,7 +112,7 @@ var RichText = cc.Class({ */ fontSize: { default: 40, - tooltip: 'i18n:COMPONENT.label.font_size', + tooltip: 'i18n:COMPONENT.richtext.font_size', notify: function () { this._layoutDirty = true; this._updateRichTextStatus(); @@ -125,6 +126,7 @@ var RichText = cc.Class({ */ maxWidth: { default: 0, + tooltip: 'i18n:COMPONENT.richtext.max_width', notify: function () { this._layoutDirty = true; this._updateRichTextStatus(); @@ -138,7 +140,7 @@ var RichText = cc.Class({ */ lineHeight: { default: 40, - tooltip: 'i18n:COMPONENT.label.line_height', + tooltip: 'i18n:COMPONENT.richtext.line_height', notify: function () { this._layoutDirty = true; this._updateRichTextStatus(); @@ -183,17 +185,12 @@ var RichText = cc.Class({ _initSgNode: function () { + this._resetState(); + var sgNode = this._sgNode = new _ccsg.Node(); + sgNode.setVisible(false); sgNode.setCascadeOpacityEnabled(true); - if (this.enabledInHierarchy && !sgNode.isVisible()) { - sgNode.setVisible(true); - } - - if ( !this.enabledInHierarchy ) { - sgNode.setVisible(false); - } - var self = this; sgNode.setColor = function () { self._updateLabelSegmentTextAttributes(); From ad3cf8076ddad9c52fbda672c2839b33870ad60f Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 14:48:28 +0800 Subject: [PATCH 09/11] add built-in color value support --- cocos2d/core/components/CCRichText.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index ce92bff21f..887c12149d 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -628,7 +628,12 @@ var RichText = cc.Class({ textStyle = this._textArray[index].style; } if(textStyle && textStyle.color) { - label.setColor(cc.hexToColor(textStyle.color)); + var colorValue = textStyle.color.toUpperCase(); + if(cc.Color[colorValue]) { + label.setColor(cc.Color[colorValue]); + } else { + label.setColor(cc.hexToColor(textStyle.color)); + } } else { label.setColor(this.node.color); } From 4a89edb410cb2dc4ee5aad308f89acf4fa7674d4 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 17:38:38 +0800 Subject: [PATCH 10/11] refactoring --- cocos2d/core/components/CCRichText.js | 47 +++++++------------------- cocos2d/core/label/CCHtmlTextParser.js | 9 ++--- 2 files changed, 15 insertions(+), 41 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 887c12149d..99ea3f94df 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -65,6 +65,12 @@ var RichText = cc.Class({ this._textArray = null; this._resetState(); + + if(CC_EDITOR) { + this._updateRichTextStatus = debounce(this._updateRichText, 200); + } else { + this._updateRichTextStatus = this._updateRichText; + } }, editor: CC_EDITOR && { @@ -74,7 +80,6 @@ var RichText = cc.Class({ properties: { - _useOriginalSize: true, /** * !#en Content string of RichText. * !#zh 富文本显示的文本内容。 @@ -148,33 +153,21 @@ var RichText = cc.Class({ } }, - _updateRichTextStatus: function () { - if(this._sgNode) { - if(CC_EDITOR) { - this._debouncedUpdateRichText(); - } else { - this._updateRichText(); - } - } - }, - statics: { HorizontalAlign: HorizontalAlign, VerticalAlign: VerticalAlign }, - _createSgNode: function () { - return null; - }, - __preload: function () { this._super(); - if(CC_EDITOR) { - this._debouncedUpdateRichText = debounce(this._updateRichText, 200); - } else { + + if (!CC_EDITOR) { this._registerEvents(); } + }, + _createSgNode: function () { + return new _ccsg.Node(); }, _updateLabelSegmentTextAttributes: function() { @@ -184,11 +177,7 @@ var RichText = cc.Class({ }, _initSgNode: function () { - - this._resetState(); - - var sgNode = this._sgNode = new _ccsg.Node(); - sgNode.setVisible(false); + var sgNode = this._sgNode; sgNode.setCascadeOpacityEnabled(true); var self = this; @@ -200,10 +189,6 @@ var RichText = cc.Class({ sgNode.setContentSize = function () {}; this._updateRichText(); - - if(CC_JSB) { - sgNode.retain(); - } }, _computeAlignmentOffset: function() { @@ -648,14 +633,6 @@ var RichText = cc.Class({ if(textStyle.event.click) { label._clickHandler = textStyle.event.click; } - - if(textStyle.event.hoverin) { - label._hoverinHandler = textStyle.event.hoverin; - } - - if(textStyle.event.hoverout) { - label._hoveroutHandler = textStyle.event.hoverout; - } } } diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js index 92f57fc040..633714f92d 100644 --- a/cocos2d/core/label/CCHtmlTextParser.js +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -22,6 +22,7 @@ THE SOFTWARE. ****************************************************************************/ +var eventRegx = /^(click)(\s)*=/; /** * A utils class for parsing HTML texts. The parsed results will be an object array. */ @@ -134,7 +135,7 @@ cc.HtmlTextParser.prototype = { _processEventHandler: function (eventString) { var index = 0; var obj = {}; - var eventNames = eventString.match(this._getEventRegx()); + var eventNames = eventString.match(eventRegx); var isValidTag = false; while(eventNames) { var eventName = eventNames[0]; @@ -172,7 +173,7 @@ cc.HtmlTextParser.prototype = { } eventString = eventString.substring(index).trim(); - eventNames = eventString.match(this._getEventRegx()); + eventNames = eventString.match(eventRegx); } return obj; @@ -208,10 +209,6 @@ cc.HtmlTextParser.prototype = { } }, - _getEventRegx: function () { - return /^(click)(\s)*=/; - }, - _escapeSpecialSymbol: function(str) { for(var i = 0; i < this._specialSymbolArray.length; ++i) { var key = this._specialSymbolArray[i][0]; From 5c2adc05390e6cc6076d4a994d7e777bfd8e8f0a Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 17:52:42 +0800 Subject: [PATCH 11/11] refine lineOffsetX calculation --- cocos2d/core/components/CCRichText.js | 39 ++++++++++----------------- 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 99ea3f94df..9191ac9a55 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -191,29 +191,6 @@ var RichText = cc.Class({ this._updateRichText(); }, - _computeAlignmentOffset: function() { - this._linesOffsetX = []; - switch (this.horizontalAlign) { - case cc.TextAlignment.LEFT: - for (var i = 0; i < this._lineCount; ++i) { - this._linesOffsetX.push(0); - } - break; - case cc.TextAlignment.CENTER: - this._linesWidth.forEach(function(lineWidth) { - this._linesOffsetX.push((this._labelWidth - lineWidth) / 2); - }.bind(this)); - break; - case cc.TextAlignment.RIGHT: - this._linesWidth.forEach(function(lineWidth) { - this._linesOffsetX.push(this._labelWidth - lineWidth); - }.bind(this)); - break; - default: - break; - } - }, - _measureText: function (string, styleIndex) { var label = new _ccsg.Label(string); label._styleIndex = styleIndex; @@ -575,7 +552,6 @@ var RichText = cc.Class({ }, _updateRichTextPosition: function () { - this._computeAlignmentOffset(); var nextTokenX = 0; var nextLineIndex = 1; @@ -587,7 +563,20 @@ var RichText = cc.Class({ nextTokenX = 0; nextLineIndex = lineCount; } - var lineOffsetX = this._linesOffsetX[lineCount - 1]; + var lineOffsetX = 0; + switch (this.horizontalAlign) { + case cc.TextAlignment.LEFT: + lineOffsetX = 0; + break; + case cc.TextAlignment.CENTER: + lineOffsetX = (this._labelWidth - this._linesWidth[lineCount - 1]) / 2; + break; + case cc.TextAlignment.RIGHT: + lineOffsetX = this._labelWidth - this._linesWidth[lineCount - 1]; + break; + default: + break; + } label.setPositionX(nextTokenX + lineOffsetX); var labelSize = label.getContentSize();