refreshless-8.x-1.x-dev/modules/refreshless_turbo_gin/src/Hooks/Library.php
modules/refreshless_turbo_gin/src/Hooks/Library.php
<?php
declare(strict_types=1);
namespace Drupal\refreshless_turbo_gin\Hooks;
use Drupal\hux\Attribute\Alter;
use Drupal\Core\Extension\ModuleHandlerInterface;
/**
* Library hook implementations.
*/
class Library {
/**
* Hook constructor; saves dependencies.
*
* @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
* The Drupal module handler.
*/
public function __construct(
protected readonly ModuleHandlerInterface $moduleHandler,
) {}
/**
* Replace JavaScript in a provided library with our JavaScript override.
*
* @param array &$library
* The library entry to alter.
*
* @param string $originalJs
* The original JavaScript file path, as specified in *.libraries.yml.
*
* @param string $ourJs
* The path to our JavaScript override, relative to our js directory.
*/
protected function replaceJs(
array &$library, string $originalJs, string $ourJs,
): void {
if (
// Don't do anything if the library doesn't have the expected file. This
// is both to avoid errors and to ensure we don't alter libraries that
// have been altered by another extension because we could end up
// conflicting with their changes.
!isset($library['js'][$originalJs])
) {
return;
}
// Copy the existing library definition from the original's to ours.
$library['js'][
'/' . $this->moduleHandler->getModule(
'refreshless_turbo_gin',
)->getPath() . '/js/' . $ourJs
] = $library['js'][$originalJs];
// Remove the original JavaScript entry.
unset($library['js'][$originalJs]);
// Remove any existing version as this is now no longer accurate; we don't
// want a core or module version to be used as the cache-busting query
// string as this can now have changes regardless of whether core or the
// extension has been updated.
unset($library['version']);
}
#[Alter('library_info')]
/**
* Alter library definitions to add our Gin integration to that theme.
*
* @see \hook_library_info_alter()
*/
public function alter(array &$libraries, string $extension): void {
if ($extension !== 'gin') {
return;
}
$libraries['gin_accent'][
'dependencies'
][] = 'refreshless_turbo_gin/gin_accent';
$libraries['navigation'][
'dependencies'
][] = 'refreshless_turbo_gin/gin_navigation';
$libraries['core_navigation'][
'dependencies'
][] = 'refreshless_turbo_gin/gin_navigation';
$libraries['tableheader'][
'dependencies'
][] = 'refreshless_turbo_gin/compatibility.tableheader';
$libraries['dropbutton']['dependencies'][] = 'core/drupal';
$libraries['dropbutton']['dependencies'][] = 'core/jquery';
$this->replaceJs(
$libraries['dropbutton'], 'dist/js/dropbutton.js',
'dropbutton.js',
);
$libraries['sticky']['dependencies'][] = 'core/jquery';
$this->replaceJs(
$libraries['sticky'], 'dist/js/sticky.js',
'sticky.js',
);
}
}
