Commit 07403e9f authored by osman's avatar osman

Code cleanup, Disabled paths, Status messages

parent fa957140
......@@ -86,7 +86,7 @@ Enable the *Lazy-load* filter for the desired text-formats. i.e. *Full HTML* or
Check out the configuration at `admin/config/content/lazy`.
Configure which elements should be lazy-loaded in the **global settings** area.
Configure which elements should be lazy-loaded in the **settings** area.
**Blazy configuration** options come with the Blazy defaults. Refer to [Blazy plugin documentation][5] for each setting.
......
......@@ -18,10 +18,8 @@ function lazy_requirements($phase) {
$has_blazy = FALSE;
if ($library['js']) {
foreach ($library['js'] as $js) {
if ($js['type'] == 'file') {
if (file_exists(DRUPAL_ROOT . '/' . $js['data'])) {
$has_blazy = TRUE;
}
if (($js['type'] == 'file') && file_exists(DRUPAL_ROOT . '/' . $js['data'])) {
$has_blazy = TRUE;
}
}
}
......
......@@ -103,7 +103,8 @@ function lazy_page_attachments(array &$attachments) {
/**
* Callback function to check whether lazy is enabled in any text-formats.
*
* @return mixed Lazy configuration object if enabled, false otherwise.
* @return mixed
* Lazy configuration object if enabled, false otherwise.
*/
function lazy_is_enabled() {
$status = [];
......@@ -115,9 +116,9 @@ function lazy_is_enabled() {
foreach ($filters as $key => $filter) {
$filter = unserialize($filter);
if (
isset($filter['status']) && $filter['status']
&& isset($filter['dependencies']['module'])
&& in_array('lazy', $filter['dependencies']['module'])
isset($filter['status'], $filter['dependencies']['module'])
&& $filter['status']
&& in_array('lazy', $filter['dependencies']['module'], TRUE)
) {
$status[$key] = TRUE;
}
......@@ -125,7 +126,7 @@ function lazy_is_enabled() {
$config = \Drupal::config('lazy.settings')->get();
$image_fields = $config['image_fields'];
if (count($image_fields)) {
if ($image_fields && !empty($image_fields)) {
foreach ($image_fields as $field_name => $bool_value) {
if ($bool_value) {
$status[$field_name] = TRUE;
......@@ -133,19 +134,15 @@ function lazy_is_enabled() {
}
}
$config['status'] = $status;
return count($status) ? $config : FALSE;
}
/**
* Implements hook_field_formatter_third_party_settings_form().
*
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* @param $view_mode
* @param $form
*
* @return array
*/
function lazy_field_formatter_third_party_settings_form($plugin, $field_definition, $view_mode, $form, $form_state) {
function lazy_field_formatter_third_party_settings_form($plugin) {
$element = [];
if ($plugin->getPluginId() === 'image') {
......@@ -161,9 +158,7 @@ function lazy_field_formatter_third_party_settings_form($plugin, $field_definiti
}
/**
* @param $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $form_id
* Implements hook_form_FORM_BASE_ID_alter().
*/
function lazy_form_entity_view_display_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$entity_type = $form['#entity_type'];
......@@ -174,9 +169,6 @@ function lazy_form_entity_view_display_edit_form_alter(&$form, FormStateInterfac
foreach ($fields as $field_name => $field) {
if (
($field['type'] === 'image')
&& isset($field['settings_edit_form'])
&& isset($field['settings_edit_form']['third_party_settings'])
&& isset($field['settings_edit_form']['third_party_settings']['lazy'])
&& isset($field['settings_edit_form']['third_party_settings']['lazy']['lazy_image'])
) {
$route_match = \Drupal::service('current_route_match');
......@@ -191,15 +183,13 @@ function lazy_form_entity_view_display_edit_form_alter(&$form, FormStateInterfac
/**
* Implements hook_field_formatter_settings_summary_alter().
*
* @param $summary
* @param $context
*/
function lazy_field_formatter_settings_summary_alter(&$summary, $context) {
if ($context['formatter']->getPluginId() === 'image') {
if ($context['formatter']->getThirdPartySetting('lazy', 'lazy_image', FALSE)) {
$summary[] = t('Lazy-loading enabled');
}
if (
($context['formatter']->getPluginId() === 'image')
&& $context['formatter']->getThirdPartySetting('lazy', 'lazy_image', FALSE)
) {
$summary[] = t('Lazy-loading enabled');
}
}
......@@ -207,6 +197,7 @@ function lazy_field_formatter_settings_summary_alter(&$summary, $context) {
* Update `lazy.settings.image_fields` value with currently enabled options.
*
* @param array $image_fields
* An array of image fields set to use Lazy.
*/
function lazy_settings_update(array $image_fields) {
$current_image_fields = \Drupal::config('lazy.settings')->get('image_fields');
......@@ -228,27 +219,29 @@ function lazy_settings_update(array $image_fields) {
/**
* Checks whether lazy-load is disabled for the current path.
*
* @param $disabled_paths
* @param string $disabled_paths
* List of paths Lazy should be disabled.
*
* @return bool
* Whether Lazy is disabled for the requested path.
*/
function lazy_disabled_by_path($disabled_paths) {
// Convert path to lowercase. This allows comparison of the same path
// with different case. Ex: /Page, /page, /PAGE.
$pages = mb_strtolower($disabled_paths);
if (!$pages) {
return TRUE;
if (empty($disabled_paths)) {
return FALSE;
}
// Compare the lowercase path alias (if any) and internal path.
$path = \Drupal::service('path.current')->getPath();
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($path);
// Do not trim a trailing slash if that is the complete path.
$path = $path === '/' ? $path : rtrim($path, '/');
// Convert path to lowercase. This allows comparison of the same path
// with different case. Ex: /Page, /page, /PAGE.
$disabled_paths = mb_strtolower($disabled_paths);
// Current path. Do not trim a trailing slash if that is the complete path.
$current_path = \Drupal::service('path.current')->getPath();
$current_path = $current_path === '/' ? $current_path : rtrim($current_path, '/');
// Path alias.
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
$path_alias = mb_strtolower($path_alias);
// If either returns TRUE, Lazy should be disabled for this path.
$path_matcher = \Drupal::service('path.matcher')->matchPath($current_path, $disabled_paths);
$path_alias_matcher = \Drupal::service('path.matcher')->matchPath($path_alias, $disabled_paths);
$path_matcher = \Drupal::service('path.matcher')->matchPath($path, $pages);
$path_alias_matcher = \Drupal::service('path.matcher')->matchPath($path_alias, $pages);
return $path_alias_matcher || (($path !== $path_alias) && $path_matcher);
return ($path_alias_matcher || $path_matcher);
}
......@@ -5,6 +5,7 @@ namespace Drupal\lazy\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Messenger\MessengerInterface;
/**
* Configure Lazy settings for this site.
......@@ -25,40 +26,94 @@ class LazyForm extends ConfigFormBase {
return ['lazy.settings'];
}
/**
* Gets enabled filter formats.
*
* @param array|null $status
* Array of filter-formats and entity bundles.
*/
protected function getEnabledFiltersAndFields($status) {
$links = [];
$anchor_links = [];
if (!empty($status)) {
foreach ($status as $name => $bool_value) {
if ($bool_value && is_string($name)) {
if ((strpos($name, 'filter.format.') === 0) && ($filter_format = substr($name, 14))) {
$links['filter'][$filter_format] = [
'uri' => Url::fromRoute('entity.filter_format.edit_form', [
'filter_format' => $filter_format,
])->toString(),
'title' => $filter_format,
];
}
elseif (($entity = explode('--', $name)) && count($entity)) {
list($entity_type, $entity_bundle, $view_mode) = $entity;
if (($entity_type !== NULL) && ($entity_bundle !== NULL)) {
$links['field']["$entity_type--$entity_bundle--$view_mode"] = [
'uri' => Url::fromRoute("entity.entity_view_display.$entity_type.view_mode", [
(($entity_type === 'paragraph') ? 'paragraphs' : $entity_type) . '_type' => $entity_bundle,
'view_mode_name' => $view_mode,
])->toString(),
'title' => $entity_bundle . " ($view_mode)",
];
}
}
}
}
foreach ($links as $key => $link_group) {
foreach ($link_group as $link) {
$anchor_links[$key][] = '<a href="' . $link['uri'] . '">' . $link['title'] . '</a>';
}
}
}
$filter_links_result = (isset($anchor_links['filter']) && count($anchor_links['filter'])) ? implode(', ', $anchor_links['filter']) : 'none';
$field_links_result = (isset($anchor_links['field']) && count($anchor_links['field'])) ? implode(', ', $anchor_links['field']) : 'none';
$filter_message_type = ($filter_links_result === 'none') ? MessengerInterface::TYPE_WARNING : MessengerInterface::TYPE_STATUS;
$this->messenger()->addMessage($this->t("The <strong>text-formats</strong> have lazy-loading enabled: $filter_links_result"), $filter_message_type);
$field_message_type = ($field_links_result === 'none') ? MessengerInterface::TYPE_WARNING : MessengerInterface::TYPE_STATUS;
$this->messenger()->addMessage($this->t("The <strong>image fields</strong> have lazy-loading enabled: $field_links_result"), $field_message_type);
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('lazy.settings');
$filter_enabled = lazy_is_enabled();
$description = $this->t('The inline images and iframes will be lazy-loaded for the selected text-formats');
$desc_extra = $this->t('The %filter filter must be enabled for at least one <a href=":path">text-format</a>.', [
':path' => Url::fromRoute('filter.admin_overview')->toString(),
'%filter' => 'Lazy-load',
]);
if (
!(bool) $config->get('alter_tag')['img']
&& !(bool) $config->get('alter_tag')['iframe']
) {
$this->messenger()->addStatus($this->t('Lazy-load is currently disabled. Update configuration in global settings to enable it.'), 'warning');
$this->getEnabledFiltersAndFields($filter_enabled['status']);
if (!$filter_enabled) {
$this->messenger()->addWarning($this->t('<p>The %filter filter must be enabled for at least one <a href=":path">text-format</a>, or one entity image:</p>', [
':path' => Url::fromRoute('filter.admin_overview')->toString(),
'%filter' => 'Lazy-load',
]));
}
$form['settings'] = [
'#type' => 'fieldset',
'#title' => $this->t('Global settings'),
'#title' => $this->t('Settings'),
'#open' => TRUE,
];
if (
!(bool) $config->get('alter_tag')['img']
&& !(bool) $config->get('alter_tag')['iframe']
) {
$alter_tag_description = $this->t('Only selected tags will be lazy-loaded in activated text-formats.');
}
$form['settings']['alter_tag'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Select the inline elements to be lazy-loaded via filter.'),
'#description' => $alter_tag_description,
'#options' => [
'img' => $this->t('Enable for images (%img tags)', ['%img' => '<img>']),
'iframe' => $this->t('Enable for iframes (%iframe tags)', ['%iframe' => '<iframe>']),
],
'#default_value' => $config->get('alter_tag'),
'#description' => $description . ($filter_enabled ? '' : $desc_extra),
'#disabled' => !$filter_enabled,
];
......@@ -88,7 +143,7 @@ class LazyForm extends ConfigFormBase {
$form['paths']['disabled_paths'] = array(
'#type' => 'textarea',
'#title' => t('Pages'),
'#title' => $this->t('Pages'),
'#default_value' => $config->get('disabled_paths'),
'#description' => $this->t("Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. An example path is %user-wildcard for every user page. %front is the front page.", [
'%user-wildcard' => '/user/*',
......@@ -219,7 +274,6 @@ class LazyForm extends ConfigFormBase {
public function cacheClear() {
drupal_flush_all_caches();
$this->messenger()->addMessage('Cache cleared.');
// return $this->redirect('lazy.config_form');
}
}
......@@ -41,9 +41,9 @@ class LazyFilter extends FilterBase {
$matches = $html_dom->getElementsByTagName($tag);
foreach ($matches as $element) {
$classes = $element->getAttribute('class');
$classes = (strlen($classes) > 0) ? explode(' ', $classes) : [];
$classes = ($classes !== '') ? explode(' ', $classes) : [];
$parent_classes = $element->parentNode->getAttribute('class');
$parent_classes = (strlen($parent_classes) > 0) ? explode(' ', $parent_classes) : [];
$parent_classes = ($parent_classes !== '') ? explode(' ', $parent_classes) : [];
if (empty($opt_tags[$tag])) {
// If the `tag` is not enabled remove the bLazy selector class.
if (($key = array_search($opt_selector, $classes, FALSE)) !== FALSE) {
......@@ -55,7 +55,8 @@ class LazyFilter extends FilterBase {
}
}
else {
// `tag` is enabled. Make sure skipClass is not set before proceeding.
// `tag` is enabled. Make sure skipClass is not set before
// proceeding.
if (!in_array($opt_skipClass, $classes, FALSE) && !in_array($opt_skipClass, $parent_classes, FALSE)) {
$classes[] = $opt_selector;
$classes = array_unique($classes);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment