-
Notifications
You must be signed in to change notification settings - Fork 2k
/
rule-content-remove-styles.js
53 lines (45 loc) · 1.71 KB
/
rule-content-remove-styles.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
/* globals Element */
/**
* External dependencies
*/
import { forEach } from 'lodash';
function matches( element, selector ) {
const ep = Element.prototype;
// modern browsers support `matches` but IE11 and older safari support it as `matchesSelector` with a prefix
const matcher =
ep.matches || ep.webkitMatchesSelector || ep.mozMatchesSelector || ep.msMatchesSelector;
if ( ! matcher ) {
return false;
}
return matcher.call( element, selector );
}
export default function removeContentStyles( post, dom ) {
if ( ! dom ) {
throw new Error( 'this transform must be used as part of withContentDOM' );
}
// Allow the markup for galleries, Instagram, and Twitter. Styling will be allowed on elements that match this selector.
const allowedMarkupSelector =
'.gallery, .gallery *, .gallery-row, .gallery-row *, .gallery-group, .gallery-group *, ' +
'blockquote[class^="instagram-"], blockquote[class^="instagram-"] *, ' +
'blockquote[class^="twitter-"], blockquote[class^="twitter-"] *';
// remove most style attributes
const styled = dom.querySelectorAll( '[style]' );
forEach( styled, function ( element ) {
if ( ! matches( element, allowedMarkupSelector ) ) {
element.removeAttribute( 'style' );
}
} );
// remove all style elements outside of galleries and embeds
forEach( dom.querySelectorAll( 'style' ), function ( element ) {
if ( ! matches( element, allowedMarkupSelector ) ) {
element.parentNode && element.parentNode.removeChild( element );
}
} );
// remove align from non images. Unlike above, img align is permitted anywhere.
forEach( dom.querySelectorAll( '[align]' ), ( element ) => {
if ( element.tagName !== 'IMG' ) {
element.removeAttribute( 'align' );
}
} );
return post;
}