v1.5.1: frontend auth hardening — rate limiting, email verification, honeypots, CSV safety

Security-only release per ADR-0001. Closes all six ship-blockers from the
post-v1.5.0 audit: PSEC-001 (no rate limiting), PSEC-002 (account
enumeration via separate error messages), PSEC-003 (registration auto-login
with no email verification), PSEC-004 (ungated "My Data" templates),
PSEC-005 (CSV formula injection on subscriber export), PSEC-006 (no
honeypot/CAPTCHA on public forms).

Adds inc/config.php (single source of truth for all security thresholds,
filterable via peptide_starter_security_config), inc/rate-limiter.php
(Peptide_Starter_Rate_Limiter + Cloudflare-aware client IP resolver,
transient-backed, never stores raw IPs), and inc/email-verification.php
(43-char token, 24h TTL, /verify rewrite, rate-limited resend endpoint).

Auth handlers rewritten to: unify all failure messages, rate-limit before
any expensive check, drop registrations with a filled honeypot silently,
stop auto-login on register, send a verification email instead. The
require_login() helper lives in inc/helpers.php and is applied at the top
of page-tracker.php, page-subject-log.php, and page-protocol-builder.php;
page-calculator.php stays open (no PII, no writes).

Newsletter signup gains: consent checkbox, privacy link, honeypot,
autoload=false on the wp_options blob, unsubscribe token stored per row,
/newsletter-unsubscribe route, merged success+duplicate into a single "ok"
state. Admin export runs every cell through peptide_starter_csv_safe()
which prefixes leading =/+/-/@/tab/CR with a quote.

Contact handler hardens against email-header injection (rejects name
values with \r \n , < >), rate-limits, honors honeypot, tags mail
failures with a request ID for correlation without logging message
content.

Adds Tools → Mail Test (inc/mail-diagnostic.php): a permanent wp_mail
probe so we can check Hostinger outbound deliverability any time it looks
flaky. Adds a one-time admin_init migration that enrols pre-v1.5.1
subscribers into the verification flow (currently a no-op — zero users —
but guarded for the future).

Other cleanup from the audit: fallback primary menu moved out of
header.php into inc/helpers.php (redeclaration risk), placeholder footer
language links replaced with "Translations coming soon", footer copyright
now reads through the customizer getter, settings-panel gains a proper
Tab/Shift+Tab focus trap and saves/restores body overflow, documentation
heading IDs slugified from heading text with collision counters, JS files
standardized on const/let.

Six new PHPUnit suites cover rate limiter lifecycle, auth handler error
unification and rate limits, email verification token generation and
expiry, contact handler header injection + rate limit + honeypot,
newsletter signup consent + CSV safety, and require_login gate behavior.

ARCHITECTURE.md and CONVENTIONS.md updated in the same commit — new
module layout, data flows, security patterns for rate-limiting,
honeypotting, gating, and CSV-safe export.

Version bumped to 1.5.1 in style.css and functions.php.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
peptiderepo
2026-04-14 13:01:22 +07:00
parent d28d5f45d5
commit cb8b73f4ab
34 changed files with 2816 additions and 745 deletions

View File

