-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix/changes #201
Fix/changes #201
Conversation
Current Aviator status
This PR was merged manually (without Aviator). Merging manually can negatively impact the performance of the queue. Consider using Aviator next time.
See the real-time status of this PR on the
Aviator webapp.
Use the Aviator Chrome Extension
to see the status of your PR within GitHub.
|
Aviator Changeset actions:
|
Changed Files
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
Please follow naming conventions! 😿 |
Przewodnik Recenzenta przez SourceryTen pull request refaktoryzuje funkcję Diagram sekwencji dla zrefaktoryzowanego procesu wysyłania formularzasequenceDiagram
participant User as User
participant Form as Form
participant Handler as HandleSubmit
participant Helper as Helper Functions
participant Server as Server
User->>Form: Submits form
Form->>Handler: handleSubmit(event, token)
Handler->>Helper: getFormData()
Helper-->>Handler: returns formData object
Handler->>Helper: prepareData(formData, token)
Helper-->>Handler: returns prepared FormData
Handler->>Helper: sendDataToServer(button, data, file)
Helper->>Server: sends form data
Server-->>User: response
Diagram klas przedstawiający zrefaktoryzowane funkcje wysyłania formularzaclassDiagram
class HandleSubmit {
+handleSubmit(event, token)
}
class FormDataHelper {
+getFormData()
+prepareData(formData, token)
}
class ServerCommunication {
+sendDataToServer(submitButton, data, file)
}
HandleSubmit ..> FormDataHelper : uses
HandleSubmit ..> ServerCommunication : uses
note for HandleSubmit "Główny punkt wejścia dla wysyłania formularza"
note for FormDataHelper "Obsługuje przygotowanie danych formularza"
note for ServerCommunication "Zarządza komunikacją z serwerem"
Diagram przepływu zrefaktoryzowanego procesu wysyłania formularzagraph TD
A[Wysłanie Formularza] --> B[handleSubmit]
B --> C[getFormData]
C --> D[prepareData]
D --> E[Utworzenie Pliku]
E --> F[sendDataToServer]
style B fill:#f9f,stroke:#333,stroke-width:2px
style C fill:#bbf,stroke:#333,stroke-width:2px
style D fill:#bbf,stroke:#333,stroke-width:2px
style F fill:#bbf,stroke:#333,stroke-width:2px
Zmiany na Poziomie Pliku
Porady i poleceniaInterakcja z Sourcery
Dostosowywanie DoświadczeniaUzyskaj dostęp do pulpitu nawigacyjnego, aby:
Uzyskiwanie Pomocy
Original review guide in EnglishReviewer's Guide by SourceryThis pull request refactors the Sequence diagram for refactored form submission processsequenceDiagram
participant User as User
participant Form as Form
participant Handler as HandleSubmit
participant Helper as Helper Functions
participant Server as Server
User->>Form: Submits form
Form->>Handler: handleSubmit(event, token)
Handler->>Helper: getFormData()
Helper-->>Handler: returns formData object
Handler->>Helper: prepareData(formData, token)
Helper-->>Handler: returns prepared FormData
Handler->>Helper: sendDataToServer(button, data, file)
Helper->>Server: sends form data
Server-->>User: response
Class diagram showing refactored form submission functionsclassDiagram
class HandleSubmit {
+handleSubmit(event, token)
}
class FormDataHelper {
+getFormData()
+prepareData(formData, token)
}
class ServerCommunication {
+sendDataToServer(submitButton, data, file)
}
HandleSubmit ..> FormDataHelper : uses
HandleSubmit ..> ServerCommunication : uses
note for HandleSubmit "Main entry point for form submission"
note for FormDataHelper "Handles form data preparation"
note for ServerCommunication "Manages server communication"
Flow diagram of the refactored form submission processgraph TD
A[Form Submit] --> B[handleSubmit]
B --> C[getFormData]
C --> D[prepareData]
D --> E[Create File]
E --> F[sendDataToServer]
style B fill:#f9f,stroke:#333,stroke-width:2px
style C fill:#bbf,stroke:#333,stroke-width:2px
style D fill:#bbf,stroke:#333,stroke-width:2px
style F fill:#bbf,stroke:#333,stroke-width:2px
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Here's the code health analysis summary for commits Analysis Summary
|
This pull request failed to merge: PR cannot be automatically rebased, please rebase manually to continue. After you have resolved the problem, you should remove the Additional debug info: There is a conflict with Please resolve manually and requeue. If resolving manually does not work, you may need to wait for previous PRs in the queue to merge. |
👋 reisene your PR is conflicting and needs to be updated to be merged |
Merge ProtectionsYour pull request matches the following merge protections and will not be merged until they are valid. 🟢 Do not merge outdated PRsWonderful, this rule succeeded.Make sure PRs are almost up to date before merging
|
public_html/js/send_email.js
Outdated
@@ -1,2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e={email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value},r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}var o=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),a=document.getElementById("csrf-token").value,n=new FormData,t=(n.append("name",e.name),n.append("email",e.email),n.append("phone",e.phone),n.append("message",e.message),n.append("g-recaptcha-response",t),n.append("uniqueID",o),n.append("csrf_token",a),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}));await sendDataToServer(r,n,t)}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The line packs multiple imports and initializations into a single line, which significantly reduces the readability and maintainability of the code. It is recommended to split this line into multiple lines, with each import or initialization on its own line. This will make the code easier to read and maintain, and it will also make it easier to track changes in version control systems.
Recommended Change:
import displayNotification from "./modules/notification.js";
import phoneFormatter from "./modules/phone-format.js";
import initButtonAnimation from "./modules/button-animation.js";
let form = document.getElementById("my-form");
let init = initButtonAnimation();
This change separates each operation into its own line, enhancing clarity and maintainability.
src/js/send_email.js
Outdated
const data = prepareData(formData, token); | ||
|
||
const file = new File([JSON.stringify(formData)], 'form_data.txt', { | ||
type: 'text/plain', | ||
}); | ||
|
||
await sendDataToServer(submitButton, data, file); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential Data Race and Security Concern
The function prepareData
constructs a FormData
object and appends various user inputs and tokens. However, there is a potential data race or security issue with how the CSRF token is handled:
- The CSRF token is fetched and appended to the form data within the same function that handles the form submission. This could lead to scenarios where the token is not yet available or has been tampered with before submission.
Recommendation:
- Consider fetching and validating the CSRF token before enabling the form submission button. This ensures that the token is valid and present, reducing the risk of CSRF attacks.
src/js/send_email.js
Outdated
// Get the CSRF token from the hidden input field | ||
const csrfToken = document.getElementById('csrf-token').value; | ||
|
||
// Prepare data for sending | ||
// Create a new FormData object to store the form data | ||
const data = new FormData(); | ||
|
||
// Append the form data to the FormData object | ||
data.append('name', formData.name); | ||
data.append('email', formData.email); | ||
data.append('phone', formData.phone); | ||
data.append('message', formData.message); | ||
|
||
// Append the reCAPTCHA token and unique ID to the FormData object | ||
data.append('g-recaptcha-response', token); | ||
data.append('uniqueID', uniqueID); | ||
data.append('csrf_token', csrfToken); | ||
|
||
const file = new File([JSON.stringify(formData)], 'form_data.txt', { | ||
type: 'text/plain', | ||
}); | ||
// Append the CSRF token to the FormData object | ||
data.append('csrf_token', csrfToken); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Inefficient Handling of Form Data
The prepareData
function manually appends each form field to the FormData
object. This approach is not only verbose but also error-prone, as any change in the form structure requires updates in this function.
Recommendation:
- Use a more dynamic approach to append form data by iterating over the form elements or using the
FormData
constructor directly with the form element:
const data = new FormData(form);
This method automatically handles all form inputs and is less prone to errors if the form structure changes.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cześć @reisene - Przejrzałem twoje zmiany - oto kilka uwag:
Ogólne uwagi:
- Proszę użyć bardziej opisowego tytułu PR, który odzwierciedla rzeczywiste zmiany (np. 'Refaktoryzacja kodu przesyłania formularza na mniejsze funkcje')
- Rozważ usunięcie zbędnego przesyłania pliku danych formularza, ponieważ te same dane są już przesyłane za pomocą obiektu FormData
Oto, co sprawdziłem podczas przeglądu
- 🟡 Ogólne problemy: znaleziono 1 problem
- 🟢 Bezpieczeństwo: wszystko wygląda dobrze
- 🟢 Testowanie: wszystko wygląda dobrze
- 🟢 Złożoność: wszystko wygląda dobrze
- 🟢 Dokumentacja: wszystko wygląda dobrze
Sourcery jest darmowe dla open source - jeśli podobają Ci się nasze recenzje, rozważ ich udostępnienie ✨
Original comment in English
Hey @reisene - I've reviewed your changes - here's some feedback:
Overall Comments:
- Please use a more descriptive PR title that reflects the actual changes (e.g., 'Refactor form submission code into smaller functions')
- Consider removing the redundant form data file submission since the same data is already being sent via FormData object
Here's what I looked at during the review
- 🟡 General issues: 1 issue found
- 🟢 Security: all looks good
- 🟢 Testing: all looks good
- 🟢 Complexity: all looks good
- 🟢 Documentation: all looks good
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
const uniqueID = `${Date.now()}${Math.floor(Math.random() * 1000000).toString(36)}`; | ||
|
||
// Get the CSRF token from the hidden input field | ||
const csrfToken = document.getElementById('csrf-token').value; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue: Dodaj obsługę błędów dla brakującego elementu tokena CSRF
Jeśli element csrf-token nie zostanie znaleziony, zostanie zgłoszony błąd niezdefiniowany. Rozważ dodanie odpowiedniej obsługi błędów dla tego przypadku.
Original comment in English
issue: Add error handling for missing CSRF token element
If the csrf-token element is not found, this will throw an undefined error. Consider adding proper error handling for this case.
public_html/js/send_email.js
Outdated
@@ -1,2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e={email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value},r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}var o=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),a=document.getElementById("csrf-token").value,n=new FormData,t=(n.append("name",e.name),n.append("email",e.email),n.append("phone",e.phone),n.append("message",e.message),n.append("g-recaptcha-response",t),n.append("uniqueID",o),n.append("csrf_token",a),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}));await sendDataToServer(r,n,t)}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (code-quality): Użyj const
lub let
zamiast var
. (avoid-using-var
)
Wyjaśnienie
`const` jest preferowane, ponieważ zapewnia, że nie można ponownie przypisać referencji (co może prowadzić do błędnego i mylącego kodu). `let` może być używane, jeśli potrzebujesz ponownie przypisać referencje - jest preferowane w stosunku do `var`, ponieważ jest blokowe, a nie funkcjonalne.Original comment in English
issue (code-quality): Use const
or let
instead of var
. (avoid-using-var
)
Explanation
`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.From the Airbnb JavaScript Style Guide
public_html/js/send_email.js
Outdated
@@ -2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (code-quality): Użyj nawiasów blokowych dla ifów, while'ów itp. (use-braces
)
Wyjaśnienie
Zaleca się zawsze używać nawiasów i tworzyć jawne bloki instrukcji.Użycie dozwolonej składni do napisania tylko jednej instrukcji może prowadzić do bardzo mylących sytuacji, zwłaszcza gdy później programista może dodać kolejną instrukcję, zapominając o dodaniu nawiasów (co oznacza, że nie byłaby ona uwzględniona w warunku).
Original comment in English
suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces
)
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); | |
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if (e.preventDefault(),form) { |
Explanation
It is recommended to always use braces and create explicit statement blocks.Using the allowed syntax to just write a single statement can lead to very confusing
situations, especially where subsequently a developer might add another statement
while forgetting to add the braces (meaning that this wouldn't be included in the condition).
public_html/js/send_email.js
Outdated
@@ -2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (code-quality): Użyj nawiasów blokowych dla ifów, while'ów itp. (use-braces
)
Wyjaśnienie
Zaleca się zawsze używać nawiasów i tworzyć jawne bloki instrukcji.Użycie dozwolonej składni do napisania tylko jednej instrukcji może prowadzić do bardzo mylących sytuacji, zwłaszcza gdy później programista może dodać kolejną instrukcję, zapominając o dodaniu nawiasów (co oznacza, że nie byłaby ona uwzględniona w warunku).
Original comment in English
suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces
)
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); | |
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if (r) { |
Explanation
It is recommended to always use braces and create explicit statement blocks.Using the allowed syntax to just write a single statement can lead to very confusing
situations, especially where subsequently a developer might add another statement
while forgetting to add the braces (meaning that this wouldn't be included in the condition).
public_html/js/send_email.js
Outdated
@@ -2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (code-quality): Użyj const
lub let
zamiast var
. (avoid-using-var
)
Wyjaśnienie
`const` jest preferowane, ponieważ zapewnia, że nie można ponownie przypisać referencji (co może prowadzić do błędnego i mylącego kodu). `let` może być używane, jeśli potrzebujesz ponownie przypisać referencje - jest preferowane w stosunku do `var`, ponieważ jest blokowe, a nie funkcjonalne.Original comment in English
issue (code-quality): Use const
or let
instead of var
. (avoid-using-var
)
Explanation
`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.From the Airbnb JavaScript Style Guide
public_html/js/send_email.js
Outdated
@@ -2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (code-quality): Użyj nawiasów blokowych dla ifów, while'ów itp. (use-braces
)
Wyjaśnienie
Zaleca się zawsze używać nawiasów i tworzyć jawne bloki instrukcji.Użycie dozwolonej składni do napisania tylko jednej instrukcji może prowadzić do bardzo mylących sytuacji, zwłaszcza gdy później programista może dodać kolejną instrukcję, zapominając o dodaniu nawiasów (co oznacza, że nie byłaby ona uwzględniona w warunku).
Original comment in English
suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces
)
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); | |
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if (r.error) { |
Explanation
It is recommended to always use braces and create explicit statement blocks.Using the allowed syntax to just write a single statement can lead to very confusing
situations, especially where subsequently a developer might add another statement
while forgetting to add the braces (meaning that this wouldn't be included in the condition).
public_html/js/send_email.js
Outdated
@@ -2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (code-quality): Użyj const
lub let
zamiast var
. (avoid-using-var
)
Wyjaśnienie
`const` jest preferowane, ponieważ zapewnia, że nie można ponownie przypisać referencji (co może prowadzić do błędnego i mylącego kodu). `let` może być używane, jeśli potrzebujesz ponownie przypisać referencje - jest preferowane w stosunku do `var`, ponieważ jest blokowe, a nie funkcjonalne.Original comment in English
issue (code-quality): Use const
or let
instead of var
. (avoid-using-var
)
Explanation
`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.From the Airbnb JavaScript Style Guide
public_html/js/send_email.js
Outdated
@@ -2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (code-quality): Użyj nawiasów blokowych dla ifów, while'ów itp. (use-braces
)
Wyjaśnienie
Zaleca się zawsze używać nawiasów i tworzyć jawne bloki instrukcji.Użycie dozwolonej składni do napisania tylko jednej instrukcji może prowadzić do bardzo mylących sytuacji, zwłaszcza gdy później programista może dodać kolejną instrukcję, zapominając o dodaniu nawiasów (co oznacza, że nie byłaby ona uwzględniona w warunku).
Original comment in English
suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces
)
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); | |
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if (!o.ok) { |
Explanation
It is recommended to always use braces and create explicit statement blocks.Using the allowed syntax to just write a single statement can lead to very confusing
situations, especially where subsequently a developer might add another statement
while forgetting to add the braces (meaning that this wouldn't be included in the condition).
public_html/js/send_email.js
Outdated
@@ -2 +1,2 @@ | |||
import displayNotification from"./modules/notification.js";import phoneFormatter from"./modules/phone-format.js";import initButtonAnimation from"./modules/button-animation.js";let form=document.getElementById("my-form"),init=initButtonAnimation();function generateCsfrToken(){fetch("/php/generate-token.php").then(e=>e.text()).then(e=>{localStorage.setItem("csrf_token",e),document.getElementById("csrf-token").value=e}).catch(e=>{var t={message:"Błąd pobierania tokena",url:"/php/generate-token.php",method:"GET"};Sentry.captureException(new Error(t.message),{extra:t}),console.error("Błąd pobierania tokena:",e)})}async function handleSubmit(e,t){if(e.preventDefault(),form){var e=getFormData(),r=form.querySelector('button[type="submit"]');if(r){r.disabled=!0;try{await validateFormData(r,e)}catch(e){return void console.error(e)}await sendDataToServer(r,prepareData(e,t),new File([JSON.stringify(e)],"form_data.txt",{type:"text/plain"}))}else console.error("Submit button not found.")}else console.error("Form not found."),Sentry.captureException(error,{extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formName:"kontakt",formAction:window.location.href,formMethod:"POST"}})}function getFormData(){return{email:document.getElementById("email").value,phone:document.getElementById("phone").value.replace(/\D/g,""),name:document.getElementById("name").value,message:document.getElementById("message").value}}function prepareData(e,t){var r=""+Date.now()+Math.floor(1e6*Math.random()).toString(36),o=document.getElementById("csrf-token").value,a=new FormData;return a.append("name",e.name),a.append("email",e.email),a.append("phone",e.phone),a.append("message",e.message),a.append("g-recaptcha-response",t),a.append("uniqueID",r),a.append("csrf_token",o),a}async function validateFormData(t,e){try{var r=await(await fetch("../php/validate-data.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(r.error)throw displayNotification(r.error,"error"),setTimeout(()=>{init.resetButton()},200),new Error(r.error);return!0}catch(e){throw t.disabled=!1,e}}async function sendDataToServer(e,t,r){try{var o=await fetch("../php/send_email.php",{method:"POST",body:t});if(!o.ok)throw new Error(`Błąd ${o.status}: `+o.statusText);var a=await o.json();a.success?(displayNotification(a.message,"success"),setTimeout(()=>{init.animateButton("success")},0),setTimeout(()=>{form.reset()},5e3)):(displayNotification(a.message,"error"),setTimeout(()=>{init.animateButton("error")},0))}catch(e){console.error("Form submission error:",e.message,e.stack),handleError(r,e)}finally{e.disabled=!1,setTimeout(()=>{init.resetButton()},5e3)}}function handleError(e,t){Sentry.captureException(t,{attachments:[{filename:"form_data.txt",data:e,contentType:"text/plain"}],tags:{"form-name":"kontakt"},extra:{url:window.location.href,referrer:document.referrer,userAgent:navigator.userAgent,formData:e,formMethod:"POST",formAction:"../php/send_email.php",formError:t.message,formErrorStack:t.stack,formErrorName:t.name,formErrorMessage:t.message}}),t.message.includes("Błąd")?displayNotification("Wystąpił błąd. Proszę spróbować ponownie.","error"):displayNotification("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error")}document.addEventListener("DOMContentLoaded",()=>{document.getElementById("phone").addEventListener("input",phoneFormatter),generateCsfrToken(),phoneFormatter()}),form.addEventListener("submit",r=>{r.preventDefault(),fetch("../config.json").then(e=>e.text()).then(e=>{let t=JSON.parse(e);grecaptcha.ready(()=>{grecaptcha.execute(t.recaptchaSiteKey,{action:"submit"}).then(e=>{e?handleSubmit(r,e):displayNotification("ReCAPTCHA verification failed. Please try again.","error")}).catch(e=>{console.error("ReCAPTCHA error:",e),displayNotification("ReCAPTCHA verification failed. Please try again.","error")})})}).catch(e=>{console.error("Error loading config:",e)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (code-quality): Użyj const
lub let
zamiast var
. (avoid-using-var
)
Wyjaśnienie
`const` jest preferowane, ponieważ zapewnia, że nie można ponownie przypisać referencji (co może prowadzić do błędnego i mylącego kodu). `let` może być używane, jeśli potrzebujesz ponownie przypisać referencje - jest preferowane w stosunku do `var`, ponieważ jest blokowe, a nie funkcjonalne.Original comment in English
issue (code-quality): Use const
or let
instead of var
. (avoid-using-var
)
Explanation
`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.From the Airbnb JavaScript Style Guide
This pull request failed to merge: PR cannot be automatically rebased, please rebase manually to continue. After you have resolved the problem, you should remove the Additional debug info: There is a conflict with Please resolve manually and requeue. If resolving manually does not work, you may need to wait for previous PRs in the queue to merge. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code review by ChatGPT
Dependency Review✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.OpenSSF Scorecard
Scanned Files |
@@ -0,0 +1,2 @@ | |||
import{jest}from"@jest/globals";import displayNotification from"../modules/notification";import phoneFormatter from"../modules/phone-format";import initButtonAnimation from"../modules/button-animation";jest.mock("../modules/notification"),jest.mock("../modules/phone-format"),jest.mock("../modules/button-animation"),describe("Form Submission Handler",()=>{let a,o;beforeEach(()=>{(a=document.createElement("form")).id="my-form",(o=document.createElement("button")).type="submit",a.appendChild(o);["email","phone","name","message","csrf-token"].forEach(e=>{var t=document.createElement("input");t.id=e,t.value="test-"+e,a.appendChild(t)}),document.body.appendChild(a),global.fetch=jest.fn(),global.localStorage={getItem:jest.fn(),setItem:jest.fn()}}),afterEach(()=>{document.body.innerHTML="",jest.clearAllMocks()}),test("generateCsfrToken fetches and stores token correctly",async()=>{let e="test-token";global.fetch.mockResolvedValueOnce({text:()=>Promise.resolve(e)}),await generateCsfrToken(),expect(global.fetch).toHaveBeenCalledWith("/php/generate-token.php"),expect(localStorage.setItem).toHaveBeenCalledWith("csrf_token",e),expect(document.getElementById("csrf-token").value).toBe(e)}),test("validateFormData handles validation success",async()=>{global.fetch.mockResolvedValueOnce({json:()=>Promise.resolve({success:!0})});var e=await validateFormData(o,{email:"test@example.com",phone:"123456789",name:"Test User",message:"Test message"});expect(e).toBe(!0)}),test("validateFormData handles validation error",async()=>{global.fetch.mockResolvedValueOnce({json:()=>Promise.resolve({error:"Validation failed"})}),await expect(validateFormData(o,{email:"invalid-email",phone:"",name:"",message:""})).rejects.toThrow("Validation failed"),expect(displayNotification).toHaveBeenCalledWith("Validation failed","error")}),test("sendDataToServer handles successful submission",async()=>{var e=new FormData,t=new File(["{}"],"test.txt");global.fetch.mockResolvedValueOnce({ok:!0,json:()=>Promise.resolve({success:!0,message:"Success"})}),await sendDataToServer(o,e,t),expect(displayNotification).toHaveBeenCalledWith("Success","success"),expect(o.disabled).toBe(!1)}),test("sendDataToServer handles submission error",async()=>{var e=new FormData,t=new File(["{}"],"test.txt");global.fetch.mockRejectedValueOnce(new Error("Network error")),await sendDataToServer(o,e,t),expect(displayNotification).toHaveBeenCalledWith("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error"),expect(o.disabled).toBe(!1)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
'arrow function syntax (=>)' is only available in ES6 (use 'esversion: 6').
'import' is only available in ES6 (use 'esversion: 6').
'let' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz).
Expected '(' and instead saw '{'.
Expected ')' and instead saw ';'.
Expected ')' and instead saw 'test-token'.
Expected ')' to match '{' from line 1 and instead saw '.'.
Expected ')' to match '{' from line 1 and instead saw 'e'.
Expected an assignment or function call and instead saw an expression.
Expected an identifier and instead saw '='.
Expected an identifier and instead saw 'let' (a reserved word).
Missing semicolon.
Unrecoverable syntax error. (33% scanned).
Skipping bot pull request creation because the queue is empty and this pull request is up to date with |
@@ -0,0 +1,2 @@ | |||
import{jest}from"@jest/globals";import displayNotification from"../modules/notification";import phoneFormatter from"../modules/phone-format";import initButtonAnimation from"../modules/button-animation";jest.mock("../modules/notification"),jest.mock("../modules/phone-format"),jest.mock("../modules/button-animation"),describe("Form Submission Handler",()=>{let a,o;beforeEach(()=>{(a=document.createElement("form")).id="my-form",(o=document.createElement("button")).type="submit",a.appendChild(o);["email","phone","name","message","csrf-token"].forEach(e=>{var t=document.createElement("input");t.id=e,t.value="test-"+e,a.appendChild(t)}),document.body.appendChild(a),global.fetch=jest.fn(),global.localStorage={getItem:jest.fn(),setItem:jest.fn()}}),afterEach(()=>{document.body.innerHTML="",jest.clearAllMocks()}),test("generateCsfrToken fetches and stores token correctly",async()=>{let e="test-token";global.fetch.mockResolvedValueOnce({text:()=>Promise.resolve(e)}),await generateCsfrToken(),expect(global.fetch).toHaveBeenCalledWith("/php/generate-token.php"),expect(localStorage.setItem).toHaveBeenCalledWith("csrf_token",e),expect(document.getElementById("csrf-token").value).toBe(e)}),test("validateFormData handles validation success",async()=>{global.fetch.mockResolvedValueOnce({json:()=>Promise.resolve({success:!0})});var e=await validateFormData(o,{email:"test@example.com",phone:"123456789",name:"Test User",message:"Test message"});expect(e).toBe(!0)}),test("validateFormData handles validation error",async()=>{global.fetch.mockResolvedValueOnce({json:()=>Promise.resolve({error:"Validation failed"})}),await expect(validateFormData(o,{email:"invalid-email",phone:"",name:"",message:""})).rejects.toThrow("Validation failed"),expect(displayNotification).toHaveBeenCalledWith("Validation failed","error")}),test("sendDataToServer handles successful submission",async()=>{var e=new FormData,t=new File(["{}"],"test.txt");global.fetch.mockResolvedValueOnce({ok:!0,json:()=>Promise.resolve({success:!0,message:"Success"})}),await sendDataToServer(o,e,t),expect(displayNotification).toHaveBeenCalledWith("Success","success"),expect(o.disabled).toBe(!1)}),test("sendDataToServer handles submission error",async()=>{var e=new FormData,t=new File(["{}"],"test.txt");global.fetch.mockRejectedValueOnce(new Error("Network error")),await sendDataToServer(o,e,t),expect(displayNotification).toHaveBeenCalledWith("Wystąpił nieoczekiwany błąd. Proszę skontaktować się z administratorem.","error"),expect(o.disabled).toBe(!1)})}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The line combines multiple imports and Jest mock setups along with the initialization of a test suite, all in a single line. This approach significantly reduces the readability and maintainability of the code.
Recommended Solution:
- Break down the line into multiple lines, separating imports, Jest mock setups, and test suite initialization. This will enhance clarity and make the code easier to manage and understand.
|
@mergify queue |
🟠 Waiting for conditions to match
|
@mergify queue |
🟠 Waiting for conditions to match
|
@mergify queue |
🟠 Waiting for conditions to match
|
Podsumowanie przez Sourcery
Ulepszenia:
Original summary in English
Summary by Sourcery
Enhancements: