From e920d879282acde53eef26957f39d09524c47410 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 15 May 2019 17:05:07 -0700 Subject: [PATCH] Account for toggleClass when obtaining used class names for tree shaking --- .../sanitizers/class-amp-style-sanitizer.php | 15 ++++++++++++ tests/test-amp-style-sanitizer.php | 24 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/includes/sanitizers/class-amp-style-sanitizer.php b/includes/sanitizers/class-amp-style-sanitizer.php index 5fb9c704241..1691e3fd4a3 100644 --- a/includes/sanitizers/class-amp-style-sanitizer.php +++ b/includes/sanitizers/class-amp-style-sanitizer.php @@ -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; } diff --git a/tests/test-amp-style-sanitizer.php b/tests/test-amp-style-sanitizer.php index fb24a5f145d..19f2cedc460 100644 --- a/tests/test-amp-style-sanitizer.php +++ b/tests/test-amp-style-sanitizer.php @@ -757,6 +757,30 @@ public function get_attribute_selector_data() { '.\@\@\@\@' => false, ), ), + 'toggle_class' => array( + implode( + '', + array( + '
', + '', + '', + '', + '', + '', + '', + ) + ), + array( + '.expanded' => true, + '.clicked' => true, + '.tapped' => true, + '.pressed' => true, + '.im-pressed' => true, + '.touch\:ed' => true, + '.exploded' => false, + '.stateful' => false, + ), + ), ); }