Skip to content

Commit

Permalink
Merge branch 'enhance/PRESS7-131-annotate-opt-images' of https://gith…
Browse files Browse the repository at this point in the history
…ub.com/newfold-labs/wp-module-performance into enhance/PRESS7-130-server-prefer-webp
  • Loading branch information
arunshenoy99 committed Dec 23, 2024
2 parents 6f3f629 + 8ec4c1b commit 1b1d100
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 66 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ jobs:
if: "!! env.GIT_DIFF"

- name: Cache Composer vendor directory
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
Expand Down
165 changes: 104 additions & 61 deletions assets/bulk-optimizer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
document.addEventListener( 'DOMContentLoaded', () => {
const { __ } = wp.i18n;

const bulkOptimizeButtonId = 'nfd-bulk-optimize-btn';
let cancelRequested = false;

// Exact class lists for Bulk Select and Delete Permanently buttons
const bulkSelectButtonClasses = [
'button',
'media-button',
Expand All @@ -16,18 +17,12 @@ document.addEventListener( 'DOMContentLoaded', () => {
'delete-selected-button',
];

/**
* Removes the "Bulk Optimize" button if present.
*/
const removeBulkOptimizeButton = () => {
const bulkOptimizeButton =
document.getElementById( bulkOptimizeButtonId );
if ( bulkOptimizeButton ) bulkOptimizeButton.remove();
};

/**
* Creates a modal with progress bar and filename display.
*/
const createModal = () => {
const modal = document.createElement( 'div' );
modal.id = 'nfd-bulk-modal';
Expand Down Expand Up @@ -56,13 +51,20 @@ document.addEventListener( 'DOMContentLoaded', () => {

const modalTitle = document.createElement( 'h2' );
modalTitle.id = 'nfd-modal-title';
modalTitle.textContent = 'Optimizing Images...';
modalTitle.textContent = __(
'Optimizing Images…',
'wp-module-performance'
);

const currentFileName = document.createElement( 'p' );
currentFileName.id = 'nfd-current-file';
currentFileName.textContent = 'Preparing files...';
currentFileName.textContent = __(
'Preparing files…',
'wp-module-performance'
);

const progressContainer = document.createElement( 'div' );
progressContainer.id = 'nfd-progress-container';
progressContainer.style.cssText = `
width: 100%;
height: 20px;
Expand All @@ -82,63 +84,72 @@ document.addEventListener( 'DOMContentLoaded', () => {
transition: width 0.3s ease;
`;

const cancelButton = document.createElement( 'button' );
cancelButton.textContent = 'Cancel';
cancelButton.className = 'button button-secondary';
cancelButton.style.marginTop = '1rem';
cancelButton.addEventListener( 'click', () => {
cancelRequested = true;
closeModal();
window.location.reload(); // Reload on cancel
const resultList = document.createElement( 'ul' );
resultList.id = 'nfd-result-list';
resultList.style.cssText = `
text-align: center;
margin: 1rem auto;
max-height: 200px;
overflow-y: auto;
`;

const doneButton = document.createElement( 'button' );
doneButton.textContent = __( 'Done', 'wp-module-performance' );
doneButton.className = 'button button-secondary';
doneButton.style.marginTop = '1rem';
doneButton.style.display = 'none'; // Hidden initially
doneButton.addEventListener( 'click', () => {
modal.remove();
} );

progressContainer.appendChild( progressBar );
modalContent.append(
modalTitle,
currentFileName,
progressContainer,
cancelButton
resultList,
doneButton
);
modal.appendChild( modalContent );
document.body.appendChild( modal );

return { modal, progressBar, modalTitle, currentFileName };
return {
modal,
progressBar,
modalTitle,
currentFileName,
resultList,
doneButton,
progressContainer,
};
};

/**
* Opens the modal and resets its display.
*/
const openModal = () => {
cancelRequested = false;
const { progressBar, modalTitle, currentFileName } = createModal();
const {
progressBar,
modalTitle,
currentFileName,
resultList,
doneButton,
progressContainer,
} = createModal();
progressBar.style.width = '0%';
currentFileName.textContent = '';
return { progressBar, modalTitle, currentFileName };
};

/**
* Closes the modal and reloads the page.
*/
const closeModal = () => {
const modal = document.getElementById( 'nfd-bulk-modal' );
if ( modal ) modal.remove();
window.location.reload(); // Reload on close
return {
progressBar,
modalTitle,
currentFileName,
resultList,
doneButton,
progressContainer,
};
};

/**
* Extracts the file name from the attachment element.
*
* @param attachment
*/
const getFileName = ( attachment ) => {
const mediaContent = attachment.closest( '.media-frame-content' );
const fileNameElement = mediaContent?.querySelector( '.filename' );
return fileNameElement?.textContent || 'Unknown File';
return attachment.getAttribute( 'aria-label' );
};

/**
* Handles bulk optimization with progress bar and filename display.
*/
const handleBulkOptimize = async () => {
const selectedItems = Array.from(
document.querySelectorAll( '.attachment.selected' )
Expand All @@ -156,18 +167,30 @@ document.addEventListener( 'DOMContentLoaded', () => {
return;
}

// Open modal and start progress
const { progressBar, modalTitle, currentFileName } = openModal();
const {
progressBar,
modalTitle,
currentFileName,
resultList,
doneButton,
progressContainer,
} = openModal();
const results = [];

try {
for ( let i = 0; i < selectedItems.length; i++ ) {
if ( cancelRequested ) {
modalTitle.textContent = 'Optimization Canceled';
modalTitle.textContent = __(
'Optimization Canceled',
'wp-module-performance'
);
break;
}

const { id: mediaId, name: fileName } = selectedItems[ i ];
currentFileName.textContent = `Optimizing: ${ fileName }`;
currentFileName.textContent =
__( 'Optimizing:', 'wp-module-performance' ) +
` ${ fileName }`;

try {
await wp.apiFetch( {
Expand All @@ -176,23 +199,40 @@ document.addEventListener( 'DOMContentLoaded', () => {
data: { media_id: parseInt( mediaId, 10 ) },
} );

const progress = ( ( i + 1 ) / selectedItems.length ) * 100;
progressBar.style.width = `${ progress }%`;
results.push( { name: fileName, status: 'passed' } );
} catch ( error ) {
console.error(
`Error optimizing media ID: ${ mediaId }`,
error
);
results.push( { name: fileName, status: 'failed' } );
}
}

if ( ! cancelRequested ) {
modalTitle.textContent = 'Optimization Complete!';
setTimeout( closeModal, 2000 );
const progress = ( ( i + 1 ) / selectedItems.length ) * 100;
progressBar.style.width = `${ progress }%`;
}

modalTitle.textContent = __(
'Optimization Complete!',
'wp-module-performance'
);
progressContainer.style.display = 'none';
currentFileName.style.display = 'none';

results.forEach( ( { name, status } ) => {
const listItem = document.createElement( 'li' );
const statusText =
status === 'passed'
? __( 'Passed', 'wp-module-performance' )
: __( 'Failed', 'wp-module-performance' );

listItem.textContent = `${ name } - ${ statusText }`;
resultList.appendChild( listItem );
} );

resultList.style.textAlign = 'center';
doneButton.style.display = 'block';
} catch ( error ) {
modalTitle.textContent = 'An error occurred.';
setTimeout( closeModal, 3000 );
modalTitle.textContent = __(
'An error occurred.',
'wp-module-performance'
);
}
};

Expand All @@ -201,7 +241,10 @@ document.addEventListener( 'DOMContentLoaded', () => {
bulkOptimizeButton.id = bulkOptimizeButtonId;
bulkOptimizeButton.className =
'button media-button button-large button-primary';
bulkOptimizeButton.textContent = 'Optimize';
bulkOptimizeButton.textContent = __(
'Optimize',
'wp-module-performance'
);
bulkOptimizeButton.disabled = true;
bulkOptimizeButton.addEventListener( 'click', handleBulkOptimize );
return bulkOptimizeButton;
Expand Down
2 changes: 1 addition & 1 deletion build/bulk-optimizer.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion includes/Images/ImageSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class ImageSettings {
*/
private const DEFAULT_SETTINGS = array(
'enabled' => true,
'bulk_optimization' => true,
'prefer_optimized_image_when_exists' => true,
'auto_optimized_uploaded_images' => array(
'enabled' => true,
Expand All @@ -27,7 +28,6 @@ class ImageSettings {
'lazy_loading' => array(
'enabled' => true,
),
'bulk_optimization' => true,
);

/**
Expand Down
4 changes: 2 additions & 2 deletions includes/Performance.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
use NewfoldLabs\WP\ModuleLoader\Container;
use NewfoldLabs\WP\Module\Performance\Permissions;
use NewfoldLabs\WP\Module\Installer\Services\PluginInstaller;
use NewfoldLabs\WP\Module\Performance\Images\ImageManager;

use Automattic\Jetpack\Current_Plan;
use NewfoldLabs\WP\Module\Performance\Data\Constants;
use NewfoldLabs\WP\Module\Performance\Images\ImageManager;

/**
* Performance Class
Expand Down Expand Up @@ -75,8 +75,8 @@ public function __construct( Container $container ) {

$cacheManager = new CacheManager( $container );
$cachePurger = new CachePurgingService( $cacheManager->getInstances() );
new ImageManager( $container );
new Constants( $container );
new ImageManager( $container );

add_action( 'admin_bar_menu', array( $this, 'adminBarMenu' ), 100 );
new LinkPrefetch( $container );
Expand Down

0 comments on commit 1b1d100

Please sign in to comment.