# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Commands

```bash
npm run build   # Production build → build/admin/
npm run start   # Dev build with watch
```

No PHP test suite or linter is configured. JS linting uses `@wordpress/scripts` defaults (ESLint + Prettier).

## Deploy

Push a `v*` tag (e.g. `v1.4.0`). GitHub Actions (`.github/workflows/deploy.yml`) runs `npm run build` then deploys to WordPress.org SVN via the 10up deploy action. `.distignore` controls what is excluded from the SVN release — `src/`, `node_modules/`, docs, and dev config files are all excluded; only `build/`, `inc/`, `assets/`, `languages/`, and plugin root files ship.

When releasing, bump the version in **three places**: plugin header (`binsaif-instant-image-optimizer.php` line 5), `BIIO_VERSION` constant (same file, line 25), and `Stable tag` in `readme.txt`. Add changelog entries to `readme.txt` and an Upgrade Notice.

## Architecture

### PHP — `inc/`

All classes live under the `BIIO\ImageOptimizer` namespace and follow a singleton pattern (`private __construct`, `static get_instance()`). The `spl_autoload_register` in the main plugin file maps `BIIO\ImageOptimizer\Foo\Bar` → `inc/Foo/Bar.php`.

| File | Responsibility |
|------|----------------|
| `inc/Plugin.php` | Bootstraps all components, registers activation/deactivation hooks, activation redirect, and the Settings action link on the Plugins screen |
| `inc/Core/Optimizer.php` | REST routes (`biio/v1/metadata`, `biio/v1/optimize-existing`), metadata queue logic, `wp_prepare_attachment_for_js` injection, metadata preservation filter |
| `inc/Core/SVGHandler.php` | Role-gated SVG upload permission, MIME type correction, DOMDocument-based sanitizer, SVG display/srcset hooks |
| `inc/Admin/Dashboard.php` | Settings page render, Settings API registration for `biio_options`, `biioData` JS object localization |
| `inc/Admin/MediaColumn.php` | `biio_filesize` and `biio_savings` Media Library columns, "Optimize It" button, enqueues `assets/css/media.css` on `upload.php` only |

**Settings** are stored as a single serialized option `biio_options`. Schema and defaults live in `Dashboard::register_settings()`. Always use `wp_parse_args(get_option('biio_options', []), $defaults)` when reading options outside `Dashboard` — never assume all keys exist.

**Optimization metadata** is stored under `_wp_attachment_metadata['biio']` (array). The legacy key `iiop` is also read for backwards compatibility. A flat `_biio_savings` post meta (float, 0–1 range, e.g. `0.423`) is written alongside for sortable Media Library column queries.

### JS — `src/`

Built by `@wordpress/scripts` (Webpack). Entry point: `src/admin/index.js` → `build/admin/index.js` + `build/admin/index.css`. The `src/admin/block.json` registers the bundle as a block editor script so WordPress handles script dependencies automatically.

| File | Responsibility |
|------|----------------|
| `src/shared/ImageConverter.js` | Canvas-based WebP conversion class. Skips GIFs, skips files where WebP is larger, returns `{ file, metadata }`. Shared by both upload interception and on-demand optimization. |
| `src/admin/uploader.js` | Intercepts `change`/`drop` events (capture phase) on file inputs across both the main document and the Gutenberg editor iframe. Processes files via `ImageConverter`, POSTs metadata to `biio/v1/metadata`, then re-dispatches the event with the converted files. |
| `src/admin/media-library.js` | Injects BIIO stats into the media modal (Details and TwoColumn views). Also wires up the "Optimize It" button: fetches the image, converts via `ImageConverter`, POSTs file + metadata to `biio/v1/optimize-existing`, then reloads the page. |

**`window.biioData`** is the runtime bridge localized by `Dashboard::enqueue_scripts()`:
```js
{ apiUrl, optimizeExistingUrl, nonce, options, isSettingsPage }
```

### Upload flow (new uploads)

1. `uploader.js` intercepts the browser event → `ImageConverter.convert()` → re-dispatches with WebP file.
2. Converted file uploads to WordPress normally.
3. `uploader.js` POSTs metadata to `biio/v1/metadata` → stored in `biio_metadata_queue` option.
4. WordPress fires `add_attachment` → `Optimizer::attach_metadata()` matches by filename (handles WP's `-1`, `-2` suffixes) → writes `biio` key into attachment metadata and `_biio_savings` post meta → removes item from queue.

### On-demand optimization flow (existing images)

1. "Optimize It" button rendered by `MediaColumn::render_column()` for JPEG, PNG, and SVG (when `svg_optimize_enabled` is on) attachments with no existing `biio` savings data.
2. Click → `media-library.js` fetches the image, converts via `ImageConverter`, POSTs the WebP blob + metadata JSON to `biio/v1/optimize-existing`.
3. PHP endpoint (`Optimizer::handle_optimize_existing()`): validates upload with `is_uploaded_file()`, moves file via WP Filesystem API, deletes old file via `wp_delete_file()`, updates `_wp_attached_file`, `_wp_attachment_metadata`, `post_mime_type`, and `_biio_savings`.
4. JS reloads the page on success so PHP renders the updated savings badge.

### CSS

`assets/css/media.css` contains all Media Library column styles (badges, button states, spinner, file-size display). It is **not** part of the compiled JS bundle — it is enqueued directly by `MediaColumn::enqueue_styles()` on `upload.php` only. Edit this file for any Media Library column visual changes.
