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 pathHTMLTextStyle.ts
490 lines (436 loc) · 14.7 KB
/
HTMLTextStyle.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
import { settings, utils } from '@pixi/core';
import { TextStyle, TextStyleFontStyle, TextStyleFontWeight, TextStyleLineJoin } from '@pixi/text';
import type { ITextStyle, TextStyleTextBaseline } from '@pixi/text';
// HTMLText support more white-space options
type HTMLTextStyleWhiteSpace = 'normal' | 'pre' | 'pre-line' | 'nowrap' | 'pre-wrap';
// Subset of ITextStyle
type ITextStyleIgnore = 'whiteSpace'
| 'fillGradientStops'
| 'fillGradientType'
| 'miterLimit'
| 'textBaseline'
| 'trim'
| 'leading'
| 'lineJoin';
/**
* Modifed versions from ITextStyle.
* @extends ITextStyle
*/
interface IHTMLTextStyle extends Omit<ITextStyle, ITextStyleIgnore>
{
/**
* White-space with expanded options
* @type {'normal'|'pre'|'pre-line'|'nowrap'|'pre-wrap'}
*/
whiteSpace: HTMLTextStyleWhiteSpace;
}
/**
* Font information for HTMLText
*/
interface IHTMLFont
{
/** User-supplied URL request */
originalUrl: string;
/** Base64 string for font */
dataSrc: string;
/** FontFace installed in the document */
fontFace: FontFace | null;
/** Blob-based URL for font */
src: string;
/** Family name of font */
family: string;
/** Weight of the font */
weight: TextStyleFontWeight;
/** Style of the font */
style: TextStyleFontStyle;
/** Reference counter */
refs: number;
}
/**
* Used internally to restrict text style usage and convert easily to CSS.
* @class
* @extends PIXI.TextStyle
* @see {@link https://pixijs.download/dev/docs/PIXI.TextStyle.html PIXI.TextStyle}
* @param {PIXI.ITextStyle|IHTMLTextStyle} [style] - Style to copy.
*/
class HTMLTextStyle extends TextStyle
{
/** The collection of installed fonts */
public static availableFonts: Record<string, IHTMLFont> = {};
/**
* List of default options, these are largely the same as TextStyle,
* with the exception of whiteSpace, which is set to 'normal' by default.
*/
public static readonly defaultOptions: IHTMLTextStyle = {
/** Align */
align: 'left',
/** Break words */
breakWords: false,
/** Drop shadow */
dropShadow: false,
/** Drop shadow alpha */
dropShadowAlpha: 1,
/**
* Drop shadow angle
* @type {number}
* @default Math.PI / 6
*/
dropShadowAngle: Math.PI / 6,
/** Drop shadow blur */
dropShadowBlur: 0,
/** Drop shadow color */
dropShadowColor: 'black',
/** Drop shadow distance */
dropShadowDistance: 5,
/** Fill */
fill: 'black',
/** Font family */
fontFamily: 'Arial',
/** Font size */
fontSize: 26,
/** Font style */
fontStyle: 'normal',
/** Font variant */
fontVariant: 'normal',
/** Font weight */
fontWeight: 'normal',
/** Letter spacing */
letterSpacing: 0,
/** Line height */
lineHeight: 0,
/** Padding */
padding: 0,
/** Stroke */
stroke: 'black',
/** Stroke thickness */
strokeThickness: 0,
/** White space */
whiteSpace: 'normal',
/** Word wrap */
wordWrap: false,
/** Word wrap width */
wordWrapWidth: 100,
};
/** For using custom fonts */
private _fonts: IHTMLFont[] = [];
/** List of internal style rules */
private _overrides: string[] = [];
/** Global rules or stylesheet, useful for creating rules for rendering */
private _stylesheet = '';
/** Track font changes internally */
private fontsDirty = false;
/**
* Convert a TextStyle to HTMLTextStyle
* @example
* import {TextStyle } from 'pixi.js';
* import {HTMLTextStyle} from '@pixi/text-html';
* const style = new TextStyle();
* const htmlStyle = HTMLTextStyle.from(style);
*/
static from(originalStyle: TextStyle | Partial<IHTMLTextStyle>): HTMLTextStyle
{
return new HTMLTextStyle(Object.keys(HTMLTextStyle.defaultOptions)
.reduce((obj, prop) => ({ ...obj, [prop]: originalStyle[prop as keyof IHTMLTextStyle] }), {})
);
}
/** Clear the current font */
public cleanFonts(): void
{
if (this._fonts.length > 0)
{
this._fonts.forEach((font) =>
{
URL.revokeObjectURL(font.src);
font.refs--;
if (font.refs === 0)
{
if (font.fontFace)
{
document.fonts.delete(font.fontFace);
}
delete HTMLTextStyle.availableFonts[font.originalUrl];
}
});
this.fontFamily = 'Arial';
this._fonts.length = 0;
this.styleID++;
this.fontsDirty = true;
}
}
/** Because of how HTMLText renders, fonts need to be imported */
public loadFont(url: string, options: Partial<Pick<IHTMLFont, 'weight' | 'style' | 'family'>> = {}): Promise<void>
{
const { availableFonts } = HTMLTextStyle;
// Font is already installed
if (availableFonts[url])
{
const font = availableFonts[url];
this._fonts.push(font);
font.refs++;
this.styleID++;
this.fontsDirty = true;
return Promise.resolve();
}
return settings.ADAPTER.fetch(url)
.then((response) => response.blob())
.then(async (blob) => new Promise<[string, string]>((resolve, reject) =>
{
const src = URL.createObjectURL(blob);
const reader = new FileReader();
reader.onload = () => resolve([src, reader.result as string]);
reader.onerror = reject;
reader.readAsDataURL(blob);
}))
.then(async ([src, dataSrc]) =>
{
const font: IHTMLFont = Object.assign({
family: utils.path.basename(url, utils.path.extname(url)),
weight: 'normal',
style: 'normal',
src,
dataSrc,
refs: 1,
originalUrl: url,
fontFace: null,
}, options);
availableFonts[url] = font;
this._fonts.push(font);
this.styleID++;
// Load it into the current DOM so we can properly measure it!
const fontFace = new FontFace(font.family, `url(${font.src})`, {
weight: font.weight,
style: font.style,
});
// Keep this reference so we can remove it later from document
font.fontFace = fontFace;
await fontFace.load();
document.fonts.add(fontFace);
await document.fonts.ready;
this.styleID++;
this.fontsDirty = true;
});
}
/**
* Add a style override, this can be any CSS property
* it will override any built-in style. This is the
* property and the value as a string (e.g., `color: red`).
* This will override any other internal style.
* @param {string} value - CSS style(s) to add.
* @example
* style.addOverride('background-color: red');
*/
public addOverride(...value: string[]): void
{
const toAdd = value.filter((v) => !this._overrides.includes(v));
if (toAdd.length > 0)
{
this._overrides.push(...toAdd);
this.styleID++;
}
}
/**
* Remove any overrides that match the value.
* @param {string} value - CSS style to remove.
* @example
* style.removeOverride('background-color: red');
*/
public removeOverride(...value: string[]): void
{
const toRemove = value.filter((v) => this._overrides.includes(v));
if (toRemove.length > 0)
{
this._overrides = this._overrides.filter((v) => !toRemove.includes(v));
this.styleID++;
}
}
/**
* Internally converts all of the style properties into CSS equivalents.
* @return The CSS style string, for setting `style` property of root HTMLElement.
*/
public toCSS(scale: number): string
{
return [
'display: inline-block',
`color: ${this.normalizeColor(this.fill)}`,
`font-size: ${(this.fontSize as number) * scale}px`,
`font-family: ${this.fontFamily}`,
`font-weight: ${this.fontWeight}`,
`font-style: ${this.fontStyle}`,
`font-variant: ${this.fontVariant}`,
`letter-spacing: ${this.letterSpacing * scale}px`,
`text-align: ${this.align}`,
`padding: ${this.padding * scale}px`,
`white-space: ${this.whiteSpace}`,
...this.lineHeight ? [`line-height: ${this.lineHeight * scale}px`] : [],
...this.wordWrap ? [
`word-wrap: ${this.breakWords ? 'break-all' : 'break-word'}`,
`max-width: ${this.wordWrapWidth * scale}px`
] : [],
...this.strokeThickness ? [
`-webkit-text-stroke-width: ${this.strokeThickness * scale}px`,
`-webkit-text-stroke-color: ${this.normalizeColor(this.stroke)}`,
`text-stroke-width: ${this.strokeThickness * scale}px`,
`text-stroke-color: ${this.normalizeColor(this.stroke)}`,
'paint-order: stroke',
] : [],
...this.dropShadow ? [this.dropShadowToCSS(scale)] : [],
...this._overrides,
].join(';');
}
/** Get the font CSS styles from the loaded font, If available. */
public toGlobalCSS(): string
{
return this._fonts.reduce((result, font) => (
`${result}
@font-face {
font-family: "${font.family}";
src: url('${font.dataSrc}');
font-weight: ${font.weight};
font-style: ${font.style};
}`
), this._stylesheet);
}
/** Internal stylesheet contents, useful for creating rules for rendering */
public get stylesheet(): string
{
return this._stylesheet;
}
public set stylesheet(value: string)
{
if (this._stylesheet !== value)
{
this._stylesheet = value;
this.styleID++;
}
}
/** Convert numerical colors into hex-strings */
private normalizeColor(color: any): string
{
if (Array.isArray(color))
{
color = utils.rgb2hex(color);
}
if (typeof color === 'number')
{
return utils.hex2string(color);
}
return color;
}
/** Convert the internal drop-shadow settings to CSS text-shadow */
private dropShadowToCSS(scale: number): string
{
let color = this.normalizeColor(this.dropShadowColor);
const alpha = this.dropShadowAlpha;
const x = Math.round(Math.cos(this.dropShadowAngle) * this.dropShadowDistance);
const y = Math.round(Math.sin(this.dropShadowAngle) * this.dropShadowDistance);
// Append alpha to color
if (color.startsWith('#') && alpha < 1)
{
color += (alpha * 255 | 0).toString(16).padStart(2, '0');
}
const position = `${x * scale}px ${y * scale}px`;
if (this.dropShadowBlur > 0)
{
return `text-shadow: ${position} ${this.dropShadowBlur}px ${color}`;
}
return `text-shadow: ${position} ${color}`;
}
/** Resets all properties to the defaults specified in TextStyle.prototype._default */
public reset(): void
{
Object.assign(this, HTMLTextStyle.defaultOptions);
}
/**
* Called after the image is loaded but before drawing to the canvas.
* Mostly used to handle Safari's font loading bug.
* @ignore
*/
public onBeforeDraw()
{
const { fontsDirty: prevFontsDirty } = this;
this.fontsDirty = false;
// Safari has a known bug where embedded fonts are not available
// immediately after the image loads, to compensate we wait an
// arbitrary amount of time
// @see https://bugs.webkit.org/show_bug.cgi?id=219770
if (this.isSafari && this._fonts.length > 0 && prevFontsDirty)
{
return new Promise<void>((resolve) => setTimeout(resolve, 100));
}
return Promise.resolve();
}
/**
* Proving that Safari is the new IE
* @ignore
*/
private get isSafari(): boolean
{
const { userAgent } = settings.ADAPTER.getNavigator();
return (/^((?!chrome|android).)*safari/i).test(userAgent);
}
/** @ignore fillGradientStops is not supported by HTMLText */
override set fillGradientStops(_value: number[])
{
console.warn('[HTMLTextStyle] fillGradientStops is not supported by HTMLText');
}
override get fillGradientStops()
{
return super.fillGradientStops;
}
/** @ignore fillGradientType is not supported by HTMLText */
override set fillGradientType(_value: number)
{
console.warn('[HTMLTextStyle] fillGradientType is not supported by HTMLText');
}
override get fillGradientType()
{
return super.fillGradientType;
}
/** @ignore miterLimit is not supported by HTMLText */
override set miterLimit(_value: number)
{
console.warn('[HTMLTextStyle] miterLimit is not supported by HTMLText');
}
override get miterLimit()
{
return super.miterLimit;
}
/** @ignore trim is not supported by HTMLText */
override set trim(_value: boolean)
{
console.warn('[HTMLTextStyle] trim is not supported by HTMLText');
}
override get trim()
{
return super.trim;
}
/** @ignore textBaseline is not supported by HTMLText */
override set textBaseline(_value: TextStyleTextBaseline)
{
console.warn('[HTMLTextStyle] textBaseline is not supported by HTMLText');
}
override get textBaseline()
{
return super.textBaseline;
}
/** @ignore leading is not supported by HTMLText */
override set leading(_value: number)
{
console.warn('[HTMLTextStyle] leading is not supported by HTMLText');
}
override get leading()
{
return super.leading;
}
/** @ignore lineJoin is not supported by HTMLText */
override set lineJoin(_value: TextStyleLineJoin)
{
console.warn('[HTMLTextStyle] lineJoin is not supported by HTMLText');
}
override get lineJoin()
{
return super.lineJoin;
}
}
export { HTMLTextStyle };
export type { IHTMLTextStyle, HTMLTextStyleWhiteSpace };