/*
* Emoji loader render tests.
*
* emojiSetsRenderIdentically() and emojiRendersEmptyCenterPoint() below have the
* same signatures as the versions in emoji-loader.js, but draw each string on its
* own canvas and append it to the page.
*
* To test an update, replace browserSupportsEmoji() at the top of this file
* with the version from src/js/_enqueues/lib/emoji-loader.js. No other changes
* are needed.
*/
/*
* ---------------------------------------------------------------------------
* Paste browserSupportsEmoji() from src/js/_enqueues/lib/emoji-loader.js below.
* ---------------------------------------------------------------------------
*/
/**
* Determines if the browser properly renders Emoji that Twemoji can supplement.
*
* This function may be serialized to run in a Worker. Therefore, it cannot refer to variables from the containing
* scope. Everything must be passed by parameters.
*
* @since 4.2.0
*
* @private
*
* @param {EmojiTestContext} context 2D Context.
* @param {keyof SupportTests} type Which support test to run.
* @param {EmojiSetsRenderIdentically} emojiSetsRenderIdentically Reference to emojiSetsRenderIdentically function, needed due to minification.
* @param {EmojiRendersEmptyCenterPoint} emojiRendersEmptyCenterPoint Reference to emojiRendersEmptyCenterPoint function, needed due to minification.
*
* @return {boolean} True if the browser can render emoji, false if it cannot.
*/
function browserSupportsEmoji( context, type, emojiSetsRenderIdentically, emojiRendersEmptyCenterPoint ) {
/** @type {boolean} */
let isIdentical;
switch ( type ) {
case 'flag':
/*
* Test for Transgender flag compatibility. Added in Unicode 13.
*
* To test for support, we try to render it, and compare the rendering to how it would look if
* the browser doesn't render it correctly (white flag emoji + transgender symbol).
*/
isIdentical = emojiSetsRenderIdentically(
context,
'\uD83C\uDFF3\uFE0F\u200D\u26A7\uFE0F', // as a zero-width joiner sequence
'\uD83C\uDFF3\uFE0F\u200B\u26A7\uFE0F' // separated by a zero-width space
);
if ( isIdentical ) {
return false;
}
/*
* Test for Sark flag compatibility. This is the least supported of the letter locale flags,
* so gives us an easy test for full support.
*
* To test for support, we try to render it, and compare the rendering to how it would look if
* the browser doesn't render it correctly ([C] + [Q]).
*/
isIdentical = emojiSetsRenderIdentically(
context,
'\uD83C\uDDE8\uD83C\uDDF6', // as the sequence of two code points
'\uD83C\uDDE8\u200B\uD83C\uDDF6' // as the two code points separated by a zero-width space
);
if ( isIdentical ) {
return false;
}
/*
* Test for English flag compatibility. England is a country in the United Kingdom, it
* does not have a two letter locale code but rather a five letter subdivision code.
*
* To test for support, we try to render it, and compare the rendering to how it would look if
* the browser doesn't render it correctly (black flag emoji + [G] + [B] + [E] + [N] + [G]).
*/
isIdentical = emojiSetsRenderIdentically(
context,
// as the flag sequence
'\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67\uDB40\uDC7F',
// with each code point separated by a zero-width space
'\uD83C\uDFF4\u200B\uDB40\uDC67\u200B\uDB40\uDC62\u200B\uDB40\uDC65\u200B\uDB40\uDC6E\u200B\uDB40\uDC67\u200B\uDB40\uDC7F'
);
return ! isIdentical;
case 'emoji':
/*
* Is there a large, hairy, humanoid mythical creature living in the browser?
*
* To test for Emoji 17.0 support, try to render a new emoji: Hairy Creature.
*
* The hairy creature emoji is a single code point emoji. Testing for browser
* support required testing the center point of the emoji to see if it is empty.
*
* U+1FAC8 (\uD83E\uDEC8) == Hairy creature.
*
* When updating this test, please ensure that the emoji is either a single code point
* or switch to using the emojiSetsRenderIdentically function and testing with a zero-width
* joiner vs a zero-width space.
*/
const notSupported = emojiRendersEmptyCenterPoint( context, '\uD83E\uDEC8' );
return ! notSupported;
}
}
/*
* ---------------------------------------------------------------------------
* Pen helpers. No changes needed below this line.
* ---------------------------------------------------------------------------
*/
/** Support tests to run, as passed to testEmojiSupports() in the loader. */
const TESTS = [ 'flag', 'emoji' ];
/** Friendly names for the invisible characters used in the tests. */
const CODE_POINT_NAMES = {
0x200b: 'ZWSP',
0x200d: 'ZWJ',
0xfe0f: 'VS16',
};
/** Zero-width joiner, expected in set1 where set2 has a ZWSP. */
const ZWJ = 0x200d;
/** Zero-width space, expected only in set2. */
const ZWSP = 0x200b;
/** Element the current support test's calls are appended to. */
let currentSection;
/** Counter for labelling calls within a support test. */
let callCount = 0;
/** Number of calls the loader makes for the current support test, from the silent pass. */
let loaderCallCount = Infinity;
/**
* Creates a canvas with the same size and text settings as the loader's context.
*
* @param {CanvasRenderingContext2D} context Context configured as in testEmojiSupports().
* @return {{canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D}} New canvas and context.
*/
function createTestCanvas( context ) {
const canvas = document.createElement( 'canvas' );
canvas.width = context.canvas.width;
canvas.height = context.canvas.height;
const ctx = canvas.getContext( '2d', { willReadFrequently: true } );
ctx.textBaseline = context.textBaseline;
ctx.font = context.font;
return { canvas, ctx };
}
/**
* Creates an element with optional class and text.
*
* @param {string} tag Tag name.
* @param {string} className Class name.
* @param {string} text Text content.
* @return {HTMLElement} Element.
*/
function el( tag, className = '', text = '' ) {
const node = document.createElement( tag );
if ( className ) {
node.className = className;
}
if ( text ) {
node.textContent = text;
}
return node;
}
/**
* Formats a code point as U+XXXX.
*
* @param {number} codePoint Code point.
* @return {string} Formatted code point.
*/
function formatCodePoint( codePoint ) {
return 'U+' + codePoint.toString( 16 ).toUpperCase().padStart( 4, '0' );
}
/**
* Aligns two code point sequences using their longest common subsequence.
*
* @param {number[]} a First sequence.
* @param {number[]} b Second sequence.
* @return {Array<['equal', number, number]|['delete', number]|['insert', number]>}
* Edit script: equal (index in a, index in b), delete (index in a), insert (index in b).
*/
function diffCodePoints( a, b ) {
const lcs = Array.from( { length: a.length + 1 }, () => new Array( b.length + 1 ).fill( 0 ) );
for ( let x = a.length - 1; x >= 0; x-- ) {
for ( let y = b.length - 1; y >= 0; y-- ) {
lcs[ x ][ y ] = a[ x ] === b[ y ] ? lcs[ x + 1 ][ y + 1 ] + 1 : Math.max( lcs[ x + 1 ][ y ], lcs[ x ][ y + 1 ] );
}
}
const ops = [];
let x = 0;
let y = 0;
while ( x < a.length && y < b.length ) {
if ( a[ x ] === b[ y ] ) {
ops.push( [ 'equal', x++, y++ ] );
} else if ( lcs[ x + 1 ][ y ] >= lcs[ x ][ y + 1 ] ) {
ops.push( [ 'delete', x++ ] );
} else {
ops.push( [ 'insert', y++ ] );
}
}
while ( x < a.length ) {
ops.push( [ 'delete', x++ ] );
}
while ( y < b.length ) {
ops.push( [ 'insert', y++ ] );
}
return ops;
}
/**
* Checks that set2 is set1 with ZWJs substituted by ZWSPs.
*
* set2 is expected to be set1 with:
* - each ZWJ replaced by a ZWSP (e.g. the transgender flag), and/or
* - ZWSPs inserted between code points (e.g. the Sark and England flags).
*
* The visible code points (everything except ZWJ and ZWSP) are aligned first, so
* an added, missing or changed code point is reported once rather than shifting
* the comparison of everything after it. The ZWJs and ZWSPs are then checked
* against that alignment.
*
* @param {string} set1 Set rendered as the emoji, using ZWJs.
* @param {string} set2 Set rendered as separate characters, using ZWSPs.
* @return {{issues: string[], suspect1: Map<number, string>, suspect2: Map<number, string>}}
* Issues found, and the reasons keyed by code point index in each set.
*/
function checkSubstitution( set1, set2 ) {
const a = Array.from( set1, ( char ) => char.codePointAt( 0 ) );
const b = Array.from( set2, ( char ) => char.codePointAt( 0 ) );
const issues = [];
const suspect1 = new Map();
const suspect2 = new Map();
const flag = ( map, index, reason ) => {
map.set( index, reason );
issues.push( reason );
};
const label = ( set, index, codePoints ) => `${ set } #${ index + 1 } ${ formatCodePoint( codePoints[ index ] ) }`;
// Indices of the visible code points in each set.
const visible1 = a.map( ( _, i ) => i ).filter( ( i ) => a[ i ] !== ZWJ && a[ i ] !== ZWSP );
const visible2 = b.map( ( _, j ) => j ).filter( ( j ) => b[ j ] !== ZWJ && b[ j ] !== ZWSP );
// Align the visible code points, recording which set1 index matches which set2 index.
const matched = new Map();
let deleted = [];
let inserted = [];
const flushDifferences = () => {
// A deletion alongside an insertion is a changed code point.
const changed = Math.min( deleted.length, inserted.length );
for ( let k = 0; k < changed; k++ ) {
const i = deleted[ k ];
const j = inserted[ k ];
flag( suspect1, i, `${ label( 'set1', i, a ) } does not match ${ label( 'set2', j, b ) }.` );
suspect2.set( j, `${ label( 'set2', j, b ) }: expected ${ formatCodePoint( a[ i ] ) }.` );
}
deleted.slice( changed ).forEach( ( i ) => flag( suspect1, i, `${ label( 'set1', i, a ) } missing from set2.` ) );
inserted.slice( changed ).forEach( ( j ) => flag( suspect2, j, `${ label( 'set2', j, b ) } not in set1.` ) );
deleted = [];
inserted = [];
};
diffCodePoints( visible1.map( ( i ) => a[ i ] ), visible2.map( ( j ) => b[ j ] ) ).forEach( ( [ op, x, y ] ) => {
if ( op === 'equal' ) {
flushDifferences();
matched.set( visible1[ x ], visible2[ y ] );
} else if ( op === 'delete' ) {
deleted.push( visible1[ x ] );
} else {
inserted.push( visible2[ x ] );
}
} );
flushDifferences();
// ZWSPs belong only in set2.
a.forEach( ( codePoint, i ) => {
if ( codePoint === ZWSP ) {
flag( suspect1, i, `set1 #${ i + 1 }: ZWSP in set1, expected only in set2.` );
}
} );
// Each ZWJ in set1 should be a ZWSP at the same place in set2.
const reportedZwj2 = new Set();
a.forEach( ( codePoint, i ) => {
if ( codePoint !== ZWJ ) {
return;
}
if ( ! matched.has( i - 1 ) ) {
// The preceding code point is already reported as different.
return;
}
let j = matched.get( i - 1 ) + 1;
// Skip code points already reported as not in set1.
while ( suspect2.has( j ) && b[ j ] !== ZWJ && b[ j ] !== ZWSP ) {
j++;
}
if ( b[ j ] === ZWJ ) {
flag( suspect1, i, `set1 #${ i + 1 }: ZWJ not substituted with ZWSP in set2.` );
suspect2.set( j, `set2 #${ j + 1 }: ZWJ should be a ZWSP.` );
reportedZwj2.add( j );
} else if ( b[ j ] !== ZWSP ) {
flag( suspect1, i, `set1 #${ i + 1 }: ZWJ has no matching ZWSP in set2.` );
}
} );
// ZWJs belong only in set1.
b.forEach( ( codePoint, j ) => {
if ( codePoint === ZWJ && ! reportedZwj2.has( j ) ) {
flag( suspect2, j, `set2 #${ j + 1 }: ZWJ in set2, expected only in set1.` );
}
} );
// Leading or trailing ZWSPs don't separate anything.
if ( b[ 0 ] === ZWSP ) {
flag( suspect2, 0, 'set2 #1: ZWSP at start of set2.' );
}
if ( b.length > 1 && b[ b.length - 1 ] === ZWSP ) {
flag( suspect2, b.length - 1, `set2 #${ b.length }: ZWSP at end of set2.` );
}
if ( ! b.includes( ZWSP ) ) {
issues.push( 'set2 contains no ZWSP, so the sets are not a ZWJ vs ZWSP comparison.' );
}
return { issues, suspect1, suspect2 };
}
/**
* Lists the code points in a string, flagging lone surrogates and suspect values.
*
* A lone surrogate usually means a malformed escape, e.g. '\uD83E\u1FAC8'
* instead of '\uD83E\uDEC8'.
*
* @param {string} str String to describe.
* @param {Map<number, string>} suspect Reasons keyed by index of suspect code points.
* @return {HTMLUListElement} List of code points.
*/
function codePointList( str, suspect = new Map() ) {
const list = el( 'ul', 'codepoints' );
let index = 0;
for ( const char of str ) {
const codePoint = char.codePointAt( 0 );
const isLoneSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff;
let label = formatCodePoint( codePoint );
if ( isLoneSurrogate ) {
label += ' lone surrogate';
} else if ( CODE_POINT_NAMES[ codePoint ] ) {
label += ' ' + CODE_POINT_NAMES[ codePoint ];
}
const classes = [];
const titles = [];
if ( isLoneSurrogate ) {
classes.push( 'invalid' );
titles.push( 'Malformed string: unpaired UTF-16 surrogate.' );
}
if ( suspect.has( index ) ) {
classes.push( 'suspect' );
titles.push( suspect.get( index ) );
}
const item = el( 'li', classes.join( ' ' ), label );
item.title = titles.length ? titles.join( ' ' ) : char;
list.append( item );
index++;
}
return list;
}
/**
* Creates a figure containing a canvas and its code points.
*
* @param {HTMLCanvasElement} canvas Canvas to display.
* @param {string} str String drawn on the canvas.
* @param {boolean} showCenter Whether to mark the center point.
* @param {Map<number, string>} suspect Reasons keyed by index of suspect code points.
* @return {HTMLElement} Figure.
*/
function canvasFigure( canvas, str, showCenter = false, suspect = new Map() ) {
const figure = el( 'figure' );
const wrap = el( 'div', 'canvas-wrap' );
wrap.append( canvas );
if ( showCenter ) {
wrap.append( el( 'span', 'center-marker' ) );
}
const caption = el( 'figcaption' );
caption.append( codePointList( str, suspect ) );
figure.append( wrap, caption );
return figure;
}
/**
* Creates a result box.
*
* @param {boolean} passed Whether the check indicates support.
* @param {string[]} lines Lines of text to display.
* @param {string[]} warnings Problems with the test itself, displayed in bold.
* @return {HTMLElement} Result element.
*/
function resultBox( passed, lines, warnings = [] ) {
const box = el( 'div', 'result ' + ( passed ? 'pass' : 'fail' ) );
lines.forEach( ( line ) => box.append( el( 'div', '', line ) ) );
if ( warnings.length ) {
box.classList.add( 'has-warnings' );
const list = el( 'ul', 'warnings' );
warnings.forEach( ( warning ) => {
const item = el( 'li' );
item.append( el( 'strong', '', warning ) );
list.append( item );
} );
box.append( el( 'strong', '', 'ZWJ/ZWSP substitution looks wrong, this result may be invalid:' ), list );
}
return box;
}
/**
* Appends a block for a single call to the current section.
*
* @param {string} title Call description.
* @param {HTMLElement[]} items Items to display side by side.
*/
function appendCall( title, items ) {
callCount++;
const skipped = callCount > loaderCallCount;
const block = el( 'div', skipped ? 'call skipped' : 'call' );
const row = el( 'div', 'row' );
row.append( ...items );
block.append( el( 'h3', '', `#${ callCount } ${ title }` ) );
if ( skipped ) {
block.append( el( 'p', 'skipped-note', 'Not run by the loader: an earlier check returned early.' ) );
}
block.append( row );
currentSection.append( block );
}
/**
* Renders two sets of Emoji on separate canvases and compares them.
*
* @param {CanvasRenderingContext2D} context 2D Context.
* @param {string} set1 Set of Emoji to test.
* @param {string} set2 Set of Emoji to test.
* @return {{first: HTMLCanvasElement, second: HTMLCanvasElement, differingPixels: number, isIdentical: boolean}}
* Canvases and comparison result.
*/
function compareSets( context, set1, set2 ) {
const first = createTestCanvas( context );
const second = createTestCanvas( context );
const { width, height } = first.canvas;
first.ctx.fillText( set1, 0, 0 );
second.ctx.fillText( set2, 0, 0 );
const rendered1 = first.ctx.getImageData( 0, 0, width, height ).data;
const rendered2 = second.ctx.getImageData( 0, 0, width, height ).data;
let differingPixels = 0;
for ( let i = 0; i < rendered1.length; i += 4 ) {
if (
rendered1[ i ] !== rendered2[ i ] ||
rendered1[ i + 1 ] !== rendered2[ i + 1 ] ||
rendered1[ i + 2 ] !== rendered2[ i + 2 ] ||
rendered1[ i + 3 ] !== rendered2[ i + 3 ]
) {
differingPixels++;
}
}
return {
first: first.canvas,
second: second.canvas,
differingPixels,
isIdentical: differingPixels === 0,
};
}
/**
* Renders an emoji on its own canvas and reads the center point.
*
* @param {CanvasRenderingContext2D} context 2D Context.
* @param {string} emoji Emoji to test.
* @return {{canvas: HTMLCanvasElement, centerPoint: Uint8ClampedArray, isEmpty: boolean}}
* Canvas and center point result.
*/
function readCenterPoint( context, emoji ) {
const { canvas, ctx } = createTestCanvas( context );
ctx.fillText( emoji, 0, 0 );
// Test if the center point (16, 16) is empty (0,0,0,0).
const centerPoint = ctx.getImageData( 16, 16, 1, 1 ).data;
return {
canvas,
centerPoint,
isEmpty: centerPoint.every( ( value ) => value === 0 ),
};
}
/**
* Checks if two sets of Emoji characters render the same visually.
*
* Pen version: renders each set on its own canvas and displays them side by side.
*
* Always returns false (renders differently, i.e. supported) so browserSupportsEmoji()
* does not return early and every check is displayed. The real result is displayed,
* and used for the overall result via getLoaderResult().
*
* @param {CanvasRenderingContext2D} context 2D Context.
* @param {string} set1 Set of Emoji to test.
* @param {string} set2 Set of Emoji to test.
* @return {boolean} Always false.
*/
function emojiSetsRenderIdentically( context, set1, set2 ) {
const { first, second, differingPixels, isIdentical } = compareSets( context, set1, set2 );
const substitution = checkSubstitution( set1, set2 );
appendCall( 'emojiSetsRenderIdentically( context, set1, set2 )', [
canvasFigure( first, set1, false, substitution.suspect1 ),
canvasFigure( second, set2, false, substitution.suspect2 ),
resultBox(
! isIdentical,
[
`loader returns: ${ isIdentical }`,
`differing pixels: ${ differingPixels }`,
isIdentical ? 'Renders identically: not supported' : 'Renders differently: supported',
],
substitution.issues
),
] );
return false;
}
/**
* Checks if the center point of a single emoji is empty.
*
* Pen version: renders the emoji on its own canvas and displays the result beside it.
*
* Always returns false (center point filled, i.e. supported) so browserSupportsEmoji()
* does not return early and every check is displayed. The real result is displayed,
* and used for the overall result via getLoaderResult().
*
* @param {CanvasRenderingContext2D} context 2D Context.
* @param {string} emoji Emoji to test.
* @return {boolean} Always false.
*/
function emojiRendersEmptyCenterPoint( context, emoji ) {
const { canvas, centerPoint, isEmpty } = readCenterPoint( context, emoji );
appendCall( 'emojiRendersEmptyCenterPoint( context, emoji )', [
canvasFigure( canvas, emoji, true ),
resultBox( ! isEmpty, [
`loader returns: ${ isEmpty }`,
`rgba(16, 16): ${ Array.from( centerPoint ).join( ', ' ) }`,
isEmpty ? 'Center point empty: not supported' : 'Center point filled: supported',
] ),
] );
return false;
}
/**
* Runs browserSupportsEmoji() with the real return values, without displaying anything.
*
* @param {CanvasRenderingContext2D} context 2D Context.
* @param {string} type Which support test to run.
* @return {{supported: boolean, calls: number}} Loader result and number of checks made.
*/
function getLoaderResult( context, type ) {
let calls = 0;
const supported = browserSupportsEmoji(
context,
type,
( ctx, set1, set2 ) => {
calls++;
return compareSets( ctx, set1, set2 ).isIdentical;
},
( ctx, emoji ) => {
calls++;
return readCenterPoint( ctx, emoji ).isEmpty;
}
);
return { supported, calls };
}
/**
* Runs each support test, displaying the canvases used.
*/
function run() {
const output = document.getElementById( 'output' );
document.getElementById( 'ua' ).textContent = navigator.userAgent;
// Matches the context set up in testEmojiSupports().
const context = document.createElement( 'canvas' ).getContext( '2d', { willReadFrequently: true } );
context.textBaseline = 'top';
context.font = '600 32px Arial';
TESTS.forEach( ( type ) => {
const section = el( 'section' );
const heading = el( 'h2', '', `browserSupportsEmoji( context, '${ type }', … )` );
section.append( heading );
output.append( section );
// Silent pass: the loader's real result.
const { supported, calls } = getLoaderResult( context, type );
// Display pass: every check, with early returns prevented.
currentSection = section;
callCount = 0;
loaderCallCount = calls;
browserSupportsEmoji(
context,
type,
emojiSetsRenderIdentically,
emojiRendersEmptyCenterPoint
);
heading.append( el( 'span', 'badge ' + ( supported ? 'pass' : 'fail' ), supported ? 'Supported' : 'Not supported' ) );
if ( callCount > calls ) {
heading.append( el( 'span', 'skipped-count', `loader ran ${ calls } of ${ callCount } checks` ) );
}
} );
}
document.addEventListener( 'DOMContentLoaded', run );