| 1 |
<?php |
| 2 |
declare( strict_types = 1 ); |
| 3 |
|
| 4 |
namespace Wikimedia\Parsoid\Wt2Html\DOM\Handlers; |
| 5 |
|
| 6 |
use Wikimedia\Assert\Assert; |
| 7 |
use Wikimedia\Parsoid\DOM\Element; |
| 8 |
use Wikimedia\Parsoid\Utils\DOMCompat; |
| 9 |
use Wikimedia\Parsoid\Utils\DOMDataUtils; |
| 10 |
use Wikimedia\Parsoid\Utils\DOMUtils; |
| 11 |
use Wikimedia\Parsoid\Utils\DTState; |
| 12 |
|
| 13 |
class DedupeStyles { |
| 14 |
|
| 15 |
/** |
| 16 |
* @param Element $node |
| 17 |
* @param DTState $state |
| 18 |
* @return bool|Element |
| 19 |
*/ |
| 20 |
public static function dedupe( Element $node, DTState $state ) { |
| 21 |
// Don't run on embedded docs for now since we don't want the |
| 22 |
// canonical styles to be introduced in embedded HTML which means |
| 23 |
// they will get lost wrt the top level document. |
| 24 |
Assert::invariant( $state->atTopLevel, 'This pass should only be run on the top-level' ); |
| 25 |
|
| 26 |
$key = DOMCompat::getAttribute( $node, 'data-mw-deduplicate' ); |
| 27 |
if ( $key === null ) { |
| 28 |
// Not a templatestyles <style> tag |
| 29 |
return true; |
| 30 |
} |
| 31 |
|
| 32 |
$env = $state->env; |
| 33 |
if ( !isset( $env->styleTagKeys[$key] ) ) { |
| 34 |
// Not a dupe |
| 35 |
$env->styleTagKeys[$key] = true; |
| 36 |
return true; |
| 37 |
} |
| 38 |
|
| 39 |
if ( !DOMUtils::isFosterablePosition( $node ) ) { |
| 40 |
// Dupe - replace with a placeholder <link> reference |
| 41 |
$link = $node->ownerDocument->createElement( 'link' ); |
| 42 |
DOMUtils::addRel( $link, 'mw-deduplicated-inline-style' ); |
| 43 |
$link->setAttribute( 'href', 'mw-data:' . $key ); |
| 44 |
$link->setAttribute( 'about', DOMCompat::getAttribute( $node, 'about' ) ?? '' ); |
| 45 |
$link->setAttribute( 'typeof', DOMCompat::getAttribute( $node, 'typeof' ) ?? '' ); |
| 46 |
DOMDataUtils::setDataParsoid( $link, DOMDataUtils::getDataParsoid( $node ) ); |
| 47 |
DOMDataUtils::setDataMw( $link, DOMDataUtils::getDataMw( $node ) ); |
| 48 |
$node->parentNode->replaceChild( $link, $node ); |
| 49 |
return $link; |
| 50 |
} else { |
| 51 |
$env->log( 'info/wt2html/templatestyle', |
| 52 |
'Duplicate style tag found in fosterable position. ' . |
| 53 |
'Not deduping it, but emptying out the style tag for performance reasons.' |
| 54 |
); |
| 55 |
DOMCompat::replaceChildren( $node ); |
| 56 |
return true; |
| 57 |
} |
| 58 |
} |
| 59 |
} |