Skip to content
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

Merged
merged 8 commits into from
Jan 14, 2025
Merged

Fix/changes #201

merged 8 commits into from
Jan 14, 2025

Conversation

reisene
Copy link
Owner

@reisene reisene commented Jan 14, 2025

reisene TypeError: Cannot read properties of null (reading 'includes') Powered by Pull Request Badge

Podsumowanie przez Sourcery

Ulepszenia:

  • Wyodrębnienie pobierania i przygotowania danych formularza do osobnych funkcji.
Original summary in English

Summary by Sourcery

Enhancements:

  • Extract form data retrieval and preparation into separate functions.

Copy link
Contributor

aviator-app bot commented Jan 14, 2025

Current Aviator status

Aviator will automatically update this comment as the status of the PR changes.
Comment /aviator refresh to force Aviator to re-examine your PR (or learn about other /aviator commands).

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.

Copy link
Contributor

aviator-app bot commented Jan 14, 2025

Aviator Changeset actions:

Copy link

semanticdiff-com bot commented Jan 14, 2025

Review changes with  SemanticDiff

Changed Files
File Status
  .gitignore Unsupported file format
  public_html/js/__tests__/send_email.test.js  0% smaller
  public_html/js/__tests__/send_email.test.js.map Unsupported file format
  public_html/js/send_email.js.map Unsupported file format
  src/js/send_email.js  0% smaller

Copy link

vercel bot commented Jan 14, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
hulaj-dusza-serwis ❌ Failed (Inspect) Jan 14, 2025 6:20pm

Copy link

Please follow naming conventions! 😿

Copy link
Contributor

sourcery-ai bot commented Jan 14, 2025

Przewodnik Recenzenta przez Sourcery

Ten pull request refaktoryzuje funkcję handleSubmit w pliku send_email.js, aby poprawić czytelność i organizację kodu. Wprowadza kilka funkcji pomocniczych: getFormData, prepareData i sendDataToServer, aby rozdzielić odpowiedzialności i uczynić kod łatwiejszym w utrzymaniu. Podstawowa logika pozostaje taka sama, ale kod jest teraz bardziej ustrukturyzowany i modularny.

Diagram sekwencji dla zrefaktoryzowanego procesu wysyłania formularza

sequenceDiagram
    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
Loading

Diagram klas przedstawiający zrefaktoryzowane funkcje wysyłania formularza

classDiagram
    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"
Loading

Diagram przepływu zrefaktoryzowanego procesu wysyłania formularza

graph 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
Loading

Zmiany na Poziomie Pliku

Zmiana Szczegóły Pliki
Refaktoryzacja obsługi danych formularza.
  • Utworzono getFormData do hermetyzacji pobierania danych formularza.
  • Utworzono prepareData do obsługi przygotowania danych do wysłania na serwer.
  • Zaktualizowano handleSubmit do używania nowych funkcji pomocniczych, poprawiając przejrzystość i organizację kodu.
src/js/send_email.js
Wprowadzono unikalny identyfikator dla wysyłania formularzy.
  • Dodano uniqueID do każdego wysłania formularza, aby poprawić śledzenie i debugowanie.
src/js/send_email.js
Dodano funkcjonalność przesyłania plików.
  • Utworzono obiekt File zawierający dane formularza i wysłano go na serwer.
  • Zaktualizowano sendDataToServer do obsługi przesyłania plików.
src/js/send_email.js
Zaktualizowano obsługę plików.
  • Zaktualizowano pliki .gitignore, public_html/js/send_email.js i public_html/js/send_email.js.map, aby odzwierciedlić zmiany w obsłudze plików i strukturze projektu.
.gitignore
public_html/js/send_email.js
public_html/js/send_email.js.map

Porady i polecenia

Interakcja z Sourcery

  • Wywołanie nowej recenzji: Skomentuj @sourcery-ai review w pull requeście.
  • Kontynuacja dyskusji: Odpowiedz bezpośrednio na komentarze recenzji Sourcery.
  • Wygenerowanie zgłoszenia GitHub z komentarza recenzji: Poproś Sourcery o utworzenie zgłoszenia z komentarza recenzji, odpowiadając na niego.
  • Wygenerowanie tytułu pull requesta: Napisz @sourcery-ai w dowolnym miejscu tytułu pull requesta, aby wygenerować tytuł w dowolnym momencie.
  • Wygenerowanie podsumowania pull requesta: Napisz @sourcery-ai summary w dowolnym miejscu treści pull requesta, aby wygenerować podsumowanie PR w dowolnym momencie. Możesz również użyć tego polecenia, aby określić, gdzie podsumowanie powinno zostać wstawione.

Dostosowywanie Doświadczenia

