Skip to content

Commit

Permalink
PLANET-7736: Move JS scripts away from PHP files (#2509)
Browse files Browse the repository at this point in the history
This commit removes JS scripts from the PHP files and enqueue them correctly using WordPress methods and Webpack.
  • Loading branch information
mardelnet authored Feb 6, 2025
1 parent d24febf commit e21100f
Show file tree
Hide file tree
Showing 10 changed files with 233 additions and 63 deletions.
12 changes: 12 additions & 0 deletions assets/src/js/bulk_export.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/* global bulkExportText */

document.addEventListener('DOMContentLoaded', () => {
jQuery(() => {
jQuery('select[name=\'action\'], select[name=\'action2\']').each(function () {
jQuery('<option>')
.val('export')
.text(bulkExportText)
.appendTo(this);
});
});
});
7 changes: 7 additions & 0 deletions assets/src/js/dismiss_dashboard_notice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* global dismissDashboardNotice */

jQuery('#p4-notice').on('click', '.notice-dismiss', () => {
jQuery.post(dismissDashboardNotice.ajaxurl, {'action': 'dismiss_dashboard_notice'}, () => {
jQuery('#p4-notice').hide();
});
});
20 changes: 20 additions & 0 deletions assets/src/js/filter_block_names.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
document.addEventListener('DOMContentLoaded', () => {
const nsSelect = document.getElementById('filter-by-ns');
const nameSelect = document.getElementById('filter-by-name');

nsSelect.addEventListener('change', () => {
const selectedNs = nsSelect.selectedOptions[0].value;

for (const option of nameSelect.options) {
const display = selectedNs.length === 0 ||
option.value.length === 0 ||
option.value.startsWith(`${selectedNs}/`);
option.style.display = display ? 'block' : 'none';
}

if (selectedNs.length >= 1) {
nameSelect.value = '';
}
});
});

6 changes: 6 additions & 0 deletions assets/src/js/media_import_button.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/* global mediaImportLabel */

jQuery(() =>{
jQuery('.upload-php .wrap .page-title-action')
.after(`<a href="upload.php?page=media-picker" class="add-new-h2">${mediaImportLabel}</a>`);
});
12 changes: 12 additions & 0 deletions assets/src/js/metabox_search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/* global metaboxSearchData */

$ = jQuery;

$('#parent_id').off('change').on('change', function() {
// Check selected Parent page and give bigger weight if it will be an Action page
if ((metaboxSearchData.act_page ?? -1) === $(this).val()) {
$('#weight').val(metaboxSearchData.action_weight);
} else {
$('#weight').val(metaboxSearchData.page_weight);
}
});
21 changes: 3 additions & 18 deletions src/BlockReportSearch/Block/BlockUsageTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ public function __construct(array $args = [])
'Table requires a WP_Block_Type_Registry instance.'
);
}

do_action('enqueue_filter_block_names_script');
}

/**
Expand Down Expand Up @@ -368,7 +370,7 @@ private function blockns_dropdown(): void
sort($this->blocks_ns);
$filter = $this->search_params->namespace() ?? null;

echo '<select name="namespace" id="filter-by-ns" onchange="filterBlockNames();">';
echo '<select name="namespace" id="filter-by-ns">';
echo '<option value="">- All namespaces -</option>';
foreach ($this->blocks_ns as $ns) {
echo sprintf(
Expand Down Expand Up @@ -400,23 +402,6 @@ private function blocktype_dropdown(): void
);
}
echo '</select>';

echo "<script>
const filterBlockNames = () => {
let selectedNs = document.getElementById('filter-by-ns').selectedOptions[0].value;
let select = document.getElementById('filter-by-name');
for (let option of select.options) {
let display = selectedNs.length <= 0
|| option.value.length <= 0
|| option.value.startsWith(`\${selectedNs}/`);
option.style.display = display ? 'inline' : 'none';
}
if ( selectedNs.length >= 1 ) {
select.value = '';
}
}
filterBlockNames();
</script>";
}

/**
Expand Down
152 changes: 152 additions & 0 deletions src/EnqueueController.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ public function __construct()
add_action('enqueue_hubspot_cookie_script', [$this, 'enqueue_hubspot_cookie']);
add_action('enqueue_share_buttons_script', [$this, 'enqueue_share_buttons']);
add_action('enqueue_google_tag_manager_script', [$this, 'enqueue_google_tag_manager']);
add_action('enqueue_bulk_export_script', [$this, 'enqueue_bulk_export']);
add_action('enqueue_media_import_button_script', [$this, 'enqueue_media_import_button']);
add_action('enqueue_filter_block_names_script', [$this, 'enqueue_filter_block_names']);
add_action('enqueue_metabox_search_script', [$this, 'enqueue_metabox_search']);
add_action('enqueue_dismiss_dashboard_notice_script', [$this, 'enqueue_dismiss_dashboard_notice']);
}

/**
Expand All @@ -38,6 +43,21 @@ public function enqueue_toggle_comment_submit(): void
);
}

/**
* Enqueues the filter block names script.
*
*/
public function enqueue_filter_block_names(): void
{
$this->enqueue_script(
'filter-block-names-script',
'/assets/build/filterBlockNames.js',
[],
$this->get_file_version('/assets/build/filterBlockNames.js'),
true
);
}

