Update package-lock.json and enhance Form component for better error handling and user experience

- Changed "dev" to "devOptional" for several dependencies in package-lock.json to reflect updated package configurations.
- Improved the Form component by refining error handling during form submission, including specific messages for different error scenarios.
- Enhanced the spam detection logic and added clearer feedback for users during the manual review process.
- Updated the CSRF token handling to ensure it is set correctly upon form submission.
This commit is contained in:
2025-11-02 00:29:19 +01:00
parent 8773788335
commit 84a5e71b95
3 changed files with 92 additions and 34 deletions

View File

@@ -84,12 +84,12 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
{
disclaimer && (
<div class="mt-3 flex items-start mb-6">
<div class="flex mt-0.5">
<div class="flex items-center h-5">
<input
id="disclaimer"
name="disclaimer"
type="checkbox"
class="cursor-pointer mt-1 py-3 px-4 block w-full text-md rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-slate-900"
class="w-4 h-4 cursor-pointer rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 dark:bg-slate-700 dark:checked:bg-blue-600"
required
aria-describedby="invalid-feedback-disclaimer"
/>
@@ -163,13 +163,10 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
<div id="manual-review-result" class="mt-4 text-center text-green-700 dark:text-green-400 font-medium"></div>
</div>
<script>
// TypeScript: declare the property on window
declare global {
interface Window {
__originalEmail?: string;
}
}
<script define:vars={{ spamReviewConfig: spamReview }}>
// Make spamReview accessible in client script
const spamReview = spamReviewConfig || {};
async function setCsrfToken() {
try {
const res = await fetch('/api/contact?csrf=true');
@@ -177,7 +174,7 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
const data = await res.json();
const csrfInput = document.getElementById('csrf_token');
if (csrfInput && data.csrfToken) {
(csrfInput as HTMLInputElement).value = data.csrfToken;
csrfInput.value = data.csrfToken;
}
}
} catch (e) {
@@ -187,7 +184,7 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
document.addEventListener('DOMContentLoaded', setCsrfToken);
const form = document.getElementById('contact-form') as HTMLFormElement | null;
const form = document.getElementById('contact-form');
if (form) {
form.addEventListener('submit', async (event) => {
@@ -198,14 +195,29 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
response = await fetch('/api/contact', {
method: 'POST',
body: formData,
headers: {
'Accept': 'application/json',
},
});
result = await response.json();
// Check if response is JSON before parsing
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
result = await response.json();
} else {
const text = await response.text();
throw new Error(`Unexpected response type: ${contentType || 'unknown'}. Response: ${text.substring(0, 100)}`);
}
console.log('Contact API response:', result);
} catch (_err) {
} catch (err) {
const errorElement = document.getElementById('form-error');
if (errorElement) errorElement.classList.remove('hidden');
const successElement = document.getElementById('form-success');
if (successElement) successElement.classList.add('hidden');
if (errorElement) {
errorElement.textContent = 'Network error. Please check your connection and try again.';
errorElement.classList.remove('hidden');
}
console.error('Form submission error:', err);
return;
}
@@ -214,8 +226,8 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
console.log('Spam detected, showing manual review UI.');
form.style.display = 'none';
const spamWarning = document.getElementById('spam-warning');
const manualEmail = document.getElementById('manual-email') as HTMLInputElement | null;
const manualToken = document.getElementById('manual-token') as HTMLInputElement | null;
const manualEmail = document.getElementById('manual-email');
const manualToken = document.getElementById('manual-token');
// Store the original email in a variable (not in the input)
window.__originalEmail = String(formData.get('email'));
if (spamWarning && manualEmail && manualToken) {
@@ -228,17 +240,64 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
if (!response.ok) {
const errorElement = document.getElementById('form-error');
if (errorElement) errorElement.classList.remove('hidden');
const successElement = document.getElementById('form-success');
if (successElement) successElement.classList.add('hidden');
// Handle specific error cases
if (result.message && result.message.includes('Please use POST')) {
if (errorElement) {
errorElement.textContent = 'There was an error with the form submission. Please refresh the page and try again.';
errorElement.classList.remove('hidden');
}
} else if (result.errors) {
// Handle field-specific validation errors
if (errorElement) {
errorElement.textContent = 'Please check all fields and try again.';
errorElement.classList.remove('hidden');
}
// Show field-specific errors
Object.keys(result.errors).forEach((fieldName) => {
const field = form.querySelector(`[name="${fieldName}"]`);
const feedback = document.getElementById(`invalid-feedback-${fieldName}`);
if (field && feedback) {
field.classList.add('border-red-500');
feedback.textContent = result.errors[fieldName];
feedback.classList.remove('hidden');
}
});
} else if (result.error) {
if (errorElement) {
errorElement.textContent = result.error;
errorElement.classList.remove('hidden');
}
} else {
if (errorElement) {
errorElement.textContent = 'There was an error sending your message. Please try again.';
errorElement.classList.remove('hidden');
}
}
return;
}
// Success
const successElement = document.getElementById('form-success');
if (successElement) successElement.classList.remove('hidden');
if (successElement) {
successElement.textContent = result.message || 'Your message has been sent successfully. We will get back to you soon!';
successElement.classList.remove('hidden');
}
const errorElement = document.getElementById('form-error');
if (errorElement) errorElement.classList.add('hidden');
// Clear any field error states
form.querySelectorAll('.border-red-500').forEach((el) => {
el.classList.remove('border-red-500');
});
form.querySelectorAll('.invalid-feedback').forEach((el) => {
el.classList.add('hidden');
});
form.reset();
setCsrfToken();
});
@@ -249,11 +308,11 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
if (manualReviewForm) {
manualReviewForm.onsubmit = async function (e) {
e.preventDefault();
const manualEmail = document.getElementById('manual-email') as HTMLInputElement | null;
const manualJustification = document.getElementById('manual-justification') as HTMLTextAreaElement | null;
const manualToken = document.getElementById('manual-token') as HTMLInputElement | null;
const manualEmail = document.getElementById('manual-email');
const manualJustification = document.getElementById('manual-justification');
const manualToken = document.getElementById('manual-token');
const resultDiv = document.getElementById('manual-review-result');
const form = document.getElementById('contact-form') as HTMLFormElement | null;
const form = document.getElementById('contact-form');
const spamWarning = document.getElementById('spam-warning');
if (!manualEmail || !manualJustification || !manualToken || !resultDiv) return;
const email = manualEmail.value;

View File

@@ -10,7 +10,7 @@ export async function isSpamWithGemini(message: string): Promise<boolean> {
console.warn('[Gemini] API key not set; skipping spam check.');
return false;
}
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
const prompt = `Is the following message spam? Reply with only 'yes' or 'no'.\n\nMessage:\n${message}`;
const result = await model.generateContent(prompt);
const response = result.response.text().trim().toLowerCase();