Debian Codegraph @

packages/datagrid/src/textrenderer.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 /*-----------------------------------------------------------------------------
4 | Copyright (c) 2014-2019, PhosphorJS Contributors
5 |
6 | Distributed under the terms of the BSD 3-Clause License.
7 |
8 | The full license is in the file LICENSE, distributed with this software.
9 |----------------------------------------------------------------------------*/
10 import { CellRenderer } from './cellrenderer';
11
12 import { GraphicsContext } from './graphicscontext';
13
14 /**
15 * A cell renderer which renders data values as text.
16 */
17 export class TextRenderer extends CellRenderer {
18 /**
19 * Construct a new text renderer.
20 *
21 * @param options - The options for initializing the renderer.
22 */
23 constructor(options: TextRenderer.IOptions = {}) {
24 super();
25 this.font = options.font || '12px sans-serif';
26 this.textColor = options.textColor || '#000000';
27 this.backgroundColor = options.backgroundColor || '';
28 this.verticalAlignment = options.verticalAlignment || 'center';
29 this.horizontalAlignment = options.horizontalAlignment || 'left';
30 this.horizontalPadding = options.horizontalPadding || 8;
31 this.format = options.format || TextRenderer.formatGeneric();
32 this.elideDirection = options.elideDirection || 'none';
33 this.wrapText = options.wrapText || false;
34 }
35
36 /**
37 * The CSS shorthand font for drawing the text.
38 */
39 readonly font: CellRenderer.ConfigOption<string>;
40
41 /**
42 * The CSS color for drawing the text.
43 */
44 readonly textColor: CellRenderer.ConfigOption<string>;
45
46 /**
47 * The CSS color for the cell background.
48 */
49 readonly backgroundColor: CellRenderer.ConfigOption<string>;
50
51 /**
52 * The vertical alignment for the cell text.
53 */
54 readonly verticalAlignment: CellRenderer.ConfigOption<TextRenderer.VerticalAlignment>;
55
56 /**
57 * The horizontal alignment for the cell text.
58 */
59 readonly horizontalAlignment: CellRenderer.ConfigOption<TextRenderer.HorizontalAlignment>;
60
61 /**
62 * The horizontal alignment for the cell text.
63 */
64 readonly horizontalPadding: number;
65
66 /**
67 * The format function for the cell value.
68 */
69 readonly format: TextRenderer.FormatFunc;
70
71 /**
72 * Which side to draw the ellipsis. Set to 'none' to disable ellipsis.
73 */
74 readonly elideDirection: CellRenderer.ConfigOption<TextRenderer.ElideDirection>;
75
76 /**
77 * Boolean flag for applying text wrapping.
78 */
79 readonly wrapText: CellRenderer.ConfigOption<boolean>;
80
81 /**
82 * Paint the content for a cell.
83 *
84 * @param gc - The graphics context to use for drawing.
85 *
86 * @param config - The configuration data for the cell.
87 */
88 paint(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
89 this.drawBackground(gc, config);
90 this.drawText(gc, config);
91 }
92
93 /**
94 * Draw the background for the cell.
95 *
96 * @param gc - The graphics context to use for drawing.
97 *
98 * @param config - The configuration data for the cell.
99 */
100 drawBackground(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
101 // Resolve the background color for the cell.
102 let color = CellRenderer.resolveOption(this.backgroundColor, config);
103
104 // Bail if there is no background color to draw.
105 if (!color) {
106 return;
107 }
108
109 // Fill the cell with the background color.
110 gc.fillStyle = color;
111 gc.fillRect(config.x, config.y, config.width, config.height);
112 }
113
114 /**
115 * Get the full text to be rendered by the cell.
116 */
117 getText(config: CellRenderer.CellConfig): string {
118 return this.format(config);
119 }
120
121 /**
122 * Draw the text for the cell.
123 *
124 * @param gc - The graphics context to use for drawing.
125 *
126 * @param config - The configuration data for the cell.
127 */
128 drawText(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
129 // Resolve the font for the cell.
130 let font = CellRenderer.resolveOption(this.font, config);
131
132 // Bail if there is no font to draw.
133 if (!font) {
134 return;
135 }
136
137 // Resolve the text color for the cell.
138 let color = CellRenderer.resolveOption(this.textColor, config);
139
140 // Bail if there is no text color to draw.
141 if (!color) {
142 return;
143 }
144
145 // Format the cell value to text.
146 let text = this.getText(config);
147
148 // Bail if there is no text to draw.
149 if (!text) {
150 return;
151 }
152
153 // Resolve the vertical and horizontal alignment.
154 let vAlign = CellRenderer.resolveOption(this.verticalAlignment, config);
155 let hAlign = CellRenderer.resolveOption(this.horizontalAlignment, config);
156
157 // Resolve the elision direction
158 let elideDirection = CellRenderer.resolveOption(
159 this.elideDirection,
160 config
161 );
162
163 // Resolve the text wrapping flag
164 let wrapText = CellRenderer.resolveOption(this.wrapText, config);
165
166 // Compute the padded text box height for the specified alignment.
167 let boxHeight = config.height - (vAlign === 'center' ? 1 : 2);
168
169 // Bail if the text box has no effective size.
170 if (boxHeight <= 0) {
171 return;
172 }
173
174 // Compute the text height for the gc font.
175 let textHeight = TextRenderer.measureFontHeight(font);
176
177 // Set up the text position variables.
178 let textX: number;
179 let textY: number;
180 let boxWidth: number;
181
182 // Compute the Y position for the text.
183 switch (vAlign) {
184 case 'top':
185 textY = config.y + 2 + textHeight;
186 break;
187 case 'center':
188 textY = config.y + config.height / 2 + textHeight / 2;
189 break;
190 case 'bottom':
191 textY = config.y + config.height - 2;
192 break;
193 default:
194 throw 'unreachable';
195 }
196
197 // Compute the X position for the text.
198 switch (hAlign) {
199 case 'left':
200 textX = config.x + this.horizontalPadding;
201 boxWidth = config.width - 14;
202 break;
203 case 'center':
204 textX = config.x + config.width / 2;
205 boxWidth = config.width;
206 break;
207 case 'right':
208 textX = config.x + config.width - this.horizontalPadding;
209 boxWidth = config.width - 14;
210 break;
211 default:
212 throw 'unreachable';
213 }
214
215 // Clip the cell if the text is taller than the text box height.
216 if (textHeight > boxHeight) {
217 gc.beginPath();
218 gc.rect(config.x, config.y, config.width, config.height - 1);
219 gc.clip();
220 }
221
222 // Set the gc state.
223 gc.font = font;
224 gc.fillStyle = color;
225 gc.textAlign = hAlign;
226 gc.textBaseline = 'bottom';
227
228 // Terminate call here if we're not eliding or wrapping text
229 if (elideDirection === 'none' && !wrapText) {
230 gc.fillText(text, textX, textY);
231 return;
232 }
233
234 // The current text width in pixels.
235 let textWidth = gc.measureText(text).width;
236
237 // Apply text wrapping if enabled.
238 if (wrapText && textWidth > boxWidth) {
239 // Make sure box clipping happens.
240 gc.beginPath();
241 gc.rect(config.x, config.y, config.width, config.height - 1);
242 gc.clip();
243
244 // Split column name to words based on
245 // whitespace preceding a word boundary.
246 // "Hello world" --> ["Hello ", "world"]
247 const wordsInColumn = text.split(/\s(?=\b)/);
248
249 // Y-coordinate offset for any additional lines
250 let curY = textY;
251 let textInCurrentLine = wordsInColumn.shift()!;
252
253 // Single word. Applying text wrap on word by splitting
254 // it into characters and fitting the maximum number of
255 // characters possible per line (box width).
256 if (wordsInColumn.length === 0) {
257 let curLineTextWidth = gc.measureText(textInCurrentLine).width;
258 while (curLineTextWidth > boxWidth && textInCurrentLine !== '') {
259 // Iterating from the end of the string until we find a
260 // substring (0,i) which has a width less than the box width.
261 for (let i = textInCurrentLine.length; i > 0; i--) {
262 const curSubString = textInCurrentLine.substring(0, i);
263 const curSubStringWidth = gc.measureText(curSubString).width;
264 if (curSubStringWidth < boxWidth || curSubString.length === 1) {
265 // Found a substring which has a width less than the current
266 // box width. Rendering that substring on the current line
267 // and setting the remainder of the parent string as the next
268 // string to iterate on for the next line.
269 const nextLineText = textInCurrentLine.substring(
270 i,
271 textInCurrentLine.length
272 );
273 textInCurrentLine = nextLineText;
274 curLineTextWidth = gc.measureText(textInCurrentLine).width;
275 gc.fillText(curSubString, textX, curY);
276 curY += textHeight;
277 // No need to continue iterating after we identified
278 // an index to break the string on.
279 break;
280 }
281 }
282 }
283 }
284
285 // Multiple words in column header. Fitting maximum
286 // number of words possible per line (box width).
287 else {
288 while (wordsInColumn.length !== 0) {
289 // Processing the next word in the queue.
290 const curWord = wordsInColumn.shift();
291 // Joining that word with the existing text for
292 // the current line.
293 const incrementedText = [textInCurrentLine, curWord].join(' ');
294 const incrementedTextWidth = gc.measureText(incrementedText).width;
295 if (incrementedTextWidth > boxWidth) {
296 // If the newly combined text has a width larger than
297 // the box width, we render the line before the current
298 // word was added. We set the current word as the next
299 // line.
300 gc.fillText(textInCurrentLine, textX, curY);
301 curY += textHeight;
302 textInCurrentLine = curWord!;
303 } else {
304 // The combined text hasd a width less than the box width. We
305 // set the the current line text to be the new combined text.
306 textInCurrentLine = incrementedText;
307 }
308 }
309 }
310 gc.fillText(textInCurrentLine!, textX, curY);
311 // Terminating the call here as we don't want
312 // to apply text eliding when wrapping is active.
313 return;
314 }
315
316 // Elide text that is too long
317 const elide = '\u2026';
318
319 // Loop until text width fits box or only one character remains
320 while (textWidth > boxWidth && text.length > 1) {
321 // Convert text string to array for dealing with astral symbols
322 const textArr = [...text];
323
324 if (elideDirection === 'right') {
325 // If text width is substantially bigger, take half the string
326 if (textArr.length > 4 && textWidth >= 2 * boxWidth) {
327 text =
328 textArr.slice(0, Math.floor(textArr.length / 2 + 1)).join('') +
329 elide;
330 } else {
331 // Otherwise incrementally remove the last character
332 text = textArr.slice(0, textArr.length - 2).join('') + elide;
333 }
334 } else {
335 // If text width is substantially bigger, take half the string
336 if (textArr.length > 4 && textWidth >= 2 * boxWidth) {
337 text = elide + textArr.slice(Math.floor(textArr.length / 2)).join('');
338 } else {
339 // Otherwise incrementally remove the last character
340 text = elide + textArr.slice(2).join('');
341 }
342 }
343
344 // Measure new text width
345 textWidth = gc.measureText(text).width;
346 }
347
348 // Draw the text for the cell.
349 gc.fillText(text, textX, textY);
350 }
351 }
352
353 /**
354 * The namespace for the `TextRenderer` class statics.
355 */
356 export namespace TextRenderer {
357 /**
358 * A type alias for the supported vertical alignment modes.
359 */
360 export type VerticalAlignment = 'top' | 'center' | 'bottom';
361
362 /**
363 * A type alias for the supported horizontal alignment modes.
364 */
365 export type HorizontalAlignment = 'left' | 'center' | 'right';
366
367 /**
368 * A type alias for the supported ellipsis sides.
369 */
370 export type ElideDirection = 'left' | 'right' | 'none';
371
372 /**
373 * An options object for initializing a text renderer.
374 */
375 export interface IOptions {
376 /**
377 * The font for drawing the cell text.
378 *
379 * The default is `'12px sans-serif'`.
380 */
381 font?: CellRenderer.ConfigOption<string>;
382
383 /**
384 * The color for the drawing the cell text.
385 *
386 * The default `'#000000'`.
387 */
388 textColor?: CellRenderer.ConfigOption<string>;
389
390 /**
391 * The background color for the cells.
392 *
393 * The default is `''`.
394 */
395 backgroundColor?: CellRenderer.ConfigOption<string>;
396
397 /**
398 * The vertical alignment for the cell text.
399 *
400 * The default is `'center'`.
401 */
402 verticalAlignment?: CellRenderer.ConfigOption<VerticalAlignment>;
403
404 /**
405 * The horizontal alignment for the cell text.
406 *
407 * The default is `'left'`.
408 */
409 horizontalAlignment?: CellRenderer.ConfigOption<HorizontalAlignment>;
410
411 /**
412 * The horizontal padding for the cell text in pixels.
413 *
414 * The default is `8`.
415 */
416 horizontalPadding?: number;
417
418 /**
419 * The format function for the renderer.
420 *
421 * The default is `TextRenderer.formatGeneric()`.
422 */
423 format?: FormatFunc;
424
425 /**
426 * The ellipsis direction for the cell text.
427 *
428 * The default is `'none'`.
429 */
430 elideDirection?: CellRenderer.ConfigOption<ElideDirection>;
431
432 /**
433 * Whether or not to apply text wrapping.
434 *
435 * The default is `'false'`.
436 */
437 wrapText?: CellRenderer.ConfigOption<boolean>;
438 }
439
440 /**
441 * A type alias for a format function.
442 */
443 export type FormatFunc = CellRenderer.ConfigFunc<string>;
444
445 /**
446 * Create a generic text format function.
447 *
448 * @param options - The options for creating the format function.
449 *
450 * @returns A new generic text format function.
451 *
452 * #### Notes
453 * This formatter uses the builtin `String()` to coerce any value
454 * to a string.
455 */
456 export function formatGeneric(
457 options: formatGeneric.IOptions = {}
458 ): FormatFunc {
459 let missing = options.missing || '';
460 return ({ value }) => {
461 if (value === null || value === undefined) {
462 return missing;
463 }
464 return String(value);
465 };
466 }
467
468 /**
469 * The namespace for the `formatGeneric` function statics.
470 */
471 export namespace formatGeneric {
472 /**
473 * The options for creating a generic format function.
474 */
475 export interface IOptions {
476 /**
477 * The text to use for a `null` or `undefined` data value.
478 *
479 * The default is `''`.
480 */
481 missing?: string;
482 }
483 }
484
485 /**
486 * Create a fixed decimal format function.
487 *
488 * @param options - The options for creating the format function.
489 *
490 * @returns A new fixed decimal format function.
491 *
492 * #### Notes
493 * This formatter uses the builtin `Number()` and `toFixed()` to
494 * coerce values.
495 *
496 * The `formatIntlNumber()` formatter is more flexible, but slower.
497 */
498 export function formatFixed(options: formatFixed.IOptions = {}): FormatFunc {
499 let digits = options.digits;
500 let missing = options.missing || '';
501 return ({ value }) => {
502 if (value === null || value === undefined) {
503 return missing;
504 }
505 return Number(value).toFixed(digits);
506 };
507 }
508
509 /**
510 * The namespace for the `formatFixed` function statics.
511 */
512 export namespace formatFixed {
513 /**
514 * The options for creating a fixed format function.
515 */
516 export interface IOptions {
517 /**
518 * The number of digits to include after the decimal point.
519 *
520 * The default is determined by the user agent.
521 */
522 digits?: number;
523
524 /**
525 * The text to use for a `null` or `undefined` data value.
526 *
527 * The default is `''`.
528 */
529 missing?: string;
530 }
531 }
532
533 /**
534 * Create a significant figure format function.
535 *
536 * @param options - The options for creating the format function.
537 *
538 * @returns A new significant figure format function.
539 *
540 * #### Notes
541 * This formatter uses the builtin `Number()` and `toPrecision()`
542 * to coerce values.
543 *
544 * The `formatIntlNumber()` formatter is more flexible, but slower.
545 */
546 export function formatPrecision(
547 options: formatPrecision.IOptions = {}
548 ): FormatFunc {
549 let digits = options.digits;
550 let missing = options.missing || '';
551 return ({ value }) => {
552 if (value === null || value === undefined) {
553 return missing;
554 }
555 return Number(value).toPrecision(digits);
556 };
557 }
558
559 /**
560 * The namespace for the `formatPrecision` function statics.
561 */
562 export namespace formatPrecision {
563 /**
564 * The options for creating a precision format function.
565 */
566 export interface IOptions {
567 /**
568 * The number of significant figures to include in the value.
569 *
570 * The default is determined by the user agent.
571 */
572 digits?: number;
573
574 /**
575 * The text to use for a `null` or `undefined` data value.
576 *
577 * The default is `''`.
578 */
579 missing?: string;
580 }
581 }
582
583 /**
584 * Create a scientific notation format function.
585 *
586 * @param options - The options for creating the format function.
587 *
588 * @returns A new scientific notation format function.
589 *
590 * #### Notes
591 * This formatter uses the builtin `Number()` and `toExponential()`
592 * to coerce values.
593 *
594 * The `formatIntlNumber()` formatter is more flexible, but slower.
595 */
596 export function formatExponential(
597 options: formatExponential.IOptions = {}
598 ): FormatFunc {
599 let digits = options.digits;
600 let missing = options.missing || '';
601 return ({ value }) => {
602 if (value === null || value === undefined) {
603 return missing;
604 }
605 return Number(value).toExponential(digits);
606 };
607 }
608
609 /**
610 * The namespace for the `formatExponential` function statics.
611 */
612 export namespace formatExponential {
613 /**
614 * The options for creating an exponential format function.
615 */
616 export interface IOptions {
617 /**
618 * The number of digits to include after the decimal point.
619 *
620 * The default is determined by the user agent.
621 */
622 digits?: number;
623
624 /**
625 * The text to use for a `null` or `undefined` data value.
626 *
627 * The default is `''`.
628 */
629 missing?: string;
630 }
631 }
632
633 /**
634 * Create an international number format function.
635 *
636 * @param options - The options for creating the format function.
637 *
638 * @returns A new international number format function.
639 *
640 * #### Notes
641 * This formatter uses the builtin `Intl.NumberFormat` object to
642 * coerce values.
643 *
644 * This is the most flexible (but slowest) number formatter.
645 */
646 export function formatIntlNumber(
647 options: formatIntlNumber.IOptions = {}
648 ): FormatFunc {
649 let missing = options.missing || '';
650 let nft = new Intl.NumberFormat(options.locales, options.options);
651 return ({ value }) => {
652 if (value === null || value === undefined) {
653 return missing;
654 }
655 return nft.format(value);
656 };
657 }
658
659 /**
660 * The namespace for the `formatIntlNumber` function statics.
661 */
662 export namespace formatIntlNumber {
663 /**
664 * The options for creating an intl number format function.
665 */
666 export interface IOptions {
667 /**
668 * The locales to pass to the `Intl.NumberFormat` constructor.
669 *
670 * The default is determined by the user agent.
671 */
672 locales?: string | string[];
673
674 /**
675 * The options to pass to the `Intl.NumberFormat` constructor.
676 *
677 * The default is determined by the user agent.
678 */
679 options?: Intl.NumberFormatOptions;
680
681 /**
682 * The text to use for a `null` or `undefined` data value.
683 *
684 * The default is `''`.
685 */
686 missing?: string;
687 }
688 }
689
690 /**
691 * Create a date format function.
692 *
693 * @param options - The options for creating the format function.
694 *
695 * @returns A new date format function.
696 *
697 * #### Notes
698 * This formatter uses `Date.toDateString()` to format the values.
699 *
700 * If a value is not a `Date` object, `new Date(value)` is used to
701 * coerce the value to a date.
702 *
703 * The `formatIntlDateTime()` formatter is more flexible, but slower.
704 */
705 export function formatDate(options: formatDate.IOptions = {}): FormatFunc {
706 let missing = options.missing || '';
707 return ({ value }) => {
708 if (value === null || value === undefined) {
709 return missing;
710 }
711 if (value instanceof Date) {
712 return value.toDateString();
713 }
714 return new Date(value).toDateString();
715 };
716 }
717
718 /**
719 * The namespace for the `formatDate` function statics.
720 */
721 export namespace formatDate {
722 /**
723 * The options for creating a date format function.
724 */
725 export interface IOptions {
726 /**
727 * The text to use for a `null` or `undefined` data value.
728 *
729 * The default is `''`.
730 */
731 missing?: string;
732 }
733 }
734
735 /**
736 * Create a time format function.
737 *
738 * @param options - The options for creating the format function.
739 *
740 * @returns A new time format function.
741 *
742 * #### Notes
743 * This formatter uses `Date.toTimeString()` to format the values.
744 *
745 * If a value is not a `Date` object, `new Date(value)` is used to
746 * coerce the value to a date.
747 *
748 * The `formatIntlDateTime()` formatter is more flexible, but slower.
749 */
750 export function formatTime(options: formatTime.IOptions = {}): FormatFunc {
751 let missing = options.missing || '';
752 return ({ value }) => {
753 if (value === null || value === undefined) {
754 return missing;
755 }
756 if (value instanceof Date) {
757 return value.toTimeString();
758 }
759 return new Date(value).toTimeString();
760 };
761 }
762
763 /**
764 * The namespace for the `formatTime` function statics.
765 */
766 export namespace formatTime {
767 /**
768 * The options for creating a time format function.
769 */
770 export interface IOptions {
771 /**
772 * The text to use for a `null` or `undefined` data value.
773 *
774 * The default is `''`.
775 */
776 missing?: string;
777 }
778 }
779
780 /**
781 * Create an ISO datetime format function.
782 *
783 * @param options - The options for creating the format function.
784 *
785 * @returns A new ISO datetime format function.
786 *
787 * #### Notes
788 * This formatter uses `Date.toISOString()` to format the values.
789 *
790 * If a value is not a `Date` object, `new Date(value)` is used to
791 * coerce the value to a date.
792 *
793 * The `formatIntlDateTime()` formatter is more flexible, but slower.
794 */
795 export function formatISODateTime(
796 options: formatISODateTime.IOptions = {}
797 ): FormatFunc {
798 let missing = options.missing || '';
799 return ({ value }) => {
800 if (value === null || value === undefined) {
801 return missing;
802 }
803 if (value instanceof Date) {
804 return value.toISOString();
805 }
806 return new Date(value).toISOString();
807 };
808 }
809
810 /**
811 * The namespace for the `formatISODateTime` function statics.
812 */
813 export namespace formatISODateTime {
814 /**
815 * The options for creating an ISO datetime format function.
816 */
817 export interface IOptions {
818 /**
819 * The text to use for a `null` or `undefined` data value.
820 *
821 * The default is `''`.
822 */
823 missing?: string;
824 }
825 }
826
827 /**
828 * Create a UTC datetime format function.
829 *
830 * @param options - The options for creating the format function.
831 *
832 * @returns A new UTC datetime format function.
833 *
834 * #### Notes
835 * This formatter uses `Date.toUTCString()` to format the values.
836 *
837 * If a value is not a `Date` object, `new Date(value)` is used to
838 * coerce the value to a date.
839 *
840 * The `formatIntlDateTime()` formatter is more flexible, but slower.
841 */
842 export function formatUTCDateTime(
843 options: formatUTCDateTime.IOptions = {}
844 ): FormatFunc {
845 let missing = options.missing || '';
846 return ({ value }) => {
847 if (value === null || value === undefined) {
848 return missing;
849 }
850 if (value instanceof Date) {
851 return value.toUTCString();
852 }
853 return new Date(value).toUTCString();
854 };
855 }
856
857 /**
858 * The namespace for the `formatUTCDateTime` function statics.
859 */
860 export namespace formatUTCDateTime {
861 /**
862 * The options for creating a UTC datetime format function.
863 */
864 export interface IOptions {
865 /**
866 * The text to use for a `null` or `undefined` data value.
867 *
868 * The default is `''`.
869 */
870 missing?: string;
871 }
872 }
873
874 /**
875 * Create an international datetime format function.
876 *
877 * @param options - The options for creating the format function.
878 *
879 * @returns A new international datetime format function.
880 *
881 * #### Notes
882 * This formatter uses the builtin `Intl.DateTimeFormat` object to
883 * coerce values.
884 *
885 * This is the most flexible (but slowest) datetime formatter.
886 */
887 export function formatIntlDateTime(
888 options: formatIntlDateTime.IOptions = {}
889 ): FormatFunc {
890 let missing = options.missing || '';
891 let dtf = new Intl.DateTimeFormat(options.locales, options.options);
892 return ({ value }) => {
893 if (value === null || value === undefined) {
894 return missing;
895 }
896 return dtf.format(value);
897 };
898 }
899
900 /**
901 * The namespace for the `formatIntlDateTime` function statics.
902 */
903 export namespace formatIntlDateTime {
904 /**
905 * The options for creating an intl datetime format function.
906 */
907 export interface IOptions {
908 /**
909 * The locales to pass to the `Intl.DateTimeFormat` constructor.
910 *
911 * The default is determined by the user agent.
912 */
913 locales?: string | string[];
914
915 /**
916 * The options to pass to the `Intl.DateTimeFormat` constructor.
917 *
918 * The default is determined by the user agent.
919 */
920 options?: Intl.DateTimeFormatOptions;
921
922 /**
923 * The text to use for a `null` or `undefined` data value.
924 *
925 * The default is `''`.
926 */
927 missing?: string;
928 }
929 }
930
931 /**
932 * Measure the height of a font.
933 *
934 * @param font - The CSS font string of interest.
935 *
936 * @returns The height of the font bounding box.
937 *
938 * #### Notes
939 * This function uses a temporary DOM node to measure the text box
940 * height for the specified font. The first call for a given font
941 * will incur a DOM reflow, but the return value is cached, so any
942 * subsequent call for the same font will return the cached value.
943 */
944 export function measureFontHeight(font: string): number {
945 // Look up the cached font height.
946 let height = Private.fontHeightCache[font];
947
948 // Return the cached font height if it exists.
949 if (height !== undefined) {
950 return height;
951 }
952
953 // Normalize the font.
954 Private.fontMeasurementGC.font = font;
955 let normFont = Private.fontMeasurementGC.font;
956
957 // Set the font on the measurement node.
958 Private.fontMeasurementNode.style.font = normFont;
959
960 // Add the measurement node to the document.
961 document.body.appendChild(Private.fontMeasurementNode);
962
963 // Measure the node height.
964 height = Private.fontMeasurementNode.offsetHeight;
965
966 // Remove the measurement node from the document.
967 document.body.removeChild(Private.fontMeasurementNode);
968
969 // Cache the measured height for the font and norm font.
970 Private.fontHeightCache[font] = height;
971 Private.fontHeightCache[normFont] = height;
972
973 // Return the measured height.
974 return height;
975 }
976 }
977
978 /**
979 * The namespace for the module implementation details.
980 */
981 namespace Private {
982 /**
983 * A cache of measured font heights.
984 */
985 export const fontHeightCache: { [font: string]: number } =
986 Object.create(null);
987
988 /**
989 * The DOM node used for font height measurement.
990 */
991 export const fontMeasurementNode = (() => {
992 let node = document.createElement('div');
993 node.style.position = 'absolute';
994 node.style.top = '-99999px';
995 node.style.left = '-99999px';
996 node.style.visibility = 'hidden';
997 node.textContent = 'M';
998 return node;
999 })();
1000
1001 /**
1002 * The GC used for font measurement.
1003 */
1004 export const fontMeasurementGC = (() => {
1005 let canvas = document.createElement('canvas');
1006 canvas.width = 0;
1007 canvas.height = 0;
1008 return canvas.getContext('2d')!;
1009 })();
1010 }