/**
* Enqueues the HubSpot cookie script.
*
Expand All @@ -56,7 +76,137 @@ public function enqueue_hubspot_cookie(): void
);
}

/**
* Enqueues the bulk export script.
*
* @param string $text The text to be passed to the script.
*/
public function enqueue_bulk_export(string $text): void
{
$script = [
'id' => 'bulkExportText',
'name' => 'bulk-export-script',
'path' => '/assets/build/bulkExport.js',
];

$this->enqueue_script(
$script['name'],
$script['path'],
[],
$this->get_file_version($script['path']),
true
);

if (!wp_script_is($script['name'], 'enqueued')) {
return;
}

$inline_script = 'var ' . $script['id'] . ' = "' . $text . '";';

wp_add_inline_script($script['name'], $inline_script);
}

/**
* Enqueues the dismiss dashboard notice script.
*
* This method registers and enqueues the JavaScript file used to add
* the dismiss button to the dashboard notices.
*
*/
public function enqueue_dismiss_dashboard_notice(): void
{
$script = [
'id' => 'dismissDashboardNotice',
'name' => 'dismiss-dashboard-notice-script',
'path' => '/assets/build/dismissDashboardNotice.js',
];

$this->enqueue_script(
$script['name'],
$script['path'],
[],
$this->get_file_version($script['path']),
true
);

if (!wp_script_is($script['name'], 'enqueued')) {
return;
}

wp_localize_script($script['name'], $script['id'], array(
'ajaxurl' => admin_url('admin-ajax.php'),
));
}

/**
* Enqueues the media import button script.
*
* This method registers and enqueues the JavaScript file used to add
* the media import button to the media library.
*
* @param string $label The label for the media import button.
*
*/
public function enqueue_media_import_button(string $label): void
{
$script = [
'id' => 'mediaImportLabel',
'name' => 'media-import-button-script',
'path' => '/assets/build/mediaImportButton.js',
];

$this->enqueue_script(
$script['name'],
$script['path'],
[],
$this->get_file_version($script['path']),
true
);

if (!wp_script_is($script['name'], 'enqueued')) {
return;
}

$btn_label = 'var ' . $script['id'] . ' = "' . $label . '";';

wp_add_inline_script($script['name'], $btn_label);
}

/**
* Enqueues the metabox search script.
*
* This method registers and enqueues the JavaScript file used to manage
* the functionality of setting the metabox weight based on the parent page.
*
* @param array $data The data to be passed to the script.
*/
public function enqueue_metabox_search(array $data): void
{
$script = [
'id' => 'metaboxSearchData',
'name' => 'metabox-search-script',
'path' => '/assets/build/metaboxSearch.js',
];

$this->enqueue_script(
$script['name'],
$script['path'],
[],
$this->get_file_version($script['path']),
true
);

if (!wp_script_is($script['name'], 'enqueued')) {
return;
}

wp_localize_script($script['name'], $script['id'], $data);
}

/**
* Enqueues the Google Tag Manager script and passes the context data to it.
*
* @param array $context The context data to be passed to the script.
* Enqueues the Google Tag Manager script and passes the context data to it.
*
*/
Expand Down Expand Up @@ -115,6 +265,8 @@ public function enqueue_google_tag_manager(array $context): void
* This method registers and enqueues the JavaScript file for handling
* share buttons on the website.
*
* @param array $social_data The data to be passed to the script.
*
*/
public function enqueue_share_buttons(array $social_data): void
{
Expand Down
27 changes: 5 additions & 22 deletions src/Exporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function __construct()
add_action('admin_action_export_data', [ $this, 'single_post_export_data' ]);
add_filter('post_row_actions', [ $this, 'single_post_export' ], 10, 2);
add_filter('page_row_actions', [ $this, 'single_post_export' ], 10, 2);
add_action('admin_footer-edit.php', [ $this, 'single_post_export_bulk' ]);
add_action('admin_footer', [ $this, 'single_post_export_bulk' ]);
add_action('load-edit.php', [ $this, 'single_post_export_bulk_action' ]);
add_action('admin_head', [ $this, 'add_import_button' ]);
}
Expand All @@ -44,15 +44,8 @@ public function single_post_export_bulk(): void
if (!current_user_can('edit_posts')) {
return;
}
?>
<script type="text/javascript">
jQuery(function ($) {
jQuery('<option>').val('export')
.text('<?php esc_html_e('Export', 'planet4-master-theme-backend'); ?>')
.appendTo("select[name='action']");
});
</script>
<?php
$text = __('Export', 'planet4-master-theme-backend');
do_action('enqueue_bulk_export_script', $text);
}