Uzyskaj dostęp do pulpitu nawigacyjnego, aby:

  • Włączyć lub wyłączyć funkcje recenzji, takie jak podsumowanie pull requesta wygenerowane przez Sourcery, przewodnik recenzenta i inne.
  • Zmienić język recenzji.
  • Dodawać, usuwać lub edytować niestandardowe instrukcje recenzji.
  • Dostosować inne ustawienia recenzji.

Uzyskiwanie Pomocy

Original review guide in English

Reviewer's Guide by Sourcery

This pull request refactors the handleSubmit function in send_email.js to improve code readability and organization. It introduces several helper functions: getFormData, prepareData, and sendDataToServer, to separate concerns and make the code easier to maintain. The core logic remains the same, but the code is now more structured and modular.

Sequence diagram for refactored form submission process

sequenceDiagram
    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
Loading

Class diagram showing refactored form submission functions

classDiagram
    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"
Loading

Flow diagram of the refactored form submission process

graph 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
Loading

File-Level Changes

Change Details Files
Refactored form data handling.
  • Created getFormData to encapsulate retrieving form data.
  • Created prepareData to handle data preparation for server submission.
  • Updated handleSubmit to use the new helper functions, improving code clarity and organization.
src/js/send_email.js
Introduced a unique ID for form submissions.
  • Added a uniqueID to each form submission to improve tracking and debugging.
src/js/send_email.js
Added file upload functionality.
  • Created a File object containing form data and sent it to the server.
  • Updated sendDataToServer to handle file uploads.
src/js/send_email.js
Updated file handling.
  • Updated .gitignore, public_html/js/send_email.js, and public_html/js/send_email.js.map files to reflect changes in file handling and project structure.
.gitignore
public_html/js/send_email.js
public_html/js/send_email.js.map

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

deepsource-io bot commented Jan 14, 2025

Here's the code health analysis summary for commits 5019439..185a035. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource JavaScript LogoJavaScript✅ SuccessView Check ↗
DeepSource PHP LogoPHP✅ SuccessView Check ↗
DeepSource Test coverage LogoTest coverage⚠️ Artifact not reportedTimed out: Artifact was never reportedView Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link

Click here to review and test in web IDE: Contribute

@aviator-app aviator-app bot added the blocked label Jan 14, 2025
Copy link
Contributor

aviator-app bot commented Jan 14, 2025

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 blocked pull request label from this PR and then try to re-queue the PR. Note that the pull request will be automatically re-queued if it has the mergequeue label.

Additional debug info: There is a conflict with main or with another PR in the queue.

Please resolve manually and requeue. If resolving manually does not work, you may need to wait for previous PRs in the queue to merge.

Copy link
Contributor

mergify bot commented Jan 14, 2025

👋 reisene your PR is conflicting and needs to be updated to be merged

@mergify mergify bot added the conflict label Jan 14, 2025
Copy link
Contributor

mergify bot commented Jan 14, 2025

Merge Protections

Your pull request matches the following merge protections and will not be merged until they are valid.

🟢 Do not merge outdated PRs

Wonderful, this rule succeeded.

Make sure PRs are almost up to date before merging

  • #commits-behind <= 10

@@ -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)})});

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.

Comment on lines 117 to 123
const data = prepareData(formData, token);

const file = new File([JSON.stringify(formData)], 'form_data.txt', {
type: 'text/plain',
});

await sendDataToServer(submitButton, data, file);

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.

Comment on lines 146 to 163
// 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);

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.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a 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 ✨
Pomóż mi być bardziej użytecznym! Proszę kliknij 👍 lub 👎 na każdy komentarz, a ja wykorzystam opinię, aby poprawić swoje recenzje.
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

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
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;
Copy link
Contributor

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.

@@ -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)})});
Copy link
Contributor

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.

Z Przewodnika stylu JavaScript Airbnb

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

@@ -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)})});
Copy link
Contributor

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śnienieZaleca 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)

Suggested 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"),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) {


ExplanationIt 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).

@@ -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)})});
Copy link
Contributor

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śnienieZaleca 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)

Suggested 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"),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) {


ExplanationIt 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).

@@ -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)})});
Copy link
Contributor

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.

Z Przewodnika stylu JavaScript Airbnb

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

@@ -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)})});
Copy link
Contributor

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śnienieZaleca 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)

Suggested 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"),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) {


ExplanationIt 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).

@@ -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)})});
Copy link
Contributor

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.

Z Przewodnika stylu JavaScript Airbnb

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

@@ -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)})});
Copy link
Contributor

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śnienieZaleca 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)

Suggested 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"),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) {


ExplanationIt 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).

@@ -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)})});
Copy link
Contributor

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.

Z Przewodnika stylu JavaScript Airbnb

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

