Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active April 4, 2020 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonruter/19f18bf520d0b8c37e39d17b82febd2f to your computer and use it in GitHub Desktop.
Save westonruter/19f18bf520d0b8c37e39d17b82febd2f to your computer and use it in GitHub Desktop.
<?php
/**
* AMP On Tap Attribute Fix plugin initialization file.
*
* @package AMP_On_Tap_Attribute_Fix
* @author Weston Ruter, Google
* @link https://gist.github.com/westonruter/19f18bf520d0b8c37e39d17b82febd2f
* @license GPL-2.0-or-later
* @copyright 2019 Google Inc.
*
* @wordpress-plugin
* Plugin Name: AMP On Tap Attribute Fix
* Plugin URI: https://gist.github.com/westonruter/19f18bf520d0b8c37e39d17b82febd2f
* Description: Automatically inject the required <code>role=button</code> and <code>tabindex=0</code> attributes for non-tabbable elements with <code>on="tap:..."</code>. This will be made part of the AMP plugin in <a href="https://github.com/ampproject/amp-wp/issues/4528">amp-wp#4528</a>.
* Version: 0.1
* Author: Weston Ruter, Google
* Author URI: https://weston.ruter.net/
* License: GNU General Public License v2 (or later)
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
namespace AMP_On_Tap_Attribute_Fix;
/**
* Filter sanitizers.
*
* @param array $sanitizers Sanitizers.
* @return array Sanitizers.
*/
function filter_sanitizers( $sanitizers ) {
if ( version_compare( AMP__VERSION, '1.5', '<' ) ) {
return $sanitizers;
}
require_once __DIR__ . '/class-sanitizer.php';
$sanitizers[ __NAMESPACE__ . '\Sanitizer' ] = [];
return $sanitizers;
}
add_filter( 'amp_content_sanitizers', __NAMESPACE__ . '\filter_sanitizers' );
<?php
/**
* Sanitizer
*
* @package AMP_On_Tap_Attribute_Fix
*/
namespace AMP_On_Tap_Attribute_Fix;
use AMP_Base_Sanitizer;
use DOMElement;
/**
* Class Undo_JS_Lazy_Loaded_Images_Sanitizer
*/
class Sanitizer extends AMP_Base_Sanitizer {
/**
* Sanitize.
*/
public function sanitize() {
$predicates = [
'@on',
'contains( @on, "tap:" )',
'not( @tabindex ) or not( @role )',
'not( self::button )',
'not( self::a[ @href ] )',
];
$expression = sprintf(
'//*[ %s ]',
implode(
' and ',
array_map(
static function ( $predicate ) {
return "( $predicate )";
},
$predicates
)
)
);
$attributes = [
'role' => 'button',
'tabindex' => '0',
];
/**
* Element.
*
* @var DOMElement $element
*/
foreach ( $this->dom->xpath->query( $expression ) as $element ) {
foreach ( $attributes as $attr_name => $attr_value ) {
if ( ! $element->hasAttribute( $attr_name ) ) {
$element->setAttribute( $attr_name, $attr_value );
}
}
}
}
}
@westonruter
Copy link
Author

westonruter commented Apr 4, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment