-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
utils.js
55 lines (52 loc) · 1.76 KB
/
utils.js
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
/**
* WordPress dependencies
*/
import { pipe } from '@wordpress/compose';
/**
* Escapes ampersands, shortcodes, and links.
*
* @param {string} content The content of a code block.
* @return {string} The given content with some characters escaped.
*/
export function escape( content ) {
return pipe(
escapeOpeningSquareBrackets,
escapeProtocolInIsolatedUrls
)( content || '' );
}
/**
* Returns the given content with all opening shortcode characters converted
* into their HTML entity counterpart (i.e. [ => [). For instance, a
* shortcode like [embed] becomes [embed]
*
* This function replicates the escaping of HTML tags, where a tag like
* <strong> becomes <strong>.
*
* @param {string} content The content of a code block.
* @return {string} The given content with its opening shortcode characters
* converted into their HTML entity counterpart
* (i.e. [ => [)
*/
function escapeOpeningSquareBrackets( content ) {
return content.replace( /\[/g, '[' );
}
/**
* Converts the first two forward slashes of any isolated URL into their HTML
* counterparts (i.e. // => //). For instance, https://youtube.com/watch?x
* becomes https://youtube.com/watch?x.
*
* An isolated URL is a URL that sits in its own line, surrounded only by spacing
* characters.
*
* See https://github.com/WordPress/wordpress-develop/blob/5.1.1/src/wp-includes/class-wp-embed.php#L403
*
* @param {string} content The content of a code block.
* @return {string} The given content with its ampersands converted into
* their HTML entity counterpart (i.e. & => &)
*/
function escapeProtocolInIsolatedUrls( content ) {
return content.replace(
/^(\s*https?:)\/\/([^\s<>"]+\s*)$/m,
'$1//$2'
);
}