@reisene reisene added merge when passing Merge the PR automatically once all status checks have passed and removed conflict blocked labels Jan 14, 2025
Copy link
Contributor

aviator-app bot commented Jan 14, 2025

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 blocked pull request label from this PR and then try to re-queue the PR. Note that the pull request will be automatically re-queued if it has the mergequeue label.

Additional debug info: There is a conflict with main or with another PR in the queue.

Please resolve manually and requeue. If resolving manually does not work, you may need to wait for previous PRs in the queue to merge.

@mergify mergify bot added the conflict label Jan 14, 2025
@pull-request-size pull-request-size bot added size/S and removed size/M labels Jan 14, 2025
Copy link

@github-actions github-actions bot left a 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

Copy link

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

OpenSSF Scorecard

PackageVersionScoreDetails

Scanned Files

@mergify mergify bot removed the conflict label Jan 14, 2025
@reisene reisene removed the blocked label Jan 14, 2025
@@ -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)})});
Copy link

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).

Copy link
Contributor

aviator-app bot commented Jan 14, 2025

Skipping bot pull request creation because the queue is empty and this pull request is up to date with main.

@@ -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)})});

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.

@reisene
Copy link
Owner Author

reisene commented Jan 14, 2025

@mergify queue

Copy link
Contributor

mergify bot commented Jan 14, 2025

queue

🟠 Waiting for conditions to match

  • any of: [🔀 queue conditions]
    • all of: [📌 queue conditions of queue default]
      • any of: [🛡 GitHub branch protection]
        • check-neutral = CodeQL
        • check-skipped = CodeQL
        • check-success = CodeQL
      • any of: [🛡 GitHub branch protection]
        • check-success = Mergify Merge Protections
        • check-neutral = Mergify Merge Protections
        • check-skipped = Mergify Merge Protections
  • -closed [📌 queue requirement]
  • -conflict [📌 queue requirement]
  • -draft [📌 queue requirement]
  • any of: [📌 queue -> configuration change requirements]
    • -mergify-configuration-changed
    • check-success = Configuration changed
  • any of: [📌 queue requirement]
    • check-success = Mergify Merge Protections
    • check-neutral = Mergify Merge Protections
    • check-skipped = Mergify Merge Protections

@reisene
Copy link
Owner Author

reisene commented Jan 14, 2025

@mergify queue

Copy link
Contributor

mergify bot commented Jan 14, 2025

queue

🟠 Waiting for conditions to match

  • any of: [🔀 queue conditions]
    • all of: [📌 queue conditions of queue default]
      • any of: [🛡 GitHub branch protection]
        • check-neutral = CodeQL
        • check-skipped = CodeQL
        • check-success = CodeQL
      • any of: [🛡 GitHub branch protection]
        • check-success = Mergify Merge Protections
        • check-neutral = Mergify Merge Protections
        • check-skipped = Mergify Merge Protections
  • -closed [📌 queue requirement]
  • -conflict [📌 queue requirement]
  • -draft [📌 queue requirement]
  • any of: [📌 queue -> configuration change requirements]
    • -mergify-configuration-changed
    • check-success = Configuration changed
  • any of: [📌 queue requirement]
    • check-success = Mergify Merge Protections
    • check-neutral = Mergify Merge Protections
    • check-skipped = Mergify Merge Protections

@reisene
Copy link
Owner Author

reisene commented Jan 14, 2025

@mergify queue

@reisene reisene merged commit 03ef335 into main Jan 14, 2025
17 of 25 checks passed
@reisene reisene deleted the FIX/changes branch January 14, 2025 19:37
Copy link
Contributor

mergify bot commented Jan 14, 2025

queue

🟠 Waiting for conditions to match

  • -closed [📌 queue requirement]
  • any of: [🔀 queue conditions]
    • all of: [📌 queue conditions of queue default]
      • any of: [🛡 GitHub branch protection]
        • check-neutral = CodeQL
        • check-skipped = CodeQL
        • check-success = CodeQL
      • any of: [🛡 GitHub branch protection]
        • check-success = Mergify Merge Protections
        • check-neutral = Mergify Merge Protections
        • check-skipped = Mergify Merge Protections
  • -conflict [📌 queue requirement]
  • -draft [📌 queue requirement]
  • any of: [📌 queue -> configuration change requirements]
    • -mergify-configuration-changed
    • check-success = Configuration changed
  • any of: [📌 queue requirement]
    • check-success = Mergify Merge Protections
    • check-neutral = Mergify Merge Protections
    • check-skipped = Mergify Merge Protections

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
AnyChange automerge Mergify label merge when passing Merge the PR automatically once all status checks have passed mergequeue release root size/S source
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants