Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Account for toggleClass when obtaining used class names for tree shaking #2328

Merged
merged 1 commit into from
May 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions includes/sanitizers/class-amp-style-sanitizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,21 @@ private function get_used_class_names() {
array_unique( array_filter( preg_split( '/\s+/', trim( $classes ) ) ) )
);

// Find all instances of the toggleClass() action to prevent the class name from being tree-shaken.
foreach ( $this->xpath->query( '//*/@on[ contains( ., "toggleClass" ) ]' ) as $on_attribute ) {
if ( preg_match_all( '/\.\s*toggleClass\s*\(\s*class\s*=\s*(([\'"])([^\1]*?)\2|[a-zA-Z0-9_\-]+)/', $on_attribute->nodeValue, $matches ) ) {
$class_names = array_merge(
$class_names,
array_map(
function ( $match ) {
return trim( $match, '"\'' );
},
$matches[1]
)
);
}
}

$this->used_class_names = array_fill_keys( $class_names, true );
return $this->used_class_names;
}
Expand Down
24 changes: 24 additions & 0 deletions tests/test-amp-style-sanitizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,30 @@ public function get_attribute_selector_data() {
'.\@\@\@\@' => false,
),
),
'toggle_class' => array(
implode(
'',
array(
'<div id=\"foo\"></div>',
'<button on="tap:foo . toggleClass ( class = \'expanded\' )">Yes</button>',
'<button on="tap:foo.toggleClass(class=\'clicked\')">Yes</button>',
'<button on="tap:foo.toggleClass(class=&quot;tapped&quot;)">Yes</button>',
'<button on="tap:foo.toggleClass(class=pressed);tap:foo.toggleClass(class = im-pressed)">Yes</button>',
'<button on="tap:foo.toggleClass(class = \'touch:ed\' )">Yes</button>',
'<button on="tap:AMP.setState({toggleClass:\'stateful\'})">No</button>',
)
),
array(
'.expanded' => true,
'.clicked' => true,
'.tapped' => true,
'.pressed' => true,
'.im-pressed' => true,
'.touch\:ed' => true,
'.exploded' => false,
'.stateful' => false,
),
),
);
}

Expand Down