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