This repository has been archived by the owner on Feb 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathHTMLText.ts
521 lines (439 loc) · 15.9 KB
/
HTMLText.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import { Sprite } from '@pixi/sprite';
import { Texture, Rectangle, settings, utils, ISize, ImageResource } from '@pixi/core';
import { TextStyle } from '@pixi/text';
import { HTMLTextStyle } from './HTMLTextStyle';
import type { ITextStyle } from '@pixi/text';
import type { Renderer, IRenderer } from '@pixi/core';
import type { IDestroyOptions } from '@pixi/display';
/**
* Text display object that support multi-style HTML text.
* @class
* @extends PIXI.Sprite
* @see {@link https://pixijs.download/dev/docs/PIXI.Sprite.html PIXI.Sprite}
* @see {@link https://pixijs.download/dev/docs/PIXI.TextStyle.html PIXI.TextStyle}
*/
export class HTMLText extends Sprite
{
/**
* Default opens when destroying.
* @type {PIXI.IDestroyOptions}
* @property {boolean} texture=true - Whether to destroy the texture.
* @property {boolean} children=false - Whether to destroy the children.
* @property {boolean} baseTexture=true - Whether to destroy the base texture.
*/
public static defaultDestroyOptions: IDestroyOptions = {
texture: true,
children: false,
baseTexture: true,
};
/** Default maxWidth, set at construction */
public static defaultMaxWidth = 2024;
/** Default maxHeight, set at construction */
public static defaultMaxHeight = 2024;
/** Default resolution, make sure autoResolution or defaultAutoResolution is `false`. */
public static defaultResolution: number | undefined;
/** Default autoResolution for all HTMLText objects */
public static defaultAutoResolution = true;
/** The maximum width in rendered pixels that the content can be, any larger will be hidden */
public maxWidth: number;
/** The maximum height in rendered pixels that the content can be, any larger will be hidden */
public maxHeight: number;
private _domElement: HTMLElement;
private _styleElement: HTMLElement;
private _svgRoot: SVGSVGElement;
private _foreignObject: SVGForeignObjectElement;
private _image: HTMLImageElement;
private _loadImage: HTMLImageElement;
private _resolution: number;
private _text: string | null = null;
private _style: HTMLTextStyle | null = null;
private _autoResolution = true;
private _loading = false;
private localStyleID = -1;
private dirty = false;
/** The HTMLTextStyle object is owned by this instance */
private ownsStyle = false;
/**
* @param {string} [text] - Text contents
* @param {HTMLTextStyle|PIXI.TextStyle|PIXI.ITextStyle} [style] - Style setting to use.
* Strongly recommend using an HTMLTextStyle object. Providing a PIXI.TextStyle
* will convert the TextStyle to an HTMLTextStyle and will no longer be linked.
*/
constructor(text = '', style: HTMLTextStyle | TextStyle | Partial<ITextStyle> = {})
{
const image = new Image();
const texture = Texture.from<ImageResource>(image, {
scaleMode: settings.SCALE_MODE,
resourceOptions: {
autoLoad: false,
},
});
texture.orig = new Rectangle();
texture.trim = new Rectangle();
super(texture);
const nssvg = 'http://www.w3.org/2000/svg';
const nsxhtml = 'http://www.w3.org/1999/xhtml';
const svgRoot = document.createElementNS(nssvg, 'svg');
const foreignObject = document.createElementNS(nssvg, 'foreignObject');
const domElement = document.createElementNS(nsxhtml, 'div');
const styleElement = document.createElementNS(nsxhtml, 'style');
// Arbitrary max size
foreignObject.setAttribute('width', '10000');
foreignObject.setAttribute('height', '10000');
foreignObject.style.overflow = 'hidden';
svgRoot.appendChild(foreignObject);
this.maxWidth = HTMLText.defaultMaxWidth;
this.maxHeight = HTMLText.defaultMaxHeight;
this._domElement = domElement;
this._styleElement = styleElement;
this._svgRoot = svgRoot;
this._foreignObject = foreignObject;
this._foreignObject.appendChild(styleElement);
this._foreignObject.appendChild(domElement);
this._image = image;
this._loadImage = new Image();
this._autoResolution = HTMLText.defaultAutoResolution;
this._resolution = HTMLText.defaultResolution ?? settings.RESOLUTION;
this.text = text;
this.style = style;
}
/**
* Calculate the size of the output text without actually drawing it.
* This includes the `padding` in the `style` object.
* This can be used as a fast-pass to do things like text-fitting.
* @param {object} [overrides] - Overrides for the text, style, and resolution.
* @param {string} [overrides.text] - The text to measure, if not specified, the current text is used.
* @param {HTMLTextStyle} [overrides.style] - The style to measure, if not specified, the current style is used.
* @param {number} [overrides.resolution] - The resolution to measure, if not specified, the current resolution is used.
* @return {PIXI.ISize} Width and height of the measured text.
*/
measureText(overrides?: { text?: string, style?: HTMLTextStyle, resolution?: number }): ISize
{
const { text, style, resolution } = Object.assign({
text: this._text,
style: this._style,
resolution: this._resolution,
}, overrides);
Object.assign(this._domElement, {
innerHTML: text,
style: style.toCSS(resolution),
});
this._styleElement.textContent = style.toGlobalCSS();
// Measure the contents using the shadow DOM
document.body.appendChild(this._svgRoot);
const contentBounds = this._domElement.getBoundingClientRect();
this._svgRoot.remove();
const contentWidth = Math.min(this.maxWidth, Math.ceil(contentBounds.width));
const contentHeight = Math.min(this.maxHeight, Math.ceil(contentBounds.height));
this._svgRoot.setAttribute('width', contentWidth.toString());
this._svgRoot.setAttribute('height', contentHeight.toString());
// Undo the changes to the DOM element
if (text !== this._text)
{
this._domElement.innerHTML = this._text as string;
}
if (style !== this._style)
{
Object.assign(this._domElement, { style: this._style?.toCSS(resolution) });
this._styleElement.textContent = this._style?.toGlobalCSS() as string;
}
return {
width: contentWidth + (style.padding * 2),
height: contentHeight + (style.padding * 2),
};
}
/**
* Manually refresh the text.
* @public
* @param {boolean} respectDirty - Whether to abort updating the
* text if the Text isn't dirty and the function is called.
*/
async updateText(respectDirty = true): Promise<void>
{
const { style, _image: image, _loadImage: loadImage } = this;
// check if style has changed..
if (this.localStyleID !== style.styleID)
{
this.dirty = true;
this.localStyleID = style.styleID;
}
if (!this.dirty && respectDirty)
{
return;
}
const { width, height } = this.measureText();
// Make sure canvas is at least 1x1 so it drawable
// for sub-pixel sizes, round up to avoid clipping
// we update both images, to make sure bounds are correct synchronously
image.width = loadImage.width = Math.ceil((Math.max(1, width)));
image.height = loadImage.height = Math.ceil((Math.max(1, height)));
if (!this._loading)
{
this._loading = true;
await new Promise<void>((resolve) =>
{
loadImage.onload = async () =>
{
// Fake waiting for the image to load
await style.onBeforeDraw();
this._loading = false;
// Swap image and loadImage, we do this to avoid
// flashes between updateText calls, usually when
// the onload time is longer than updateText time
image.src = loadImage.src;
loadImage.onload = null;
loadImage.src = '';
// Force update the texture
this.updateTexture();
resolve();
};
const svgURL = new XMLSerializer().serializeToString(this._svgRoot);
loadImage.src = `data:image/svg+xml;charset=utf8,${encodeURIComponent(svgURL)}`;
});
}
}
/** The raw image element that is rendered under-the-hood. */
public get source(): HTMLImageElement
{
return this._image;
}
/**
* @deprecated since 3.2.0
* @see HTMLText#image
*/
public get canvas(): HTMLImageElement
{
utils.deprecation('3.2.0', 'HTMLText property "canvas" is deprecated, use "source" instead.');
return this._image;
}
/**
* Update the texture resource.
* @private
*/
updateTexture()
{
const { style, texture, _image: image, resolution } = this;
const { padding } = style;
const { baseTexture } = texture;
texture.trim.width = texture._frame.width = image.width / resolution;
texture.trim.height = texture._frame.height = image.height / resolution;
texture.trim.x = -padding;
texture.trim.y = -padding;
texture.orig.width = texture._frame.width - (padding * 2);
texture.orig.height = texture._frame.height - (padding * 2);
// call sprite onTextureUpdate to update scale if _width or _height were set
this._onTextureUpdate();
baseTexture.setRealSize(image.width, image.height, resolution);
this.dirty = false;
}
/**
* Renders the object using the WebGL renderer
*
* @param {PIXI.Renderer} renderer - The renderer
* @private
*/
_render(renderer: Renderer)
{
if (this._autoResolution && this._resolution !== renderer.resolution)
{
this._resolution = renderer.resolution;
this.dirty = true;
}
this.updateText(true);
super._render(renderer);
}
/**
* Renders the object using the Canvas Renderer.
*
* @private
* @param {PIXI.CanvasRenderer} renderer - The renderer
*/
_renderCanvas(renderer: IRenderer)
{
if (this._autoResolution && this._resolution !== renderer.resolution)
{
this._resolution = renderer.resolution;
this.dirty = true;
}
this.updateText(true);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
super._renderCanvas(renderer);
}
/**
* Get the local bounds.
*
* @param {PIXI.Rectangle} rect - Input rectangle.
* @return {PIXI.Rectangle} Local bounds
*/
getLocalBounds(rect: Rectangle)
{
this.updateText(true);
return super.getLocalBounds(rect);
}
_calculateBounds()
{
this.updateText(true);
this.calculateVertices();
// if we have already done this on THIS frame.
(this as any)._bounds.addQuad(this.vertexData);
}
/**
* Handle dirty style changes
* @private
*/
_onStyleChange()
{
this.dirty = true;
}
/**
* Destroy this Text object. Don't use after calling.
* @param {boolean|object} options - Same as Sprite destroy options.
*/
destroy(options?: boolean | IDestroyOptions | undefined)
{
if (typeof options === 'boolean')
{
options = { children: options };
}
options = Object.assign({}, HTMLText.defaultDestroyOptions, options);
super.destroy(options);
const forceClear: any = null;
// Remove any loaded fonts if we created the HTMLTextStyle
if (this.ownsStyle)
{
this._style?.cleanFonts();
}
this._style = forceClear;
this._svgRoot?.remove();
this._svgRoot = forceClear;
this._domElement?.remove();
this._domElement = forceClear;
this._foreignObject?.remove();
this._foreignObject = forceClear;
this._styleElement?.remove();
this._styleElement = forceClear;
this._loadImage.src = '';
this._loadImage.onload = null;
this._loadImage = forceClear;
this._image.src = '';
this._image = forceClear;
}
/**
* Get the width in pixels.
* @member {number}
*/
get width()
{
this.updateText(true);
return Math.abs(this.scale.x) * this._image.width / this.resolution;
}
set width(value) // eslint-disable-line require-jsdoc
{
this.updateText(true);
const s = utils.sign(this.scale.x) || 1;
this.scale.x = s * value / this._image.width / this.resolution;
this._width = value;
}
/**
* Get the height in pixels.
* @member {number}
*/
get height()
{
this.updateText(true);
return Math.abs(this.scale.y) * this._image.height / this.resolution;
}
set height(value) // eslint-disable-line require-jsdoc
{
this.updateText(true);
const s = utils.sign(this.scale.y) || 1;
this.scale.y = s * value / this._image.height / this.resolution;
this._height = value;
}
/** The base style to render with text. */
get style(): HTMLTextStyle
{
return this._style as HTMLTextStyle;
}
set style(style: HTMLTextStyle | TextStyle | Partial<ITextStyle>) // eslint-disable-line require-jsdoc
{
// Don't do anything if we're re-assigning
if (this._style === style)
{
return;
}
style = style || {};
if (style instanceof HTMLTextStyle)
{
this.ownsStyle = false;
this._style = style;
}
// Clone TextStyle
else if (style instanceof TextStyle)
{
console.warn('[HTMLText] Cloning TextStyle, if this is not what you want, use HTMLTextStyle');
this.ownsStyle = true;
this._style = HTMLTextStyle.from(style);
}
else
{
this.ownsStyle = true;
this._style = new HTMLTextStyle(style);
}
this.localStyleID = -1;
this.dirty = true;
}
/**
* Contents of text. This can be HTML text and include tags.
* @example
* const text = new HTMLText('This is a <em>styled</em> text!');
* @member {string}
*/
get text()
{
return this._text;
}
set text(text) // eslint-disable-line require-jsdoc
{
text = String(text === '' || text === null || text === undefined ? ' ' : text);
text = this.sanitiseText(text);
if (this._text === text)
{
return;
}
this._text = text;
this.dirty = true;
}
/**
* The resolution / device pixel ratio of the canvas.
* This is set to automatically match the renderer resolution by default, but can be overridden by setting manually.
* @member {number}
* @default 1
*/
get resolution(): number
{
return this._resolution;
}
set resolution(value: number) // eslint-disable-line require-jsdoc
{
this._autoResolution = false;
if (this._resolution === value)
{
return;
}
this._resolution = value;
this.dirty = true;
}
/**
* Sanitise text - replace `<br>` with `<br/>`, ` ` with ` `
* @see https://www.sitepoint.com/community/t/xhtml-1-0-transitional-xml-parsing-error-entity-nbsp-not-defined/3392/3
*/
private sanitiseText(text: string): string
{
return text
.replace(/<br>/gi, '<br/>')
.replace(/<hr>/gi, '<hr/>')
.replace(/ /gi, ' ');
}
}