/**
Expand Down Expand Up @@ -107,20 +100,10 @@ public function single_post_export(array $actions, WP_Post $post): array

/**
* Add Import Button
*
* phpcs:disable Generic.Files.LineLength.MaxExceeded
*/
public function add_import_button(): void
{
?>
<script>
jQuery(function(){
jQuery(".upload-php .wrap .page-title-action")
.after('<a href="upload.php?page=media-picker" class="add-new-h2"><?php esc_html_e('Import Greenpeace Media', 'planet4-master-theme-backend'); ?></a>');
});

</script>
<?php
$label = __('Import Greenpeace Media', 'planet4-master-theme-backend');
do_action('enqueue_media_import_button_script', $label);
}
// phpcs:enable Generic.Files.LineLength.MaxExceeded
}
34 changes: 11 additions & 23 deletions src/MasterSite.php
Original file line number Diff line number Diff line change
Expand Up @@ -1094,18 +1094,14 @@ public function view_meta_box_search(WP_Post $post): void
. esc_html__('Weight', 'planet4-master-theme-backend')
. ' (1-' . esc_attr(Search\Search::DEFAULT_MAX_WEIGHT) . ')</label>
<input id="weight" type="text" name="weight" value="' . esc_attr($weight) . '" />';
?><script>
$ = jQuery;
$('#parent_id').off('change').on('change', function() {
// Check selected Parent page and give bigger weight if it will be an Action page
if ('<?php echo esc_js($options['act_page'] ?? -1); ?>' === $(this).val()) {
$('#weight').val(<?php echo esc_js(Search\Search::DEFAULT_ACTION_WEIGHT); ?>);
} else {
$('#weight').val(<?php echo esc_js(Search\Search::DEFAULT_PAGE_WEIGHT); ?>);
}
});
</script>
<?php

$script_data = [
'act_page' => $options['act_page'] ?? null,
'action_weight' => Search\Search::DEFAULT_ACTION_WEIGHT,
'page_weight' => Search\Search::DEFAULT_PAGE_WEIGHT,
];

do_action('enqueue_metabox_search_script', $script_data);
}
// phpcs:enable Generic.WhiteSpace.ScopeIndent

Expand Down Expand Up @@ -1668,17 +1664,9 @@ public function show_dashboard_notice(): void
return;
}

echo '<div id="p4-notice" class="notice notice-info is-dismissible">'
. wp_kses_post($message)
. '</div>'
. "<script>(function() {
jQuery('#p4-notice').on('click', '.notice-dismiss', () => {
jQuery.post(ajaxurl, {'action': 'dismiss_dashboard_notice'}, function(response) {
jQuery('#p4-notice').hide();
});
});
})();</script>
";
do_action('enqueue_dismiss_dashboard_notice_script');

echo '<div id="p4-notice" class="notice notice-info is-dismissible">' . wp_kses_post($message) . '</div>';
}

/**
Expand Down
5 changes: 5 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ module.exports = (env, argv) => {
hubspotCookie: './assets/src/js/hubspot_cookie.js',
shareButtons: './assets/src/js/share_buttons.js',
googleTagManager: './assets/src/js/google_tag_manager.js',
bulkExport: './assets/src/js/bulk_export.js',
mediaImportButton: './assets/src/js/media_import_button.js',
filterBlockNames: './assets/src/js/filter_block_names.js',
metaboxSearch: './assets/src/js/metabox_search.js',
dismissDashboardNotice: './assets/src/js/dismiss_dashboard_notice.js',
frontendIndex: './assets/src/frontendIndex.js',
editorIndex: './assets/src/editorIndex.js',
ArticlesScript: './assets/src/blocks/Articles/ArticlesScript.js',
Expand Down

0 comments on commit e21100f

Please sign in to comment.