@galacean/effects-plugin-rich-text 2.1.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,537 @@
1
+ /*!
2
+ * Name: @galacean/effects-plugin-rich-text
3
+ * Description: Galacean Effects player richtext plugin
4
+ * Author: Ant Group CO., Ltd.
5
+ * Contributors: 云垣
6
+ * Version: v2.1.0-alpha.12
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ Object.defineProperty(exports, '__esModule', { value: true });
12
+
13
+ var EFFECTS = require('@galacean/effects');
14
+
15
+ function _interopNamespace(e) {
16
+ if (e && e.__esModule) return e;
17
+ var n = Object.create(null);
18
+ if (e) {
19
+ Object.keys(e).forEach(function (k) {
20
+ if (k !== 'default') {
21
+ var d = Object.getOwnPropertyDescriptor(e, k);
22
+ Object.defineProperty(n, k, d.get ? d : {
23
+ enumerable: true,
24
+ get: function () { return e[k]; }
25
+ });
26
+ }
27
+ });
28
+ }
29
+ n["default"] = e;
30
+ return Object.freeze(n);
31
+ }
32
+
33
+ var EFFECTS__namespace = /*#__PURE__*/_interopNamespace(EFFECTS);
34
+
35
+ function _set_prototype_of(o, p) {
36
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
37
+ o.__proto__ = p;
38
+ return o;
39
+ };
40
+ return _set_prototype_of(o, p);
41
+ }
42
+
43
+ function _inherits(subClass, superClass) {
44
+ if (typeof superClass !== "function" && superClass !== null) {
45
+ throw new TypeError("Super expression must either be null or a function");
46
+ }
47
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
48
+ constructor: {
49
+ value: subClass,
50
+ writable: true,
51
+ configurable: true
52
+ }
53
+ });
54
+ if (superClass) _set_prototype_of(subClass, superClass);
55
+ }
56
+
57
+ var RichTextLoader = /*#__PURE__*/ function(AbstractPlugin) {
58
+ _inherits(RichTextLoader, AbstractPlugin);
59
+ function RichTextLoader() {
60
+ var _this;
61
+ _this = AbstractPlugin.apply(this, arguments) || this;
62
+ _this.name = "richtext";
63
+ return _this;
64
+ }
65
+ return RichTextLoader;
66
+ }(EFFECTS.AbstractPlugin);
67
+
68
+ function _array_like_to_array(arr, len) {
69
+ if (len == null || len > arr.length) len = arr.length;
70
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
71
+ return arr2;
72
+ }
73
+
74
+ function _unsupported_iterable_to_array(o, minLen) {
75
+ if (!o) return;
76
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
77
+ var n = Object.prototype.toString.call(o).slice(8, -1);
78
+ if (n === "Object" && o.constructor) n = o.constructor.name;
79
+ if (n === "Map" || n === "Set") return Array.from(n);
80
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
81
+ }
82
+
83
+ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
84
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
85
+ if (it) return (it = it.call(o)).next.bind(it);
86
+ // Fallback for engines without symbol support
87
+ if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike && o && typeof o.length === "number") {
88
+ if (it) o = it;
89
+ var i = 0;
90
+ return function() {
91
+ if (i >= o.length) return {
92
+ done: true
93
+ };
94
+ return {
95
+ done: false,
96
+ value: o[i++]
97
+ };
98
+ };
99
+ }
100
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
101
+ }
102
+
103
+ var TokenType;
104
+ (function(TokenType) {
105
+ TokenType["ContextStart"] = "ContextStart";
106
+ TokenType["Text"] = "Text";
107
+ TokenType["ContextEnd"] = "ContextEnd";
108
+ })(TokenType || (TokenType = {}));
109
+ var contextStartRegexp = /^<([a-z]+)(=([^>]+))?>$/;
110
+ var contextEndRegexp = /^<\/([a-z]+)>$/;
111
+ var rules = [
112
+ [
113
+ "ContextStart",
114
+ /^<[a-z]+(=[^>]+)?>/
115
+ ],
116
+ [
117
+ "Text",
118
+ /^[^</>=]+/
119
+ ],
120
+ [
121
+ "ContextEnd",
122
+ /^<\/[a-z]+>/
123
+ ]
124
+ ];
125
+ var lexer = function(input, lexed, cursor) {
126
+ if (lexed === void 0) lexed = [];
127
+ if (cursor === void 0) cursor = 0;
128
+ if (!input) {
129
+ return lexed;
130
+ }
131
+ for(var _iterator = _create_for_of_iterator_helper_loose(rules), _step; !(_step = _iterator()).done;){
132
+ var _step_value = _step.value, tokenType = _step_value[0], regex = _step_value[1];
133
+ var _regex_exec;
134
+ var _ref = (_regex_exec = regex.exec(input)) != null ? _regex_exec : [], tokenMatch = _ref[0];
135
+ if (tokenMatch) {
136
+ var len = tokenMatch.length;
137
+ return lexer(input.slice(len), lexed.concat({
138
+ tokenType: tokenType,
139
+ value: tokenMatch
140
+ }), cursor + len);
141
+ }
142
+ }
143
+ throw new Error('Unexpected token: "' + input[0] + '" at position ' + cursor + ' while reading "' + input + '"');
144
+ };
145
+ var richTextParser = function(input) {
146
+ var Text = function Text() {
147
+ var maybeText = peek();
148
+ if ((maybeText == null ? void 0 : maybeText.tokenType) === "Text") {
149
+ shift();
150
+ return maybeText.value;
151
+ }
152
+ return undefined;
153
+ };
154
+ var ContextStart = function ContextStart() {
155
+ var maybeContextStart = peek();
156
+ if ((maybeContextStart == null ? void 0 : maybeContextStart.tokenType) === "ContextStart") {
157
+ shift();
158
+ var matches = maybeContextStart.value.match(contextStartRegexp);
159
+ if (matches) {
160
+ var attributeName = matches[1];
161
+ var _matches_;
162
+ var attributeParam = (_matches_ = matches[3]) != null ? _matches_ : "";
163
+ return {
164
+ attributeName: attributeName,
165
+ attributeParam: attributeParam
166
+ };
167
+ }
168
+ throw new Error("Expected a font style start tag at position " + cursor);
169
+ }
170
+ return {};
171
+ };
172
+ var ContextEnd = function ContextEnd() {
173
+ var maybeContextEnd = peek();
174
+ if ((maybeContextEnd == null ? void 0 : maybeContextEnd.tokenType) === "ContextEnd") {
175
+ shift();
176
+ var matches = maybeContextEnd.value.match(contextEndRegexp);
177
+ if (matches) {
178
+ var attributeName = matches[1];
179
+ return {
180
+ attributeName: attributeName
181
+ };
182
+ }
183
+ throw new Error("Expected a font style end tag at position " + cursor);
184
+ }
185
+ return {};
186
+ };
187
+ var lexed = lexer(input);
188
+ var cursor = 0;
189
+ var shift = function() {
190
+ var shifted = lexed.shift();
191
+ var _shifted_value_length;
192
+ cursor += (_shifted_value_length = shifted == null ? void 0 : shifted.value.length) != null ? _shifted_value_length : 0;
193
+ return shifted;
194
+ };
195
+ var peek = function() {
196
+ return lexed[0];
197
+ };
198
+ var ast = [];
199
+ function Grammar(attributes, expectedEndAttributeName) {
200
+ if (attributes === void 0) attributes = [];
201
+ if (expectedEndAttributeName === void 0) expectedEndAttributeName = "";
202
+ var parsing = true;
203
+ while(parsing){
204
+ var maybeText = Text();
205
+ if (maybeText) {
206
+ ast.push({
207
+ attributes: attributes,
208
+ text: maybeText
209
+ });
210
+ continue;
211
+ }
212
+ var _ContextStart = ContextStart(), attributeName = _ContextStart.attributeName, attributeParam = _ContextStart.attributeParam;
213
+ if (attributeName) {
214
+ Grammar(attributes.concat({
215
+ attributeName: attributeName,
216
+ attributeParam: attributeParam
217
+ }), attributeName);
218
+ continue;
219
+ }
220
+ if (expectedEndAttributeName) {
221
+ var _ContextEnd = ContextEnd(), endAttributeName = _ContextEnd.attributeName;
222
+ if (!endAttributeName) {
223
+ throw new Error('Expected end of font style with tag "' + expectedEndAttributeName + '" at position ' + cursor + " but not found any tag!");
224
+ }
225
+ if (endAttributeName !== expectedEndAttributeName) {
226
+ throw new Error('Expected end of font style with tag "' + expectedEndAttributeName + '" at position ' + cursor + ' but found tag "' + endAttributeName + '"');
227
+ }
228
+ return;
229
+ }
230
+ break;
231
+ }
232
+ }
233
+ Grammar();
234
+ return ast;
235
+ };
236
+ function generateProgram(textHandler) {
237
+ return function(richText) {
238
+ var ast = richTextParser(richText);
239
+ for(var _iterator = _create_for_of_iterator_helper_loose(ast), _step; !(_step = _iterator()).done;){
240
+ var node = _step.value;
241
+ var text = node.text;
242
+ var context = node.attributes.reduce(function(ctx, param) {
243
+ var attributeName = param.attributeName, attributeParam = param.attributeParam;
244
+ if (attributeName) {
245
+ ctx[attributeName] = attributeParam;
246
+ }
247
+ return ctx;
248
+ }, {});
249
+ textHandler(text, context);
250
+ }
251
+ };
252
+ }
253
+ function isRichText(text) {
254
+ var lexed = lexer(text);
255
+ var contextTokens = lexed.filter(function(param) {
256
+ var tokenType = param.tokenType;
257
+ return tokenType === "ContextStart" || tokenType === "ContextEnd";
258
+ });
259
+ var contextStartTokens = contextTokens.filter(function(param) {
260
+ var tokenType = param.tokenType;
261
+ return tokenType === "ContextStart";
262
+ });
263
+ var contextEndTokens = contextTokens.filter(function(param) {
264
+ var tokenType = param.tokenType;
265
+ return tokenType === "ContextEnd";
266
+ });
267
+ if (contextStartTokens.length !== contextEndTokens.length || !contextStartTokens.length) {
268
+ return false;
269
+ }
270
+ var tokensOfAttribute = contextTokens.map(function(param) {
271
+ var tokenType = param.tokenType, value = param.value;
272
+ return {
273
+ tokenType: tokenType,
274
+ value: tokenType === "ContextStart" ? value.match(contextStartRegexp)[1] : value.match(contextEndRegexp)[1]
275
+ };
276
+ });
277
+ function checkPaired(param, startContextAttributes) {
278
+ var token = param[0], restToken = param.slice(1);
279
+ if (startContextAttributes === void 0) startContextAttributes = [];
280
+ if (!token) {
281
+ return startContextAttributes.length === 0;
282
+ }
283
+ if (token.tokenType === "ContextStart") {
284
+ return checkPaired(restToken, startContextAttributes.concat(token.value));
285
+ } else if (token.tokenType === "ContextEnd") {
286
+ var attributeName = startContextAttributes[startContextAttributes.length - 1];
287
+ if (attributeName !== token.value) {
288
+ return false;
289
+ }
290
+ return checkPaired(restToken, startContextAttributes.slice(0, -1));
291
+ }
292
+ throw new Error("Unexpected token: " + token.tokenType);
293
+ }
294
+ return checkPaired(tokensOfAttribute);
295
+ }
296
+
297
+ function __decorate(decorators, target, key, desc) {
298
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
299
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
300
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
301
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
302
+ }
303
+ typeof SuppressedError === "function" ? SuppressedError : function _SuppressedError(error, suppressed, message) {
304
+ var e = new Error(message);
305
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
306
+ };
307
+
308
+ /**
309
+ * 将颜色名称转换为 RGBA
310
+ * @param colorName - 颜色名称
311
+ * @returns RGBA 颜色字符串
312
+ */ function colorNameToRGBA(colorName) {
313
+ if (typeof colorName !== "string" || !colorName) {
314
+ throw new Error("Invalid color name provided");
315
+ }
316
+ if (typeof document === "undefined") {
317
+ throw new Error("This method requires a browser environment");
318
+ }
319
+ var canvas = document.createElement("canvas");
320
+ var context = canvas.getContext("2d");
321
+ if (context) {
322
+ try {
323
+ context.fillStyle = colorName;
324
+ var result = context.fillStyle;
325
+ return result;
326
+ } finally{
327
+ // Clean up DOM element
328
+ canvas.remove();
329
+ }
330
+ }
331
+ throw new Error("Failed to get 2D context for color conversion!");
332
+ }
333
+ /**
334
+ * 将 16 进制颜色转换为 RGBA
335
+ * @param hex - 16 进制颜色
336
+ * @param alpha - 透明度
337
+ * @returns - RGBA 颜色
338
+ */ function hexToRGBA(hex, alpha) {
339
+ if (alpha === void 0) alpha = 1;
340
+ hex = hex.replace(/^#/, "");
341
+ if (hex.length === 3 || hex.length === 4) {
342
+ hex = hex.split("").map(function(char) {
343
+ return char + char;
344
+ }).join("");
345
+ }
346
+ // Handle alpha channel in hex
347
+ if (hex.length === 8) {
348
+ var a = parseInt(hex.slice(6, 8), 16) / 255;
349
+ hex = hex.slice(0, 6);
350
+ alpha = a;
351
+ }
352
+ var bigint = parseInt(hex, 16);
353
+ var r = bigint >> 16 & 255;
354
+ var g = bigint >> 8 & 255;
355
+ var b = bigint & 255;
356
+ return [
357
+ r,
358
+ g,
359
+ b,
360
+ alpha
361
+ ];
362
+ }
363
+ /**
364
+ * 将颜色字符串转换为 RGBA
365
+ * @param color - 颜色字符串
366
+ * @param alpha - 透明度
367
+ * @returns - RGBA 颜色
368
+ */ function toRGBA(color, alpha) {
369
+ if (alpha === void 0) alpha = 1;
370
+ if (typeof color !== "string" || !color) {
371
+ throw new Error("Invalid color string");
372
+ }
373
+ if (color.startsWith("#")) {
374
+ return hexToRGBA(color, alpha);
375
+ } else {
376
+ return hexToRGBA(colorNameToRGBA(color));
377
+ }
378
+ }
379
+
380
+ var seed = 0;
381
+ exports.RichTextComponent = /*#__PURE__*/ function(TextComponent) {
382
+ _inherits(RichTextComponent, TextComponent);
383
+ function RichTextComponent(engine) {
384
+ var _this;
385
+ _this = TextComponent.call(this, engine) || this;
386
+ _this.processedTextOptions = [];
387
+ _this.singleLineHeight = 1.571;
388
+ _this.name = "MRichText" + seed++;
389
+ return _this;
390
+ }
391
+ var _proto = RichTextComponent.prototype;
392
+ _proto.generateTextProgram = function generateTextProgram(text) {
393
+ var _this = this;
394
+ var program = generateProgram(function(text, context) {
395
+ var textArr = text.split("\n");
396
+ textArr.forEach(function(text, index) {
397
+ var options = {
398
+ text: text,
399
+ fontSize: _this.textStyle.fontSize,
400
+ isNewLine: false
401
+ };
402
+ if (index > 0) {
403
+ options.isNewLine = true;
404
+ }
405
+ if ("b" in context) {
406
+ options.fontWeight = EFFECTS.spec.TextWeight.bold;
407
+ }
408
+ if ("i" in context) {
409
+ options.fontStyle = EFFECTS.spec.FontStyle.italic;
410
+ }
411
+ if ("size" in context && context.size) {
412
+ options.fontSize = parseInt(context.size, 10);
413
+ }
414
+ if ("color" in context && context.color) {
415
+ options.fontColor = toRGBA(context.color);
416
+ }
417
+ _this.processedTextOptions.push(options);
418
+ });
419
+ });
420
+ program(text);
421
+ };
422
+ _proto.updateTexture = function updateTexture(flipY) {
423
+ var _this = this;
424
+ if (flipY === void 0) flipY = true;
425
+ if (!this.isDirty || !this.context || !this.canvas) {
426
+ return;
427
+ }
428
+ this.generateTextProgram(this.text);
429
+ var width = 0, height = 0;
430
+ var _this1 = this, textLayout = _this1.textLayout, textStyle = _this1.textStyle;
431
+ var context = this.context;
432
+ var charsInfo = [];
433
+ var fontHeight = textStyle.fontSize * this.textStyle.fontScale;
434
+ var charInfo = {
435
+ richOptions: [],
436
+ offsetX: [],
437
+ width: 0,
438
+ lineHeight: fontHeight * this.singleLineHeight,
439
+ offsetY: fontHeight * (this.singleLineHeight - 1) / 2
440
+ };
441
+ this.processedTextOptions.forEach(function(options, index) {
442
+ var text = options.text, isNewLine = options.isNewLine, fontSize = options.fontSize;
443
+ if (isNewLine) {
444
+ charsInfo.push(charInfo);
445
+ width = Math.max(width, charInfo.width);
446
+ charInfo = {
447
+ richOptions: [],
448
+ offsetX: [],
449
+ width: 0,
450
+ lineHeight: fontHeight * _this.singleLineHeight,
451
+ offsetY: fontHeight * (_this.singleLineHeight - 1) / 2
452
+ };
453
+ height += charInfo.lineHeight;
454
+ }
455
+ var textWidth = context.measureText(text).width;
456
+ var textHeight = fontSize * _this.singleLineHeight * _this.textStyle.fontScale;
457
+ if (textHeight > charInfo.lineHeight) {
458
+ height += textHeight - charInfo.lineHeight;
459
+ charInfo.lineHeight = textHeight;
460
+ charInfo.offsetY = fontSize * _this.textStyle.fontScale * (_this.singleLineHeight - 1) / 2;
461
+ }
462
+ charInfo.offsetX.push(charInfo.width);
463
+ charInfo.width += textWidth * fontSize * _this.SCALE_FACTOR * _this.textStyle.fontScale;
464
+ charInfo.richOptions.push(options);
465
+ });
466
+ charsInfo.push(charInfo);
467
+ width = Math.max(width, charInfo.width);
468
+ height += charInfo.lineHeight;
469
+ var scale = width / height;
470
+ this.item.transform.size.set(textStyle.fontSize * this.SCALE_FACTOR, textStyle.fontSize * this.SCALE_FACTOR * scale);
471
+ this.textLayout.width = width / textStyle.fontScale;
472
+ this.textLayout.height = height / textStyle.fontScale;
473
+ this.canvas.width = width;
474
+ this.canvas.height = height;
475
+ context.clearRect(0, 0, width, height);
476
+ // fix bug 1/255
477
+ context.fillStyle = "rgba(255, 255, 255, " + this.ALPHA_FIX_VALUE + ")";
478
+ if (!flipY) {
479
+ context.translate(0, height);
480
+ context.scale(1, -1);
481
+ }
482
+ var charsLineHeight = charsInfo[0].lineHeight - charsInfo[0].offsetY;
483
+ charsInfo.forEach(function(charInfo, index) {
484
+ var richOptions = charInfo.richOptions, offsetX = charInfo.offsetX;
485
+ var x = textLayout.getOffsetX(textStyle, charInfo.width);
486
+ if (index > 0) {
487
+ charsLineHeight += charInfo.lineHeight - charInfo.offsetY + charsInfo[index - 1].offsetY;
488
+ }
489
+ richOptions.forEach(function(options, index) {
490
+ var fontScale = textStyle.fontScale, textColor = textStyle.textColor, textFamily = textStyle.fontFamily, textWeight = textStyle.textWeight, richStyle = textStyle.fontStyle;
491
+ var text = options.text, fontSize = options.fontSize, _options_fontColor = options.fontColor, fontColor = _options_fontColor === void 0 ? textColor : _options_fontColor, _options_fontFamily = options.fontFamily, fontFamily = _options_fontFamily === void 0 ? textFamily : _options_fontFamily, _options_fontWeight = options.fontWeight, fontWeight = _options_fontWeight === void 0 ? textWeight : _options_fontWeight, _options_fontStyle = options.fontStyle, fontStyle = _options_fontStyle === void 0 ? richStyle : _options_fontStyle;
492
+ context.font = fontStyle + " " + fontWeight + " " + fontSize * fontScale + "px " + fontFamily;
493
+ context.fillStyle = "rgba(" + fontColor[0] + ", " + fontColor[1] + ", " + fontColor[2] + ", " + fontColor[3] + ")";
494
+ context.fillText(text, offsetX[index] + x, charsLineHeight);
495
+ });
496
+ });
497
+ //与 toDataURL() 两种方式都需要像素读取操作
498
+ var imageData = context.getImageData(0, 0, this.canvas.width, this.canvas.height);
499
+ this.material.setTexture("uSampler0", EFFECTS.Texture.createWithData(this.engine, {
500
+ data: new Uint8Array(imageData.data),
501
+ width: imageData.width,
502
+ height: imageData.height
503
+ }, {
504
+ flipY: flipY,
505
+ magFilter: EFFECTS.glContext.LINEAR,
506
+ minFilter: EFFECTS.glContext.LINEAR,
507
+ wrapS: EFFECTS.glContext.CLAMP_TO_EDGE,
508
+ wrapT: EFFECTS.glContext.CLAMP_TO_EDGE
509
+ }));
510
+ this.isDirty = false;
511
+ };
512
+ _proto.updateWithOptions = function updateWithOptions(options) {
513
+ this.textStyle = new EFFECTS.TextStyle(options);
514
+ this.textLayout = new EFFECTS.TextLayout(options);
515
+ this.text = options.text ? options.text.toString() : "";
516
+ };
517
+ return RichTextComponent;
518
+ }(EFFECTS.TextComponent);
519
+ exports.RichTextComponent = __decorate([
520
+ EFFECTS.effectsClass(EFFECTS.spec.DataType.RichTextComponent)
521
+ ], exports.RichTextComponent);
522
+
523
+ /**
524
+ * 插件版本号
525
+ */ var version = "2.1.0-alpha.12";
526
+ EFFECTS.registerPlugin("richtext", RichTextLoader, EFFECTS.VFXItem, true);
527
+ EFFECTS.logger.info("Plugin rich text version: " + version + ".");
528
+ if (version !== EFFECTS__namespace.version) {
529
+ console.error("注意:请统一 RichText 插件与 Player 版本,不统一的版本混用会有不可预知的后果!", "\nAttention: Please ensure the RichText plugin is synchronized with the Player version. Mixing and matching incompatible versions may result in unpredictable consequences!");
530
+ }
531
+
532
+ exports.generateProgram = generateProgram;
533
+ exports.isRichText = isRichText;
534
+ exports.lexer = lexer;
535
+ exports.richTextParser = richTextParser;
536
+ exports.version = version;
537
+ //# sourceMappingURL=index.js.map