Skip to content

Use a rest api url that works on subsites as well as if someone changes the rest api base - #1737

Merged
pattonwebz merged 6 commits into
developfrom
william/no-issue/fix-subsite-multisite-saving-from-frontend-and-full-site-scanner
Jun 22, 2026
Merged

Use a rest api url that works on subsites as well as if someone changes the rest api base#1737
pattonwebz merged 6 commits into
developfrom
william/no-issue/fix-subsite-multisite-saving-from-frontend-and-full-site-scanner

Conversation

@pattonwebz

@pattonwebz pattonwebz commented Jun 5, 2026

Copy link
Copy Markdown
Member

This pull request updates how REST API endpoint URLs are handled throughout the plugin, ensuring they are dynamically passed from PHP to JavaScript rather than being hardcoded. This change improves compatibility with custom site configurations and makes the codebase more maintainable. The main updates involve adding new variables for REST URLs in PHP and refactoring JavaScript to use these variables.

REST API URL Handling Improvements:

  • Added restUrl and fixesRestUrl variables to the localized script data in both admin (maybe_enqueue_admin_and_editor_app_scripts) and frontend (maybe_enqueue_frontend_highlighter) PHP enqueue functions, ensuring all REST endpoint URLs are dynamically generated and available for JavaScript. [1] [2]

  • Updated JavaScript (src/frontendHighlighterApp/index.js and src/common/saveFixSettingsRest.js) to use the new restUrl and fixesRestUrl variables instead of hardcoded REST endpoint paths, improving flexibility and reliability. [1] [2] [3]

Validation and Error Handling:

  • Modified the frontend highlighter app to validate the presence of restUrl instead of the previously used edacUrl, ensuring required parameters are correctly checked before making API calls.

Summary by CodeRabbit

  • New Features
    • Frontend and admin now receive explicit REST endpoint URLs so the apps use configurable API bases.
  • Bug Fixes
    • Frontend actions (save/clear) handle missing REST URL gracefully and surface a “Missing REST API URL.” message.
  • Tests
    • Added tests covering REST endpoint exposure and custom REST prefix behavior.

@coderabbitai

coderabbitai Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Need an answer fast? Review this PR in Change Stack to ask focused questions about the PR or a changed range.

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 879f99cd-6222-45c4-9fac-8dc63fc850d7

📥 Commits

Reviewing files that changed from the base of the PR and between 08d4a7e and ce8674d.

📒 Files selected for processing (2)
  • src/common/saveFixSettingsRest.js
  • src/frontendHighlighterApp/index.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/common/saveFixSettingsRest.js
  • src/frontendHighlighterApp/index.js

📝 Walkthrough

Walkthrough

Hardcoded WP REST paths were replaced with localized REST base URLs. PHP enqueue code now exposes edacApiUrl, restUrl, and fixesRestUrl; frontend JS reads those globals to build POST endpoints for scan results, clearing issues, and saving fix settings. Tests added to validate the localized URLs.

Changes

Dynamic REST URL Configuration

Layer / File(s) Summary
Admin REST URL Localization
admin/class-enqueue-admin.php, tests/phpunit/Admin/EnqueueAdminTest.php
Admin enqueue now passes edacApiUrl and fixesRestUrl via rest_url() to the admin bundle. Four new tests validate fixesRestUrl is present, contains edac/v1, is absolute, and respects custom REST base prefix filters.
Frontend Highlighter REST URL Localization
includes/classes/class-enqueue-frontend.php, tests/phpunit/includes/classes/EnqueueFrontendTest.php
Frontend enqueue adds restUrl (for accessibility-checker/v1) and fixesRestUrl (for edac/v1) to the frontend app localization. Eight new tests verify both URLs are present, namespaced correctly, absolute, and respect custom REST prefix filters; a helper method enqueues and extracts the localized data for assertions.
Fix Settings REST Endpoint
src/common/saveFixSettingsRest.js
saveFixSettings dynamically builds the REST endpoint from window.edacFrontendHighlighterApp?.fixesRestUrl with fallback to window.edac_script_vars?.fixesRestUrl, replacing the hardcoded /wp-json/edac/v1 path and handling a missing-URL early return.
Scan Results and Issue Management REST Endpoints
src/frontendHighlighterApp/index.js
saveScanResults and clearIssues now construct POST URLs from edacFrontendHighlighterApp.restUrl instead of hardcoded paths; validation for clearIssues requires restUrl presence.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

codex

Poem

🐰 A rabbit's note on routed springs
No more hard paths in brittle strings,
PHP speaks URLs to JS ears,
Frontend posts now guided, clear,
Hopping endpoints, joyful things.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: passing REST API URLs dynamically to support subsites and custom REST bases instead of using hardcoded paths.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch william/no-issue/fix-subsite-multisite-saving-from-frontend-and-full-site-scanner

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request replaces hardcoded REST API paths with dynamically localized URLs (fixesRestUrl and restUrl) in both admin and frontend scripts, and adds comprehensive PHPUnit tests to verify their behavior. Feedback on these changes focuses on improving robustness: it is recommended to add guard clauses to prevent broken network requests if the localized URLs are undefined, and to access global variables via the window object to avoid potential runtime ReferenceError exceptions.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +44 to +47
const fixesRestUrl = window.edacFrontendHighlighterApp?.fixesRestUrl ?? window.edac_script_vars?.fixesRestUrl;

// make a rest call to save the settings
fetch( '/wp-json/edac/v1/fixes/update/', {
fetch( `${ fixesRestUrl }/fixes/update/`, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If fixesRestUrl is undefined or null (for example, if the script is loaded in a context where the localized variables are missing), the fetch call will attempt to request a relative URL starting with undefined/fixes/update/. Adding a guard clause to handle this scenario gracefully prevents broken network requests and improves robustness.

	const fixesRestUrl = window.edacFrontendHighlighterApp?.fixesRestUrl ?? window.edac_script_vars?.fixesRestUrl;

	if ( ! fixesRestUrl ) {
		fixSettingsContainer.classList.remove( 'edac-fix-settings--saving' );
		fixButtons.forEach( ( button ) => {
			button.disabled = false;
		} );
		fixSettingsContainer.classList.add( 'edac-fix-settings--saved--error' );
		if ( liveRegion ) {
			liveRegion.innerText = __( 'Saving failed: Missing REST API URL.', 'accessibility-checker' );
		}
		return;
	}

	// make a rest call to save the settings
	fetch( fixesRestUrl + '/fixes/update/', {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ce8674d — added guard clause / switched to window. prefix throughout.

Comment thread src/frontendHighlighterApp/index.js Outdated
saveScanResults( postId, nonce, violations, densityMetrics ) {
const self = this;
return fetch( '/wp-json/accessibility-checker/v1/post-scan-results/' + postId, {
return fetch( `${ edacFrontendHighlighterApp.restUrl }/post-scan-results/${ postId }`, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If window.edacFrontendHighlighterApp is defined but restUrl is missing or undefined, the fetch call will attempt to request a relative URL starting with undefined/post-scan-results/.... Adding a check to ensure restUrl is present before making the API call prevents broken network requests.

		const restUrl = window.edacFrontendHighlighterApp?.restUrl;
		if ( ! restUrl ) {
			return Promise.reject( new Error( 'Missing REST API URL.' ) );
		}
		return fetch( restUrl + '/post-scan-results/' + postId, {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ce8674d — added guard clause / switched to window. prefix throughout.

Comment thread src/frontendHighlighterApp/index.js Outdated

// Validate required parameters
if ( ! edacFrontendHighlighterApp?.edacUrl || ! edacFrontendHighlighterApp?.postID ) {
if ( ! edacFrontendHighlighterApp?.restUrl || ! edacFrontendHighlighterApp?.postID ) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Accessing edacFrontendHighlighterApp directly can throw a ReferenceError at runtime if the variable is completely undeclared (e.g., if the script is loaded in a context where the localization didn't run). Accessing it via window.edacFrontendHighlighterApp is safer as it will evaluate to undefined instead of throwing an error.

Suggested change
if ( ! edacFrontendHighlighterApp?.restUrl || ! edacFrontendHighlighterApp?.postID ) {
if ( ! window.edacFrontendHighlighterApp?.restUrl || ! window.edacFrontendHighlighterApp?.postID ) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ce8674d — added guard clause / switched to window. prefix throughout.

Comment thread src/frontendHighlighterApp/index.js Outdated
const summary = document.querySelector( '.edac-highlight-panel-controls-summary' );

fetch( `${ edacFrontendHighlighterApp.edacUrl }/wp-json/accessibility-checker/v1/clear-issues/${ edacFrontendHighlighterApp.postID }`, {
fetch( `${ edacFrontendHighlighterApp.restUrl }/clear-issues/${ edacFrontendHighlighterApp.postID }`, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For safety and consistency, access the localized variables via window.edacFrontendHighlighterApp to avoid potential ReferenceError at runtime.

Suggested change
fetch( `${ edacFrontendHighlighterApp.restUrl }/clear-issues/${ edacFrontendHighlighterApp.postID }`, {
fetch( window.edacFrontendHighlighterApp.restUrl + '/clear-issues/' + window.edacFrontendHighlighterApp.postID, {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ce8674d — added guard clause / switched to window. prefix throughout.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
admin/class-enqueue-admin.php (1)

139-139: ⚡ Quick win

Consider updating the editor app localization for consistency.

Line 139 still uses the old concatenation pattern (rest_url() . 'accessibility-checker/v1') while the main admin script now uses the direct rest_url('accessibility-checker/v1') pattern. For consistency and to ensure the editor app also benefits from proper multisite/custom REST base support, consider updating this line to match the new pattern.

Suggested refactor
-'edacApiUrl'   => esc_url_raw( rest_url() . 'accessibility-checker/v1' ),
+'edacApiUrl'   => esc_url_raw( rest_url( 'accessibility-checker/v1' ) ),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@admin/class-enqueue-admin.php` at line 139, Update the editor app
localization entry for 'edacApiUrl' to use the REST helper with a path argument
rather than string concatenation: replace the esc_url_raw( rest_url() .
'accessibility-checker/v1' ) pattern with esc_url_raw(
rest_url('accessibility-checker/v1') ) so the 'edacApiUrl' uses multisite/custom
REST base-aware URL generation (locate the 'edacApiUrl' array entry in
admin/class-enqueue-admin.php).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@admin/class-enqueue-admin.php`:
- Line 139: Update the editor app localization entry for 'edacApiUrl' to use the
REST helper with a path argument rather than string concatenation: replace the
esc_url_raw( rest_url() . 'accessibility-checker/v1' ) pattern with esc_url_raw(
rest_url('accessibility-checker/v1') ) so the 'edacApiUrl' uses multisite/custom
REST base-aware URL generation (locate the 'edacApiUrl' array entry in
admin/class-enqueue-admin.php).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: be7c0d1c-844f-4c51-932b-28c29b9e6c53

📥 Commits

Reviewing files that changed from the base of the PR and between 0f29712 and 08d4a7e.

📒 Files selected for processing (6)
  • admin/class-enqueue-admin.php
  • includes/classes/class-enqueue-frontend.php
  • src/common/saveFixSettingsRest.js
  • src/frontendHighlighterApp/index.js
  • tests/phpunit/Admin/EnqueueAdminTest.php
  • tests/phpunit/includes/classes/EnqueueFrontendTest.php

…ently

Add guard clause to saveFixSettings() so that if fixesRestUrl resolves
to undefined (script loaded outside a context where localisation ran),
the function exits cleanly with a user-visible error message instead of
sending a fetch to `undefined/fixes/update/`.

Add equivalent guard to saveScanResults() returning a rejected Promise
when restUrl is missing, matching the existing guard pattern in
clearIssues().

Prefix all edacFrontendHighlighterApp accesses in clearIssues() and
the new saveScanResults() guard with `window.` to avoid a ReferenceError
if the global is completely undeclared rather than merely undefined.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@pattonwebz

Copy link
Copy Markdown
Member Author

Addressed the Gemini Code Assist review findings in commit ce8674d:

  • saveFixSettingsRest.js — Added guard clause: if fixesRestUrl resolves to undefined, the function exits cleanly with a visible error message instead of sending a fetch to undefined/fixes/update/.
  • index.js saveScanResults — Added guard returning a rejected Promise when restUrl is missing, consistent with the existing guard in clearIssues.
  • index.js clearIssues guard (line 1946) — Switched edacFrontendHighlighterApp?.restUrlwindow.edacFrontendHighlighterApp?.restUrl to avoid a ReferenceError if the global is completely undeclared.
  • index.js clearIssues fetch (line 1959) — Same window. prefix applied to both property accesses for consistency.

@pattonwebz

Copy link
Copy Markdown
Member Author

Addressed the Gemini Code Assist review findings in commit ce8674d:

  • saveFixSettingsRest.js — Added guard clause: if fixesRestUrl resolves to undefined, the function exits cleanly with a visible error message instead of sending a fetch to undefined/fixes/update/.
  • index.js saveScanResults — Added guard returning a rejected Promise when restUrl is missing, consistent with the existing guard in clearIssues.
  • index.js clearIssues guard (line 1946) — Switched bare edacFrontendHighlighterAppwindow.edacFrontendHighlighterApp to avoid a ReferenceError if the global is completely undeclared.
  • index.js clearIssues fetch (line 1959) — Same window. prefix applied for consistency.

@pattonwebz

Copy link
Copy Markdown
Member Author

CodeRabbit review complete — no inline findings. All 5 pre-merge checks passed. The JS files were skipped as similar to previous changes; the PHP enqueue and test files passed cleanly.

@pattonwebz
pattonwebz merged commit 56a7fbc into develop Jun 22, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant