diff --git a/DEVELOPER.md b/DEVELOPER.md
new file mode 100644
index 0000000..5989b93
--- /dev/null
+++ b/DEVELOPER.md
@@ -0,0 +1,181 @@
+# Cimo Developer Integration
+
+Cimo optimizes files in the browser **before** your plugin or theme uploads them.
+It does not replace your upload endpoint or your upload JavaScript.
+
+## How integration works
+
+1. **Enqueue Cimo** on pages where uploads happen (required on the frontend).
+2. **Tell Cimo where or when to optimize**, using one of the methods below.
+
+Most integrations need Step 1 plus **one** method from Step 2.
+You can combine file-picker interception (A) and drag-and-drop interception (B) if your UI supports both.
+
+## Step 1: Enqueue Cimo (required on frontend)
+
+Cimo already loads in wp-admin and the block editor.
+You do not need to enqueue it there.
+
+On frontend pages or other custom screens, you must load Cimo yourself.
+Call `cimo_enqueue_assets()` on the pages where users upload files.
+Always check that the function exists first, in case Cimo is not active.
+
+Register any PHP selector filters **before** you call `cimo_enqueue_assets()` on that page.
+Cimo reads those filters while it loads its scripts.
+Filters added afterward will not apply until the next page load.
+
+**PHP**
+
+```php
+add_action( 'wp_enqueue_scripts', function () {
+ if ( is_page( 'my-upload-form' ) && function_exists( 'cimo_enqueue_assets' ) ) {
+ cimo_enqueue_assets();
+ }
+} );
+```
+
+## Step 2: Choose how Cimo optimizes files
+
+| Your upload UI | What to add after enqueue |
+|----------------|---------------------------|
+| User clicks and picks files (``) | Method A |
+| User drags files into a drop zone | Method B |
+| Your plugin already has JavaScript that uploads via Fetch, XHR, or AJAX | Method C |
+| Both a file picker and drag-and-drop | Method A + Method B |
+
+### Method A: File picker forms (automatic)
+
+Use this when your form has a normal file input.
+Your existing upload code can stay as it is.
+
+1. Wrap the file input in an element with a CSS class you control.
+2. Tell Cimo about that class with the `cimo/select_files/allowed_locations` filter.
+
+**PHP**
+
+```php
+add_filter( 'cimo/select_files/allowed_locations', function ( $locations ) {
+ $locations[] = '.my-plugin-uploader';
+ return $locations;
+} );
+```
+
+**HTML**
+
+```html
+
+
+
+```
+
+The class must be on a wrapper around the file input (or on the input itself).
+Cimo intercepts the `change` event, optimizes the file in the browser, puts the optimized file back on the input, then re-triggers `change` so your existing upload code still runs.
+You do not need to write any Cimo JavaScript for this method.
+
+### Method B: Drag-and-drop zones (automatic)
+
+Use this when users can drop files onto an area on the page, not only pick them from a file dialog.
+
+Tell Cimo about the drop target with the `cimo/drop_zone/allowed_locations` filter.
+
+**PHP**
+
+```php
+add_filter( 'cimo/drop_zone/allowed_locations', function ( $locations ) {
+ $locations[] = '.my-plugin-dropzone';
+ return $locations;
+} );
+```
+
+**HTML**
+
+```html
+
+
Drop images here
+
+```
+
+If the same UI also has a file input, add Method A as well.
+The two filters handle different events: file picking vs dropping.
+
+### Method C: Call the JavaScript API directly (manual)
+
+Use this when your plugin already controls the upload in JavaScript and you can wait for Cimo before sending the files.
+
+Call `window.cimo.optimizeFiles()` first.
+Then upload the files it returns.
+
+**JavaScript**
+
+```js
+async function onFilesSelected( files ) {
+ const results = await window.cimo.optimizeFiles( files, { showProgress: true } )
+ const filesToUpload = results.map( ( { file } ) => file )
+
+ // Continue with your plugin or theme upload flow.
+ await uploadFiles( filesToUpload )
+}
+```
+
+The API accepts a single `File`, a `FileList`, or an array of `File` objects.
+It returns:
+
+**JavaScript**
+
+```js
+[
+ {
+ file: File,
+ metadata: Object || null,
+ },
+]
+```
+
+`showProgress` defaults to `true`.
+Set it to `false` if your UI already shows upload or optimization progress.
+
+If Cimo optimization is disabled or a file type is unsupported, the original file is returned with `metadata: null`.
+
+## Complete minimal example
+
+This is a frontend form with a file picker only.
+It uses Step 1 plus Method A.
+No other Cimo code is required.
+
+**PHP**
+
+```php
+add_filter( 'cimo/select_files/allowed_locations', function ( $locations ) {
+ $locations[] = '.my-plugin-uploader';
+ return $locations;
+} );
+
+add_action( 'wp_enqueue_scripts', function () {
+ if ( is_page( 'submit-photo' ) && function_exists( 'cimo_enqueue_assets' ) ) {
+ cimo_enqueue_assets();
+ }
+} );
+```
+
+**HTML**
+
+```html
+
+```
+
+## Notes
+
+The same JavaScript API is used in free and premium.
+If Cimo Premium is loaded, premium converters are applied automatically.
+There is no separate premium entry point.
+
+Cimo optimization is pre-upload only.
+It does not optimize by attachment ID, bulk replace existing files, or run server-side Imagick/GD compression.
+
+On guest frontend uploads, files can still be optimized in the browser.
+Stats and metadata in wp-admin may not appear when the visitor is not logged in or cannot access the Cimo metadata endpoint.
diff --git a/cimo.php b/cimo.php
index bb5a5f9..58e2c2a 100644
--- a/cimo.php
+++ b/cimo.php
@@ -22,6 +22,18 @@
defined( 'CIMO_SETTINGS_SLUG' ) || define( 'CIMO_SETTINGS_SLUG', 'cimo-settings' );
require_once __DIR__ . '/src/admin/class-script-loader.php';
+
+if ( ! function_exists( 'cimo_enqueue_assets' ) ) {
+ /**
+ * Public helper for integrators to enqueue Cimo on custom upload screens.
+ */
+ function cimo_enqueue_assets() {
+ if ( class_exists( 'Cimo_Script_Loader' ) ) {
+ Cimo_Script_Loader::enqueue_cimo_assets();
+ }
+ }
+}
+
require_once __DIR__ . '/src/admin/class-meta-box.php';
require_once __DIR__ . '/src/admin/class-metadata.php';
require_once __DIR__ . '/src/admin/class-admin-notices.php';
@@ -45,4 +57,4 @@ function cimo_activate() {
if ( file_exists( plugin_dir_path( __FILE__ ) . 'pro__premium_only/index.php' ) ) {
require_once( plugin_dir_path( __FILE__ ) . 'pro__premium_only/index.php' );
}
-}
\ No newline at end of file
+}
diff --git a/e2e/fixtures/mu-plugins/cimo-e2e-dev-api.php b/e2e/fixtures/mu-plugins/cimo-e2e-dev-api.php
new file mode 100644
index 0000000..2975ed5
--- /dev/null
+++ b/e2e/fixtures/mu-plugins/cimo-e2e-dev-api.php
@@ -0,0 +1,49 @@
+post_title, 'Cimo Dev API E2E' ) ) {
+ return;
+ }
+
+ cimo_enqueue_assets();
+ }
+);
diff --git a/e2e/readme.md b/e2e/readme.md
index 05435b6..f2be30c 100644
--- a/e2e/readme.md
+++ b/e2e/readme.md
@@ -125,6 +125,7 @@ WP_PASSWORD=password
| Progress modal | Cancel when visible |
| Post-upload | Sidebar stats + attachment meta box |
| Freemium | Locked premium sections (LQIP/video/audio/SVG/stealth), bulk upsell, plugins links |
+| Developer API | Frontend enqueue + PHP selectors convert JPG → WebP; unrelated inputs stay JPEG; `optimizeFiles()` returns WebP + metadata |
| Elementor | Image widget media upload → WebP |
### Premium (`e2e/tests/premium/`)
@@ -146,10 +147,11 @@ WP_PASSWORD=password
| Path | Role |
| --- | --- |
-| `../playwright.config.js` | Free suite; Playground on 9410; ignores `tests/premium/` and `tests/elementor/` |
+| `../playwright.config.js` | Free suite; Playground on 9410; ignores `tests/premium/` and `tests/elementor/`; mounts `e2e/fixtures/mu-plugins` |
| `../playwright.premium.config.js` | Premium suite; Playground on 9411 |
| `../playwright.elementor.config.js` | Elementor smoke; Playground on 9412 |
| `playground-blueprint.json` | Login + activate Cimo (free) |
+| `fixtures/mu-plugins/` | Free-suite mu-plugin that registers integrator selectors and enqueues Cimo on Dev API e2e pages |
| `playground-blueprint.premium.json` | Activate + seed Freemius premium plan |
| `playground-blueprint.elementor.json` | Install Elementor + activate Cimo |
| `config/global-setup.js` | Cookie-authenticates via `RequestUtils.setup()`, persists `storageState` |
diff --git a/e2e/tests/developer-api.spec.ts b/e2e/tests/developer-api.spec.ts
new file mode 100644
index 0000000..c3a543e
--- /dev/null
+++ b/e2e/tests/developer-api.spec.ts
@@ -0,0 +1,275 @@
+import {
+ test,
+ expect,
+ SAMPLE_JPG,
+ dropFile,
+ waitForCimoReady,
+ saveCimoOptions,
+ deletePage,
+ reloadCimoRuntime,
+} from '../test-utils'
+
+test.describe.configure( { timeout: 180_000 } )
+
+type CimoWindow = Window & {
+ cimo?: {
+ optimizeFiles?: (
+ files: File | FileList | File[],
+ options?: { showProgress?: boolean }
+ ) => Promise | null,
+ }>>;
+ };
+ cimoSettings?: {
+ selectFilesAllowedLocations?: string[];
+ dropZoneAllowedLocations?: string[];
+ };
+}
+
+async function waitForCimoPublicApi( page: import( '@playwright/test' ).Page ) {
+ await waitForCimoReady( page )
+ await page.waitForFunction( () => {
+ return typeof ( window as CimoWindow ).cimo?.optimizeFiles === 'function'
+ }, undefined, { timeout: 30_000 } )
+}
+
+test.describe( 'Developer integration API', () => {
+ let pageId: number | null = null
+
+ test.beforeEach( async ( { requestUtils } ) => {
+ await requestUtils.deleteAllMedia()
+ await saveCimoOptions( requestUtils, {
+ webp_quality: 80,
+ max_image_dimension: 0,
+ disable_thumbnail_generation: 1,
+ smart_optimization: 0,
+ } )
+ } )
+
+ test.afterEach( async ( { requestUtils } ) => {
+ if ( pageId ) {
+ await deletePage( requestUtils, pageId )
+ pageId = null
+ }
+ await requestUtils.deleteAllMedia()
+ await saveCimoOptions( requestUtils, {
+ disable_thumbnail_generation: 0,
+ } )
+ } )
+
+ async function openDevApiPage(
+ requestUtils: import( '@wordpress/e2e-test-utils-playwright' ).RequestUtils,
+ page: import( '@playwright/test' ).Page,
+ html: string
+ ) {
+ const draft = await requestUtils.createPage( {
+ title: 'Cimo Dev API E2E',
+ status: 'publish',
+ content: `${ html }`,
+ } )
+ pageId = draft.id
+
+ await reloadCimoRuntime( page )
+ await page.goto( `/?p=${ pageId }` )
+ await waitForCimoPublicApi( page )
+ return draft
+ }
+
+ test( 'enqueues Cimo on a marked frontend page and localizes selector filters', async ( {
+ page,
+ requestUtils,
+ } ) => {
+ await openDevApiPage(
+ requestUtils,
+ page,
+ ''
+ )
+
+ const runtime = await page.evaluate( () => {
+ const settings = ( window as CimoWindow ).cimoSettings
+ return {
+ hasOptimizeFiles: typeof ( window as CimoWindow ).cimo?.optimizeFiles === 'function',
+ selectFilesAllowedLocations: settings?.selectFilesAllowedLocations || [],
+ dropZoneAllowedLocations: settings?.dropZoneAllowedLocations || [],
+ }
+ } )
+
+ expect( runtime.hasOptimizeFiles ).toBe( true )
+ expect( runtime.selectFilesAllowedLocations ).toContain( '.cimo-e2e-dev-uploader' )
+ expect( runtime.dropZoneAllowedLocations ).toContain( '.cimo-e2e-dev-dropzone' )
+ } )
+
+ test( 'intercepts a frontend file input registered through PHP selectors', async ( {
+ page,
+ requestUtils,
+ } ) => {
+ await openDevApiPage(
+ requestUtils,
+ page,
+ ''
+ )
+
+ const fileInput = page.locator( '#cimo-e2e-dev-file' )
+ await expect( fileInput ).toBeVisible()
+ await fileInput.setInputFiles( SAMPLE_JPG )
+
+ await expect.poll( async () => {
+ return await fileInput.evaluate( ( input: HTMLInputElement ) => {
+ const file = input.files?.[ 0 ]
+ return file ? { type: file.type, name: file.name } : null
+ } )
+ }, {
+ timeout: 60_000,
+ message: 'Expected the PHP selector filter to replace the selected file with WebP',
+ } ).toMatchObject( {
+ type: 'image/webp',
+ } )
+
+ const converted = await fileInput.evaluate( ( input: HTMLInputElement ) => {
+ const file = input.files?.[ 0 ]
+ return {
+ type: file?.type,
+ name: file?.name,
+ }
+ } )
+ expect( converted.type ).toBe( 'image/webp' )
+ expect( converted.name ).toMatch( /\.webp$/i )
+ } )
+
+ test( 'leaves a file input unchanged when it is outside allowed locations', async ( {
+ page,
+ requestUtils,
+ } ) => {
+ await openDevApiPage(
+ requestUtils,
+ page,
+ ''
+ )
+
+ const fileInput = page.locator( '#cimo-e2e-unrelated-file' )
+ await expect( fileInput ).toBeVisible()
+ await fileInput.setInputFiles( SAMPLE_JPG )
+
+ await expect( async () => {
+ const selected = await fileInput.evaluate( ( input: HTMLInputElement ) => {
+ return input.files?.[ 0 ]?.type || null
+ } )
+ expect( selected ).toBe( 'image/webp' )
+ } ).not.toPass( {
+ timeout: 8_000,
+ } )
+
+ const selected = await fileInput.evaluate( ( input: HTMLInputElement ) => {
+ const file = input.files?.[ 0 ]
+ return {
+ type: file?.type,
+ name: file?.name,
+ }
+ } )
+ expect( selected.type ).toBe( 'image/jpeg' )
+ expect( selected.name ).toMatch( /\.jpe?g$/i )
+ } )
+
+ test( 'intercepts a frontend drop zone registered through PHP selectors', async ( {
+ page,
+ requestUtils,
+ } ) => {
+ await openDevApiPage(
+ requestUtils,
+ page,
+ '
'
+ )
+
+ const results = await page.evaluate( async () => {
+ const optimizeFiles = ( window as CimoWindow ).cimo?.optimizeFiles
+ if ( ! optimizeFiles ) {
+ return null
+ }
+
+ const file = new File( [ 'plain text' ], 'note.txt', { type: 'text/plain' } )
+ const optimized = await optimizeFiles( [ file ], { showProgress: false } )
+ return optimized.map( ( { file: resultFile, metadata } ) => ( {
+ type: resultFile.type,
+ name: resultFile.name,
+ hasMetadata: metadata !== null,
+ } ) )
+ } )
+
+ expect( results ).toEqual( [
+ {
+ type: 'text/plain',
+ name: 'note.txt',
+ hasMetadata: false,
+ },
+ ] )
+ } )
+} )
diff --git a/playwright.config.js b/playwright.config.js
index f2111f7..334b172 100644
--- a/playwright.config.js
+++ b/playwright.config.js
@@ -44,6 +44,7 @@ module.exports = defineConfig( {
command: [
'npx @wp-playground/cli server',
'--mount=.:/wordpress/wp-content/plugins/cimo',
+ '--mount=./e2e/fixtures/mu-plugins:/wordpress/wp-content/mu-plugins',
`--blueprint=${ PLAYGROUND_BLUEPRINT }`,
'--php=8.2',
`--port=${ PORT }`,
diff --git a/readme.txt b/readme.txt
index 7765c92..ee92e6d 100644
--- a/readme.txt
+++ b/readme.txt
@@ -45,6 +45,7 @@ Just upload images to your Media Manager as you normally would, then Cimo instan
3. **Privacy-First** – your images never leave your device until they're uploaded to WordPress.
4. **Future-Proof Format** – automatic WebP conversion reduces file sizes by up to 80%, with full control over quality, dimensions, and thumbnail generation.
5. **Universal Compatibility** – works seamlessly with the WordPress Block Editor, Elementor, Beaver Builder, and all major page builders.
+6. **Developer Friendly** – integrate your own upload UI with a small PHP helper and optional JavaScript API. See the [developer integration guide](https://docs.wpcimo.com/article/798-developer-integration?utm_source=plugin-directory&utm_medium=plugin-page&utm_campaign=readme-txt).
= Works with =
@@ -69,6 +70,19 @@ Just upload images to your Media Manager as you normally would, then Cimo instan
**Since Cimo's optimization works during the upload process, Cimo should be compatible with any plugin that uses images**
+= For developers =
+
+Cimo can optimize files in the browser before your plugin or theme uploads them.
+Your existing upload code can stay as it is.
+
+On frontend pages, load Cimo with `cimo_enqueue_assets()`, then either:
+
+* Register your file input wrapper with `cimo/select_files/allowed_locations`
+* Register a drop zone with `cimo/drop_zone/allowed_locations`
+* Or call `window.cimo.optimizeFiles()` from your own JavaScript
+
+See the [developer integration guide](https://docs.wpcimo.com/article/798-developer-integration?utm_source=plugin-directory&utm_medium=plugin-page&utm_campaign=readme-txt) for the full walkthrough.
+
= What's in Cimo Premium? =
Free already optimizes images as you upload. [Cimo Premium](https://wpcimo.com/pricing/?utm_source=plugin-directory&utm_medium=plugin-page&utm_campaign=readme-txt) finishes the job on what's already on your site:
@@ -100,6 +114,11 @@ Video & Audio optimization are also performed as you upload your files, even bef
== Frequently Asked Questions ==
+= Can I use Cimo with my own plugin or theme upload form? =
+
+Yes. Load Cimo on that page with `cimo_enqueue_assets()`, then tell Cimo about your file input or drop zone, or call `window.cimo.optimizeFiles()` from your JavaScript.
+See the [developer integration guide](https://docs.wpcimo.com/article/798-developer-integration?utm_source=plugin-directory&utm_medium=faq&utm_campaign=readme-txt).
+
= What makes Cimo different from other image optimizers? =
Unlike server-side plugins, Cimo processes everything in your browser. No external APIs, no server processing, no waiting - just instant optimization as you upload.
diff --git a/src/admin/class-script-loader.php b/src/admin/class-script-loader.php
index 76e80ed..9418fed 100644
--- a/src/admin/class-script-loader.php
+++ b/src/admin/class-script-loader.php
@@ -48,6 +48,67 @@ public function maybe_enqueue_for_bricks_builder() {
}
}
+ /**
+ * Get selectors where Cimo should intercept file input selections.
+ *
+ * @return array
+ */
+ public static function get_select_files_allowed_locations() {
+ $locations = [
+ '.components-form-file-upload', // Allow uploads to the image block.
+ '.media-frame', // Allow uploads from the Media Manager.
+ '.media-upload-form', // Allow uploads from the admin Media > Add Media File.
+ '.moxie-shim', // Allow uploads from the admin Media > Library grid view.
+ ];
+
+ // Public integration point for plugins/themes that want Cimo to auto-intercept
+ // file inputs inside their own upload UI.
+ return self::sanitize_allowed_locations(
+ apply_filters( 'cimo/select_files/allowed_locations', $locations )
+ );
+ }
+
+ /**
+ * Get selectors where Cimo should intercept file drops.
+ *
+ * @return array
+ */
+ public static function get_drop_zone_allowed_locations() {
+ $locations = [
+ '.media-frame-uploader', // Allowed to drop in the Media Manager.
+ '.media-upload-form', // Allowed to drop in the admin Media > Add Media File.
+ '.editor-post-featured-image', // Allowed to drop in the featured image drop zone.
+ '.editor-styles-wrapper', // Allowed to drop in the block editor when adding new image blocks.
+ '.uploader-window', // Allowed to drop in the admin Media > Library grid view.
+ '.uploader-editor', // Allowed to drop in the WooCommerce description editor.
+ '.block-library-utils__media-control', // Allowed to drop in the block editor image block media control.
+ ];
+
+ // Public integration point for plugins/themes that want Cimo to auto-intercept
+ // dropped files inside their own upload UI.
+ return self::sanitize_allowed_locations(
+ apply_filters( 'cimo/drop_zone/allowed_locations', $locations )
+ );
+ }
+
+ /**
+ * Keep localized selector settings as a clean list of strings.
+ *
+ * @param mixed $locations Selectors from defaults and filters.
+ * @return array
+ */
+ private static function sanitize_allowed_locations( $locations ) {
+ if ( ! is_array( $locations ) ) {
+ return [];
+ }
+
+ $locations = array_filter( $locations, 'is_string' );
+ $locations = array_map( 'trim', $locations );
+ $locations = array_filter( $locations );
+
+ return array_values( array_unique( $locations ) );
+ }
+
public static function enqueue_cimo_assets() {
// If cimo-script is already enqueued, don't enqueue again.
if ( wp_script_is( 'cimo-script', 'enqueued' ) ) {
@@ -112,6 +173,9 @@ public static function enqueue_cimo_assets() {
'svgOptimizationEnabled' => isset( $settings['svg_optimization_enabled'] ) ? (int) $settings['svg_optimization_enabled'] : 1,
'stealthModeEnabled' => isset( $settings['stealth_mode_enabled'] ) ? (int) $settings['stealth_mode_enabled'] : 0,
'wpScalingThreshold' => $threshold,
+ // Public PHP selector filters are localized for the browser-side interceptors.
+ 'selectFilesAllowedLocations' => self::get_select_files_allowed_locations(),
+ 'dropZoneAllowedLocations' => self::get_drop_zone_allowed_locations(),
]
);
diff --git a/src/admin/js/index.js b/src/admin/js/index.js
index fb75ac4..05d3c4c 100644
--- a/src/admin/js/index.js
+++ b/src/admin/js/index.js
@@ -1,3 +1,4 @@
+import './public-api'
import './media-manager/drop-zone'
import './media-manager/select-files'
import './media-manager/sidebar-info'
diff --git a/src/admin/js/media-manager/allowed-locations.js b/src/admin/js/media-manager/allowed-locations.js
new file mode 100644
index 0000000..d0c839f
--- /dev/null
+++ b/src/admin/js/media-manager/allowed-locations.js
@@ -0,0 +1,56 @@
+import { applyFilters } from '@wordpress/hooks'
+
+const normalizeLocations = locations => {
+ if ( ! Array.isArray( locations ) ) {
+ return []
+ }
+
+ return locations.filter( location => typeof location === 'string' && location.length > 0 )
+}
+
+/**
+ * Get current select file selectors from PHP settings and internal JS filters.
+ *
+ * @return {Array} Selectors where file input changes should be intercepted.
+ */
+export const getSelectFilesAllowedLocations = () => {
+ const locations = normalizeLocations( window.cimoSettings?.selectFilesAllowedLocations )
+
+ return normalizeLocations( applyFilters( 'cimo.selectFiles.allowedLocations', locations ) )
+}
+
+/**
+ * Get current drop zone selectors from PHP settings and internal JS filters.
+ *
+ * @return {Array} Selectors where file drops should be intercepted.
+ */
+export const getDropZoneAllowedLocations = () => {
+ const locations = normalizeLocations( window.cimoSettings?.dropZoneAllowedLocations )
+
+ return normalizeLocations( applyFilters( 'cimo.dropZone.allowedLocations', locations ) )
+}
+
+/**
+ * Find the closest ancestor matching one of Cimo's allowed upload locations.
+ *
+ * @param {Element} element Element where the upload event started.
+ * @param {Array} locations CSS selectors to test.
+ * @return {Element|null} Matching element, if one exists.
+ */
+export const closestAllowedLocation = ( element, locations ) => {
+ for ( const location of locations ) {
+ try {
+ // Invalid selectors should not break uploads; ignore them and keep checking.
+ const matchedElement = element.closest( location )
+
+ if ( matchedElement ) {
+ return matchedElement
+ }
+ } catch ( error ) {
+ // eslint-disable-next-line no-console
+ console.warn( `[Cimo] Ignoring invalid selector: ${ location }`, error )
+ }
+ }
+
+ return null
+}
diff --git a/src/admin/js/media-manager/drop-zone.js b/src/admin/js/media-manager/drop-zone.js
index deee381..46af5b5 100644
--- a/src/admin/js/media-manager/drop-zone.js
+++ b/src/admin/js/media-manager/drop-zone.js
@@ -8,27 +8,14 @@
import { domReady } from '~cimo/shared/dom-ready'
import { getFileConverter, requiresFileConversion } from '~cimo/shared/converters'
import { watchForEditorIframe } from '~cimo/shared/util'
-import { saveMetadata } from '~cimo/shared/metadata-saver'
-import { cacheConverterNotice } from '~cimo/shared/upload-notice-cache'
-import { ProgressModal } from './progress-modal'
-import { applyFilters } from '@wordpress/hooks'
+import { optimizeFileConverters } from '../optimize-files'
+import { closestAllowedLocation, getDropZoneAllowedLocations } from './allowed-locations'
/**
* Intercept editor media uploads and convert images to WebP on the client
* before uploading to WordPress. This affects the block editor only.
*/
-// Allowed locations to be able to select files.
-const ALLOWED_LOCATIONS = applyFilters( 'cimo.dropZone.allowedLocations', [
- '.media-frame-uploader', // Allowed to drop in the Media Manager
- '.media-upload-form', // Allowed to drop in the admin Media > Add Media File
- '.editor-post-featured-image', // Allowed to drop in the featured image drop zone
- '.editor-styles-wrapper', // Allowed to drop in the block editor when adding new image blocks
- '.uploader-window', // Allowed to drop in the admin Media > Library grid view
- '.uploader-editor', // Allowed to drop in the WooCommerce description editor
- '.block-library-utils__media-control', // Allowed to drop in the block editor image block media control
-] )
-
// Add event listener to the Media Manager's drop zone
function addDropZoneListenerToMediaManager( targetDocument ) {
if ( ! targetDocument ) {
@@ -59,18 +46,8 @@ function addDropZoneListenerToMediaManager( targetDocument ) {
return
}
- // TODO: We also want to filter out the target so we can set when this
- // is triggered. We might break other funcitonality that we don't have
- // the conversion to happen.
-
// Find the matched element based on the locations
- let matchedElement
- for ( const location of ALLOWED_LOCATIONS ) {
- matchedElement = event.target.closest( location )
- if ( matchedElement ) {
- break
- }
- }
+ let matchedElement = closestAllowedLocation( event.target, getDropZoneAllowedLocations() )
// Allowed a fallback to drop in the Media Manager
matchedElement = matchedElement || event.target.closest( '.supports-drag-drop' )
@@ -99,39 +76,12 @@ function addDropZoneListenerToMediaManager( targetDocument ) {
uploaderWindow.style.display = 'none'
}
- // Cancel the conversion if the user closes the progress modal.
- const onCancel = () => {
- // This is enough to cancel the entire process since the promises below will finish resolving.
- fileConverters.forEach( converter => converter.cancel() )
- }
-
- // Show the progress modal
- const progressModal = new ProgressModal( fileConverters, onCancel )
- progressModal.open()
-
// Process and optimize each media file here,
// e.g. converting to webp, resizing, compressing, etc.
- const optimizedResults = await Promise.all(
- fileConverters.map( async converter => {
- try {
- const result = await converter.optimize()
- cacheConverterNotice( result )
- if ( result.error ) {
- // eslint-disable-next-line no-console
- console.warn( result.error )
- }
- return result
- } catch ( error ) {
- // eslint-disable-next-line no-console
- console.warn( error )
- return { file: converter.file, metadata: null }
- }
- } )
- )
+ const optimizedResults = await optimizeFileConverters( fileConverters )
// Extract files and metadata from results
const optimizedFiles = optimizedResults.map( result => result.file )
- const conversionMetadata = optimizedResults.map( result => result.metadata )
// Create a DataTransfer to hold the optimized file
const dataTransfer = new DataTransfer()
@@ -139,9 +89,6 @@ function addDropZoneListenerToMediaManager( targetDocument ) {
dataTransfer.items.add( file )
} )
- // Save the metadata to the server.
- await saveMetadata( conversionMetadata )
-
// Find the correct target to dispatch the event to
let target = event.target.closest( '.components-drop-zone, [data-is-drop-zone="true"]' ) || event.target
// This specifically handles the WooCommerce/classic description editor
@@ -218,9 +165,6 @@ function addDropZoneListenerToMediaManager( targetDocument ) {
target.dispatchEvent( dropEvent )
}
}
-
- // Close when optimization finishes, including when we fall back to the original file after an error.
- progressModal.close()
}
// Add our custom drop listener
diff --git a/src/admin/js/media-manager/select-files.js b/src/admin/js/media-manager/select-files.js
index cf5db4e..b3a5d45 100644
--- a/src/admin/js/media-manager/select-files.js
+++ b/src/admin/js/media-manager/select-files.js
@@ -8,18 +8,8 @@
import { domReady } from '~cimo/shared/dom-ready'
import { getFileConverter, requiresFileConversion } from '~cimo/shared/converters'
import { watchForEditorIframe } from '~cimo/shared/util'
-import { saveMetadata } from '~cimo/shared/metadata-saver'
-import { cacheConverterNotice } from '~cimo/shared/upload-notice-cache'
-import { ProgressModal } from './progress-modal'
-import { applyFilters } from '@wordpress/hooks'
-
-// Allowed locations to be able to select files.
-const ALLOWED_LOCATIONS = applyFilters( 'cimo.selectFiles.allowedLocations', [
- '.components-form-file-upload', // Allow uploads to the image block
- '.media-frame', // Allow uploads from the Media Manager
- '.media-upload-form', // Allow uploads from the admin Media > Add Media File
- '.moxie-shim', // Allow uploads from the admin Media > Library grid view
-] )
+import { optimizeFileConverters } from '../optimize-files'
+import { closestAllowedLocation, getSelectFilesAllowedLocations } from './allowed-locations'
// Add event listener to the Media Manager's drop zone
function addSelectFilesListenerToFileUploads( targetDocument ) {
@@ -56,12 +46,8 @@ function addSelectFilesListenerToFileUploads( targetDocument ) {
return
}
- // TODO: We need filter this so that we will only override this on file
- // selects that we want to, like the media manager picker or the image
- // block uploader.
// Allow these locations to be able to select files.
- const isAllowed = ALLOWED_LOCATIONS.some( selector => event.target.closest( selector ) )
- if ( ! isAllowed ) {
+ if ( ! closestAllowedLocation( event.target, getSelectFilesAllowedLocations() ) ) {
return
}
@@ -77,39 +63,12 @@ function addSelectFilesListenerToFileUploads( targetDocument ) {
event.stopPropagation()
event.stopImmediatePropagation()
- // Cancel the conversion if the user closes the progress modal.
- const onCancel = () => {
- // This is enough to cancel the entire process since the promises below will finish resolving.
- fileConverters.forEach( converter => converter.cancel() )
- }
-
- // Show the progress modal
- const progressModal = new ProgressModal( fileConverters, onCancel )
- progressModal.open()
-
// Process and optimize each media file here,
// e.g. converting to webp, resizing, compressing, etc.
- const optimizedResults = await Promise.all(
- fileConverters.map( async converter => {
- try {
- const result = await converter.optimize()
- cacheConverterNotice( result )
- if ( result.error ) {
- // eslint-disable-next-line no-console
- console.warn( result.error )
- }
- return result
- } catch ( error ) {
- // eslint-disable-next-line no-console
- console.warn( error )
- return { file: converter.file, metadata: null }
- }
- } )
- )
+ const optimizedResults = await optimizeFileConverters( fileConverters )
// Extract files from results
const optimizedFiles = optimizedResults.map( result => result.file )
- const conversionMetadata = optimizedResults.map( result => result.metadata )
// Create a DataTransfer to hold the optimized file
const dataTransfer = new DataTransfer()
@@ -117,9 +76,6 @@ function addSelectFilesListenerToFileUploads( targetDocument ) {
dataTransfer.items.add( file )
} )
- // Save the metadata to the server.
- await saveMetadata( conversionMetadata )
-
// Assign the files to the input element
event.target.files = dataTransfer.files
@@ -128,9 +84,6 @@ function addSelectFilesListenerToFileUploads( targetDocument ) {
// Mark this event so we know conversion is already done
changeEvent.__cimo_converted = true // eslint-disable-line camelcase
event.target.dispatchEvent( changeEvent )
-
- // Close when optimization finishes, including when we fall back to the original file after an error.
- progressModal.close()
}
if ( ! targetDocument.body.__cimo_selectfiles_listener_attached ) {
diff --git a/src/admin/js/optimize-files.js b/src/admin/js/optimize-files.js
new file mode 100644
index 0000000..aabd013
--- /dev/null
+++ b/src/admin/js/optimize-files.js
@@ -0,0 +1,128 @@
+import { getFileConverter, requiresFileConversion } from '~cimo/shared/converters'
+import { saveMetadata } from '~cimo/shared/metadata-saver'
+import { cacheConverterNotice } from '~cimo/shared/upload-notice-cache'
+import { ProgressModal } from './media-manager/progress-modal'
+
+/**
+ * Normalize the public API input shape. Integrators may pass a single File,
+ * FileList, DataTransfer file list, or plain array of File objects.
+ *
+ * @param {File|FileList|Array} files Files to optimize.
+ * @return {Array} Normalized file array.
+ */
+const normalizeFiles = files => {
+ if ( ! files ) {
+ return []
+ }
+
+ if ( typeof files.length === 'number' ) {
+ return Array.from( files )
+ }
+
+ return [ files ]
+}
+
+/**
+ * Optimize an existing converter list and save Cimo metadata before the
+ * caller's upload flow continues.
+ *
+ * Interceptors use this after they have already checked whether conversion is
+ * required. The public API usually calls optimizeFiles() instead.
+ *
+ * @param {Array} fileConverters Converter instances.
+ * @param {Object} options Options for the optimization run.
+ * @param {boolean} [options.showProgress=true] Whether to show Cimo's progress modal.
+ * @return {Promise>} Optimized files and metadata.
+ */
+export const optimizeFileConverters = async ( fileConverters, options = {} ) => {
+ const converters = Array.isArray( fileConverters ) ? fileConverters : []
+
+ if ( window.cimoSettings?.disableOptimization ) {
+ return converters.map( converter => ( {
+ file: converter.file,
+ metadata: null,
+ } ) )
+ }
+
+ const showProgress = options.showProgress !== false
+
+ // Cancel the conversion if the user closes the progress modal.
+ const onCancel = () => {
+ // This is enough to cancel the entire process since the promises below will finish resolving.
+ converters.forEach( converter => converter.cancel() )
+ }
+
+ // Show the progress modal.
+ const progressModal = showProgress
+ ? new ProgressModal( converters, onCancel )
+ : null
+
+ progressModal?.open()
+
+ try {
+ // Process and optimize each media file here,
+ // e.g. converting to webp, resizing, compressing, etc.
+ const optimizedResults = await Promise.all(
+ converters.map( async converter => {
+ try {
+ const result = await converter.optimize()
+ cacheConverterNotice( result )
+ if ( result.error ) {
+ // eslint-disable-next-line no-console
+ console.warn( result.error )
+ }
+ return result
+ } catch ( error ) {
+ // eslint-disable-next-line no-console
+ console.warn( error )
+ return { file: converter.file, metadata: null }
+ }
+ } )
+ )
+
+ // Save the metadata to the server.
+ await saveMetadata( optimizedResults.map( result => result.metadata ?? null ) )
+
+ return optimizedResults.map( result => ( {
+ file: result.file,
+ metadata: result.metadata ?? null,
+ } ) )
+ } finally {
+ // Close when optimization finishes, including when we fall back to the original file after an error.
+ progressModal?.close()
+ }
+}
+
+/**
+ * Public optimization entry point exposed as window.cimo.optimizeFiles().
+ *
+ * Cimo only handles pre-upload optimization here. The integrator remains
+ * responsible for uploading results.map( result => result.file ) through their
+ * normal upload flow.
+ *
+ * @param {File|FileList|Array} files Files to optimize before upload.
+ * @param {Object} options Options for the optimization run.
+ * @param {boolean} [options.showProgress=true] Whether to show Cimo's progress modal.
+ * @return {Promise>} Files for the caller to upload.
+ */
+export const optimizeFiles = async ( files, options = {} ) => {
+ if ( window.cimoSettings?.disableOptimization ) {
+ return normalizeFiles( files ).map( file => ( {
+ file,
+ metadata: null,
+ } ) )
+ }
+
+ // Use Cimo's shared converter resolver so free and premium converters follow
+ // the same path as Media Library uploads.
+ const fileConverters = normalizeFiles( files ).map( file => getFileConverter( file ) )
+
+ if ( ! requiresFileConversion( fileConverters ) ) {
+ return fileConverters.map( converter => ( {
+ file: converter.file,
+ metadata: null,
+ } ) )
+ }
+
+ return optimizeFileConverters( fileConverters, options )
+}
diff --git a/src/admin/js/public-api.js b/src/admin/js/public-api.js
new file mode 100644
index 0000000..3d520fe
--- /dev/null
+++ b/src/admin/js/public-api.js
@@ -0,0 +1,7 @@
+import { optimizeFiles } from './optimize-files'
+
+window.cimo = window.cimo || {}
+
+// Stable public API for plugins/themes that need pre-upload optimization.
+// Returns { file, metadata } results.
+window.cimo.optimizeFiles = optimizeFiles