@@ -1,36 +1,37 @@
/**
* Authentication Page — Form Toggle & Validation
* Authentication Page — Form Toggle & AJAX
* Peptide Starter Theme
*
* Handles:
* - Toggle between sign-in and register forms
* - Client-side form validation
* - Password strength indicator
* - AJAX form submission to avoid full page reload
* - AJAX form submission (no redirect on register — success message only)
* - XSS-safe message rendering
*
* @see page-auth.php — renders the auth forms
* @see functions.php — AJAX handlers (ps_auth_login, ps_auth_register)
* @see page-auth.php — renders the forms
* @see inc/auth-handlers.php — ps_auth_login / ps_auth_register
*
* Conditionally enqueued only on pages using the Sign In / Register template.
* Conditionally enqueued on pages using the Sign In / Register template.
*/
(function() {
(function () {
'use strict';
var loginWrap = document.getElementById('ps-auth-login');
var registerWrap = document.getElementById('ps-auth-register');
var showRegister = document.getElementById('ps-show-register');
var showLogin = document.getElementById('ps-show-login');
var messages = document.getElementById('ps-auth-messages');
var loginForm = document.getElementById('ps-login-form');
var registerForm = document.getElementById('ps-register-form');
const loginWrap = document.getElementById('ps-auth-login');
const registerWrap = document.getElementById('ps-auth-register');
const showRegister = document.getElementById('ps-show-register');
const showLogin = document.getElementById('ps-show-login');
const messages = document.getElementById('ps-auth-messages');
const loginForm = document.getElementById('ps-login-form');
const registerForm = document.getElementById('ps-register-form');
if (!loginWrap || !registerWrap) {
return;
}
/**
* Toggle between login and register views.
* Swap which form is visible. Uses a class, not inline style, so the
* stylesheet is the single source of truth.
* @param {string} view - 'login' or 'register'.
*/
function showView(view) {
@@ -45,121 +46,128 @@
}
if (showRegister) {
showRegister.addEventListener('click', function(e) {
showRegister.addEventListener('click', function (e) {
e.preventDefault();
showView('register');
});
}
if (showLogin) {
showLogin.addEventListener('click', function(e) {
showLogin.addEventListener('click', function (e) {
e.preventDefault();
showView('login');
});
}
// Check URL hash on load for deep linking.
if (window.location.hash === '#register') {
showView('register');
}
/**
* Display a message in the auth messages area.
* @param {string} text - Message text.
* @param {string} type - 'success', 'error', or 'info'.
* Render a message in the messages region. Text is escaped.
* @param {string} text
* @param {string} type - 'success' | 'error' | 'info'.
*/
function showMessage(text, type) {
if (!messages) {
return;
}
var alertClass = 'ps-alert ps-alert-' + (type || 'info');
messages.innerHTML = '<div class="' + alertClass + '"><p>' + escapeHtml(text) + '</p></div>';
if (!messages) return;
const wrap = document.createElement('div');
wrap.className = 'ps-alert ps-alert-' + (type || 'info');
const p = document.createElement('p');
p.textContent = text;
wrap.appendChild(p);
messages.innerHTML = '';
messages.appendChild(wrap);
}
function clearMessages() {
if (messages) {
messages.innerHTML = '';
}
if (messages) { messages.innerHTML = ''; }
}
/**
* Escape HTML entities to prevent XSS in message display.
* @param {string} str - Raw string.
* @returns {string} Escaped string.
*/
function escapeHtml(str) {
var div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
/**
* Password strength indicator.
* Updates the #ps-password-strength element with a rating.
*/
var passwordInput = document.getElementById('ps-reg-password');
var strengthEl = document.getElementById('ps-password-strength');
// Password strength indicator (registration form).
const passwordInput = document.getElementById('ps-reg-password');
const strengthEl = document.getElementById('ps-password-strength');
if (passwordInput && strengthEl) {
passwordInput.addEventListener('input', function() {
var val = passwordInput.value;
var score = 0;
var label = '';
passwordInput.addEventListener('input', function () {
const val = passwordInput.value;
let score = 0;
if (val.length >= 8) { score++; }
if (val.length >= 12) { score++; }
if (/[a-z]/.test(val) && /[A-Z]/.test(val)) { score++; }
if (/\d/.test(val)) { score++; }
if (/[^a-zA-Z0-9]/.test(val)) { score++; }
if (val.length >= 8) { score++; }
if (val.length >= 12) { score++; }
if (/[a-z]/.test(val) && /[A-Z]/.test(val)) { score++; }
if (/\d/.test(val)) { score++; }
if (/[^a-zA-Z0-9]/.test(val)) { score++; }
if (val.length === 0) {
label = '';
} else if (score <= 1) {
label = '<span class="ps-strength-weak">Weak</span>';
} else if (score <= 3) {
label = '<span class="ps-strength-fair">Fair</span>';
} else {
label = '<span class="ps-strength-strong">Strong</span>';
let className = '';
let label = '';
if (val.length === 0) { className = ''; }
else if (score <= 1) { className = 'ps-strength-weak'; label = 'Weak'; }
else if (score <= 3) { className = 'ps-strength-fair'; label = 'Fair'; }
else { className = 'ps-strength-strong'; label = 'Strong'; }
strengthEl.innerHTML = '';
if (className) {
const span = document.createElement('span');
span.className = className;
span.textContent = label;
strengthEl.appendChild(span);
}
strengthEl.innerHTML = label;
});
}
/**
* AJAX form submission handler.
* @param {HTMLFormElement} form - The form to submit.
* Submit a form via AJAX to admin-ajax. Login success redirects; register
* success shows an inbox-check message (no redirect — email verification
* is the next step).
* @param {HTMLFormElement} form
* @param {string} kind - 'login' or 'register'.
*/
function submitForm(form) {
var formData = new FormData(form);
var btn = form.querySelector('button[type="submit"]');
var origText = btn.textContent;
function submitForm(form, kind) {
const formData = new FormData(form);
const btn = form.querySelector('button[type="submit"]');
const origText = btn.textContent;
btn.disabled = true;
btn.textContent = '...';
clearMessages();
var xhr = new XMLHttpRequest();
xhr.open('POST', (typeof peptideStarterData !== 'undefined' ? peptideStarterData.ajaxUrl : '/wp-admin/admin-ajax.php'));
const xhr = new XMLHttpRequest();
const url = (typeof window.peptideStarterData !== 'undefined' && window.peptideStarterData.ajaxUrl)
? window.peptideStarterData.ajaxUrl
: '/wp-admin/admin-ajax.php';
xhr.open('POST', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function() {
xhr.onload = function () {
btn.disabled = false;
btn.textContent = origText;
try {
var resp = JSON.parse(xhr.responseText);
if (resp.success && resp.data && resp.data.redirect) {
window.location.href = resp.data.redirect;
} else {
showMessage(resp.data && resp.data.message ? resp.data.message : 'An error occurred.', 'error');
}
} catch (e) {
let resp;
try { resp = JSON.parse(xhr.responseText); } catch (e) {
showMessage('An unexpected error occurred. Please try again.', 'error');
return;
}
if (resp && resp.success) {
if (kind === 'login' && resp.data && resp.data.redirect) {
window.location.href = resp.data.redirect;
return;
}
if (kind === 'register' && resp.data && resp.data.message) {
showMessage(resp.data.message, 'success');
form.reset();
if (strengthEl) { strengthEl.innerHTML = ''; }
return;
}
showMessage('Request completed.', 'success');
return;
}
const msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'An error occurred.';
showMessage(msg, 'error');
};
xhr.onerror = function() {
xhr.onerror = function () {
btn.disabled = false;
btn.textContent = origText;
showMessage('Network error. Please check your connection.', 'error');
@@ -169,24 +177,29 @@
}
if (loginForm) {
loginForm.addEventListener('submit', function(e) {
loginForm.addEventListener('submit', function (e) {
e.preventDefault();
if (!loginForm.checkValidity()) {
loginForm.reportValidity();
return;
}
submitForm(loginForm);
submitForm(loginForm, 'login');
});
}
if (registerForm) {
registerForm.addEventListener('submit', function(e) {
registerForm.addEventListener('submit', function (e) {
e.preventDefault();
if (!registerForm.checkValidity()) {
registerForm.reportValidity();
return;
}
submitForm(registerForm);
submitForm(registerForm, 'register');
});
}
// Surface /auth?verify_error=1.
if (messages && /[?&]verify_error=1/.test(window.location.search)) {
showMessage('That verification link is invalid or has expired. Sign in and request a new one.', 'error');
}
})();

View File

@@ -3,23 +3,22 @@
* Peptide Starter Theme
*
* Handles:
* - Auto-generates ToC from h2 headings in the documentation body
* - Scroll spy highlights the active section in the sidebar
* - Smooth scrolling on ToC link click
* - Auto-generates ToC from h2 headings
* - Slugifies heading IDs from the heading text (with collision counter)
* so deep links survive edits that change the author's order
* - IntersectionObserver scroll spy highlights the active section
* - Smooth scroll with header offset on ToC click
* - Collapses sidebar to dropdown on mobile
*
* @see page-documentation.php — renders the two-column layout
* @see style.css — .ps-docs-* classes
*
* Conditionally enqueued only on pages using the Documentation template.
*/
(function() {
(function () {
'use strict';
const docsBody = document.getElementById('ps-docs-body');
const tocList = document.getElementById('ps-docs-toc-list');
const sidebar = document.querySelector('.ps-docs-sidebar');
const docsBody = document.getElementById('ps-docs-body');
const tocList = document.getElementById('ps-docs-toc-list');
const sidebar = document.querySelector('.ps-docs-sidebar');
if (!docsBody || !tocList) {
return;
@@ -28,32 +27,51 @@
const headings = docsBody.querySelectorAll('h2');
if (headings.length === 0) {
// Hide the sidebar if there are no headings to navigate.
if (sidebar) {
sidebar.style.display = 'none';
}
if (sidebar) { sidebar.style.display = 'none'; }
return;
}
/**
* Build the Table of Contents from h2 headings.
* Assigns IDs to headings that lack one for anchor linking.
* Deterministic slug derived from heading text. Collisions resolved
* with a numeric suffix so every h2 gets a unique ID even when authors
* repeat titles ("Examples", "Examples", ...).
* @param {string} text
* @returns {string}
*/
function slugify(text) {
return String(text)
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '') || 'section';
}
function buildToc() {
headings.forEach(function(heading, index) {
// Ensure every heading has an ID for anchor links.
const used = Object.create(null);
headings.forEach(function (heading) {
if (!heading.id) {
heading.id = 'section-' + (index + 1);
let base = slugify(heading.textContent || '');
let slug = base;
let n = 2;
while (document.getElementById(slug) || used[slug]) {
slug = base + '-' + n;
n++;
}
heading.id = slug;
used[slug] = true;
}
var li = document.createElement('li');
var link = document.createElement('a');
const li = document.createElement('li');
const link = document.createElement('a');
link.href = '#' + heading.id;
link.textContent = heading.textContent;
link.className = 'ps-docs-toc-link';
link.addEventListener('click', function(e) {
link.addEventListener('click', function (e) {
e.preventDefault();
smoothScrollTo(heading);
});
@@ -63,82 +81,53 @@
});
}
/**
* Smooth scroll to a target element, accounting for the sticky header.
* @param {HTMLElement} target The element to scroll to.
*/
function smoothScrollTo(target) {
var headerHeight = document.querySelector('.site-header')
? document.querySelector('.site-header').offsetHeight
: 0;
var offset = 24; // Extra breathing room below header.
var top = target.getBoundingClientRect().top + window.pageYOffset - headerHeight - offset;
const headerEl = document.querySelector('.site-header');
const headerHeight = headerEl ? headerEl.offsetHeight : 0;
const offset = 24;
const top = target.getBoundingClientRect().top + window.pageYOffset - headerHeight - offset;
window.scrollTo({
top: top,
behavior: 'smooth'
});
// Update URL hash without jumping.
window.scrollTo({ top: top, behavior: 'smooth' });
history.replaceState(null, '', '#' + target.id);
}
/**
* Scroll spy — highlights the ToC link corresponding to the
* currently visible section. Uses IntersectionObserver for performance.
*/
function initScrollSpy() {
var tocLinks = tocList.querySelectorAll('.ps-docs-toc-link');
const tocLinks = tocList.querySelectorAll('.ps-docs-toc-link');
if (tocLinks.length === 0) return;
if (tocLinks.length === 0) {
return;
}
const headerEl = document.querySelector('.site-header');
const headerHeight = headerEl ? headerEl.offsetHeight : 0;
var headerHeight = document.querySelector('.site-header')
? document.querySelector('.site-header').offsetHeight
: 0;
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var id = entry.target.id;
tocLinks.forEach(function(link) {
link.classList.remove('ps-docs-toc-link--active');
if (link.getAttribute('href') === '#' + id) {
link.classList.add('ps-docs-toc-link--active');
}
});
}
const observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (!entry.isIntersecting) return;
const id = entry.target.id;
tocLinks.forEach(function (link) {
link.classList.remove('ps-docs-toc-link--active');
if (link.getAttribute('href') === '#' + id) {
link.classList.add('ps-docs-toc-link--active');
}
});
});
}, {
rootMargin: '-' + (headerHeight + 32) + 'px 0px -60% 0px',
threshold: 0
});
headings.forEach(function(heading) {
observer.observe(heading);
});
headings.forEach(function (heading) { observer.observe(heading); });
}
/**
* Mobile dropdown toggle for the sidebar ToC.
*/
function initMobileToggle() {
var tocTitle = document.querySelector('.ps-docs-toc-title');
const tocTitle = document.querySelector('.ps-docs-toc-title');
if (!tocTitle || !sidebar) return;
if (!tocTitle) {
return;
}
tocTitle.addEventListener('click', function() {
// Only toggle on mobile (sidebar is not sticky).
tocTitle.addEventListener('click', function () {
if (window.innerWidth < 1024) {
sidebar.classList.toggle('ps-docs-sidebar--open');
}
});
}
// Initialize.
buildToc();
initScrollSpy();
initMobileToggle();

View File

@@ -1,84 +1,66 @@
/**
* Navigation and Mobile Menu Toggle
* Peptide Starter Theme
*
* Handles:
* - Mobile hamburger menu toggle
* - Navigation overlay click handling
* - Menu state persistence
*/
(function() {
'use strict';
const menuToggle = document.querySelector('.menu-toggle');
const primaryNav = document.querySelector('.primary-navigation');
const navOverlay = document.querySelector('.nav-overlay');
if (!menuToggle || !primaryNav || !navOverlay) {
return;
}
/**
* Toggle mobile menu visibility
*/
function toggleMenu() {
const isActive = primaryNav.classList.contains('active');
if (isActive) {
closeMenu();
} else {
openMenu();
}
}
/**
* Open mobile menu
*/
function openMenu() {
primaryNav.classList.add('active');
navOverlay.classList.add('active');
document.body.style.overflow = 'hidden';
menuToggle.setAttribute('aria-expanded', 'true');
}
/**
* Close mobile menu
*/
function closeMenu() {
primaryNav.classList.remove('active');
navOverlay.classList.remove('active');
document.body.style.overflow = '';
menuToggle.setAttribute('aria-expanded', 'false');
}
// Menu toggle button click
menuToggle.addEventListener('click', toggleMenu);
// Overlay click
navOverlay.addEventListener('click', closeMenu);
// Close menu when a nav link is clicked
const navLinks = primaryNav.querySelectorAll('a');
navLinks.forEach(link => {
link.addEventListener('click', closeMenu);
});
// Close menu on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeMenu();
}
});
// Set initial aria-expanded state
menuToggle.setAttribute('aria-expanded', 'false');
// Close menu when window is resized above mobile breakpoint
const mediaQuery = window.matchMedia('(min-width: 768px)');
mediaQuery.addEventListener('change', (e) => {
if (e.matches) {
closeMenu();
}
});
})();
/**
* Navigation and Mobile Menu Toggle
* Peptide Starter Theme
*
* Handles:
* - Mobile hamburger menu toggle
* - Navigation overlay click handling
* - Menu state persistence
*/
(function () {
'use strict';
const menuToggle = document.querySelector('.menu-toggle');
const primaryNav = document.querySelector('.primary-navigation');
const navOverlay = document.querySelector('.nav-overlay');
if (!menuToggle || !primaryNav || !navOverlay) {
return;
}
let previousOverflow = '';
function openMenu() {
primaryNav.classList.add('active');
navOverlay.classList.add('active');
previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
menuToggle.setAttribute('aria-expanded', 'true');
}
function closeMenu() {
primaryNav.classList.remove('active');
navOverlay.classList.remove('active');
document.body.style.overflow = previousOverflow;
previousOverflow = '';
menuToggle.setAttribute('aria-expanded', 'false');
}
function toggleMenu() {
if (primaryNav.classList.contains('active')) {
closeMenu();
} else {
openMenu();
}
}
menuToggle.addEventListener('click', toggleMenu);
navOverlay.addEventListener('click', closeMenu);
const navLinks = primaryNav.querySelectorAll('a');
navLinks.forEach(function (link) {
link.addEventListener('click', closeMenu);
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') { closeMenu(); }
});
menuToggle.setAttribute('aria-expanded', 'false');
const mediaQuery = window.matchMedia('(min-width: 768px)');
mediaQuery.addEventListener('change', function (e) {
if (e.matches) { closeMenu(); }
});
})();

View File

@@ -1,163 +1,164 @@
/**
* Settings Panel — Open/Close & Contact Form
* Settings Panel — Open/Close, Focus Trap, Contact Form AJAX
* Peptide Starter Theme
*
* Handles:
* - Toggle settings slide-out panel visibility
* - AJAX submission of the contact form
* - Overlay backdrop click to close
* - Escape key to close
* - Focus trap inside the panel for accessibility
* - Open / close the slide-out panel (button, overlay click, Escape)
* - Save and restore document.body.style.overflow so other panels
* opening the overlay don't stomp on the caller's original value
* - Focus trap: Tab / Shift+Tab wrap within the panel while it's open
* - AJAX submission of the contact form with XSS-safe status rendering
*
* @see template-parts/settings-panel.php — panel HTML
* @see header.php — settings icon trigger button
* @see functions.php — AJAX handler for contact form
*
* Enqueued globally (lightweight — all listeners are passive until panel opens).
* @see header.php — trigger button
* @see inc/contact-handler.php — AJAX endpoint
*/
(function() {
(function () {
'use strict';
var panel = document.getElementById('ps-settings-panel');
var overlay = document.getElementById('ps-settings-overlay');
var closeBtn = document.getElementById('ps-settings-close');
var openBtn = document.getElementById('ps-settings-toggle');
var contactForm = document.getElementById('ps-contact-form');
var statusEl = document.getElementById('ps-contact-status');
const panel = document.getElementById('ps-settings-panel');
const overlay = document.getElementById('ps-settings-overlay');
const closeBtn = document.getElementById('ps-settings-close');
const openBtn = document.getElementById('ps-settings-toggle');
const contactForm = document.getElementById('ps-contact-form');
const statusEl = document.getElementById('ps-contact-status');
if (!panel || !overlay) {
return;
}
const FOCUSABLE = 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
let previousOverflow = '';
let firstFocusable = null;
let lastFocusable = null;
/**
* Open the settings panel.
* Snapshot and refresh the focusable boundary elements inside the panel.
* Called on open so dynamically-rendered fields are included.
*/
function refreshFocusables() {
const list = panel.querySelectorAll(FOCUSABLE);
if (!list.length) {
firstFocusable = null;
lastFocusable = null;
return;
}
firstFocusable = list[0];
lastFocusable = list[list.length - 1];
}
function openPanel() {
panel.classList.add('ps-settings-panel--open');
panel.setAttribute('aria-hidden', 'false');
overlay.classList.add('ps-settings-overlay--active');
overlay.setAttribute('aria-hidden', 'false');
previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
// Focus the close button for keyboard users.
refreshFocusables();
if (closeBtn) {
setTimeout(function() { closeBtn.focus(); }, 100);
setTimeout(function () { closeBtn.focus(); }, 100);
}
}
/**
* Close the settings panel.
*/
function closePanel() {
panel.classList.remove('ps-settings-panel--open');
panel.setAttribute('aria-hidden', 'true');
overlay.classList.remove('ps-settings-overlay--active');
overlay.setAttribute('aria-hidden', 'true');
document.body.style.overflow = '';
document.body.style.overflow = previousOverflow;
previousOverflow = '';
// Return focus to the trigger button.
if (openBtn) {
openBtn.focus();
}
}
// Bind open trigger.
if (openBtn) {
openBtn.addEventListener('click', openPanel);
function trapFocus(e) {
if (!panel.classList.contains('ps-settings-panel--open')) return;
if (e.key !== 'Tab') return;
if (!firstFocusable || !lastFocusable) return;
if (e.shiftKey && document.activeElement === firstFocusable) {
e.preventDefault();
lastFocusable.focus();
} else if (!e.shiftKey && document.activeElement === lastFocusable) {
e.preventDefault();
firstFocusable.focus();
}
}
// Bind close button.
if (closeBtn) {
closeBtn.addEventListener('click', closePanel);
}
// Bind overlay backdrop click.
if (openBtn) { openBtn.addEventListener('click', openPanel); }
if (closeBtn) { closeBtn.addEventListener('click', closePanel); }
overlay.addEventListener('click', closePanel);
// Close on Escape key.
document.addEventListener('keydown', function(e) {
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && panel.classList.contains('ps-settings-panel--open')) {
closePanel();
}
});
document.addEventListener('keydown', trapFocus);
/**
* Contact form AJAX submission.
*/
// Contact form AJAX.
if (contactForm) {
contactForm.addEventListener('submit', function(e) {
contactForm.addEventListener('submit', function (e) {
e.preventDefault();
if (!contactForm.checkValidity()) {
contactForm.reportValidity();
return;
}
var formData = new FormData(contactForm);
var btn = contactForm.querySelector('button[type="submit"]');
var origText = btn.textContent;
const formData = new FormData(contactForm);
const btn = contactForm.querySelector('button[type="submit"]');
const origText = btn.textContent;
btn.disabled = true;
btn.textContent = '...';
if (statusEl) { statusEl.innerHTML = ''; }
if (statusEl) {
statusEl.innerHTML = '';
}
var xhr = new XMLHttpRequest();
var ajaxUrl = (typeof peptideStarterData !== 'undefined' && peptideStarterData.ajaxUrl)
? peptideStarterData.ajaxUrl
const xhr = new XMLHttpRequest();
const url = (typeof window.peptideStarterData !== 'undefined' && window.peptideStarterData.ajaxUrl)
? window.peptideStarterData.ajaxUrl
: '/wp-admin/admin-ajax.php';
xhr.open('POST', ajaxUrl);
xhr.open('POST', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function() {
xhr.onload = function () {
btn.disabled = false;
btn.textContent = origText;
try {
var resp = JSON.parse(xhr.responseText);
if (resp.success) {
if (statusEl) {
statusEl.innerHTML = '<div class="ps-alert ps-alert-success"><p>' +
escapeHtml(resp.data.message || 'Message sent.') + '</p></div>';
}
contactForm.reset();
} else {
if (statusEl) {
statusEl.innerHTML = '<div class="ps-alert ps-alert-error"><p>' +
escapeHtml(resp.data.message || 'Failed to send.') + '</p></div>';
}
}
} catch (ex) {
if (statusEl) {
statusEl.innerHTML = '<div class="ps-alert ps-alert-error"><p>An unexpected error occurred.</p></div>';
}
let resp;
try { resp = JSON.parse(xhr.responseText); } catch (ex) {
renderStatus('An unexpected error occurred.', 'error');
return;
}
if (resp && resp.success) {
renderStatus((resp.data && resp.data.message) || 'Message sent.', 'success');
contactForm.reset();
} else {
renderStatus((resp && resp.data && resp.data.message) || 'Failed to send.', 'error');
}
};
xhr.onerror = function() {
xhr.onerror = function () {
btn.disabled = false;
btn.textContent = origText;
if (statusEl) {
statusEl.innerHTML = '<div class="ps-alert ps-alert-error"><p>Network error. Please try again.</p></div>';
}
renderStatus('Network error. Please try again.', 'error');
};
xhr.send(formData);
});
}
/**
* Escape HTML for safe insertion.
* @param {string} str - Raw text.
* @returns {string} Escaped HTML.
*/
function escapeHtml(str) {
var div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
function renderStatus(text, type) {
if (!statusEl) return;
const wrap = document.createElement('div');
wrap.className = 'ps-alert ps-alert-' + (type || 'info');
const p = document.createElement('p');
p.textContent = text;
wrap.appendChild(p);
statusEl.innerHTML = '';
statusEl.appendChild(wrap);
}
})();