The date picker format stopped working after I moved the code from the PHTML file to a separate JavaScript file

I was implementing a date picker on one of my pages, and it was working fine. However, after moving my JavaScript files from the PHTML file to a separate JS file, it stopped working and is now picking the wrong format. Can you help me fix it?

Working file that present in the same phtml file

 $('#imported_from_dated').datepicker({
    format: '<?php echo DATE_PICKER_FORMAT; ?>', // format 'yyyy-mm-dd'
 }).on('changeDate', function (e) {
   $('#searchDataForm').formValidation('revalidateField', 'imported_from_dated');
   if ($('#imported_to_dated').val() != '') {
     $('#searchDataForm').formValidation('revalidateField', 'imported_to_dated');
   }
   $('#imported_from_dated').show();   
 });

 $('#imported_to_dated').datepicker({
   format: '<?php echo DATE_PICKER_FORMAT; ?>', // format 'yyyy-mm-dd'
 }).on('changeDate', function (e) {
    $('#searchDataForm').formValidation('revalidateField', 'imported_from_dated');
    $('#searchDataForm').formValidation('revalidateField', 'imported_to_dated');
    $('#imported_to_dated').show();
 });

 $('#searchDataForm').formValidation({
    message: 'list message',
    fields: {
        imported_from_dated: {
            validators: {
                notEmpty: {
                    message: 'error message 1',
                },
                date: {
                    format: '<?php echo DATE_VALIDATION_FORMAT; ?>', // format MM/DD/YYYY
                    message: 'error message 2',
                }
            }
        },
        imported_to_dated: {
            validators: {
                notEmpty: {
                    message: 'error message 3',,
                },
                date: {
                    format: dateValidationFormat,
                    message: 'error message 4',,
                },
                callback: {
                    callback: function (value, validator, $field) {
                        var startDate = $('#imported_from_dated').val();
                        var endDate = $('#imported_to_dated').val();
                        if (startDate !== '' && endDate !== '') {

                            var dateSt = startDate.split('/');
                            var dateEd = endDate.split('/');
                            var StDt = Date.parse(dateSt[2] + '-' + dateSt[0] + '-' + dateSt[1]); //Year, Month, Date
                            var EdDt = Date.parse(dateEd[2] + '-' + dateEd[0] + '-' + dateEd[1]);

                            if (StDt > EdDt) {
                                return {
                                    valid: false,
                                    message: 'error message 5',
                                };
                            }
                        }
                        return true;
                    }
                }
            }
        }
    }
}).on("keyup",'[name="imported_from_dated"]',function() {
    $("#searchDataForm").formValidation('revalidateField', 'imported_from_dated');
}).on("keyup",'[name="imported_to_dated"]',function() {
    $("#searchDataForm").formValidation('revalidateField', 'imported_to_dated');
});

from the above code while i am selecting any date it will update in to MM/DD/YYYY format.
example : 09/05/2024

But i have move the js file in to seperate file and the code looks like this
PHTML file

 <script type="text/javascript">
    var dateFormat = '<?php echo DATE_PICKER_FORMAT; ?>';
    var dateValidationFormat = <?php echo DATE_VALIDATION_FORMAT; ?>;
 </script>

 JS file

 $('#imported_from_dated').datepicker({
   format: dateFormat,
}).on('changeDate', function (e) {
    $('#searchDataForm').formValidation('revalidateField', 'imported_from_dated');
    if ($('#imported_to_dated').val() != '') {
        $('#searchDataForm').formValidation('revalidateField', 'imported_to_dated');
    }
    $('#imported_from_dated').show();
});

$('#imported_to_dated').datepicker({
   format: dateFormat,
}).on('changeDate', function (e) {
    $('#searchDataForm').formValidation('revalidateField', 'imported_from_dated');
    $('#searchDataForm').formValidation('revalidateField', 'imported_to_dated');
    $('#imported_to_dated').show();
});


$('#searchDataForm').formValidation({
    message: 'list message',
    fields: {
        imported_from_dated: {
            validators: {
                notEmpty: {
                    message: 'error message 1',
                },
                date: {
                    format: dateValidationFormat, // format MM/DD/YYYY
                    message: 'error message 2',
                }
            }
        },
        imported_to_dated: {
            validators: {
                notEmpty: {
                    message: 'error message 3',,
                },
                date: {
                    format: dateValidationFormat,
                    message: 'error message 4',,
                },
                callback: {
                    callback: function (value, validator, $field) {
                        var startDate = $('#imported_from_dated').val();
                        var endDate = $('#imported_to_dated').val();
                        if (startDate !== '' && endDate !== '') {

                            var dateSt = startDate.split('/');
                            var dateEd = endDate.split('/');
                            var StDt = Date.parse(dateSt[2] + '-' + dateSt[0] + '-' + dateSt[1]); //Year, Month, Date
                            var EdDt = Date.parse(dateEd[2] + '-' + dateEd[0] + '-' + dateEd[1]);

                            if (StDt > EdDt) {
                                return {
                                    valid: false,
                                    message: 'error message 5',
                                };
                            }
                        }
                        return true;
                    }
                }
            }
        }
    }
}).on("keyup",'[name="imported_from_dated"]',function() {
    $("#searchDataForm").formValidation('revalidateField', 'imported_from_dated');
}).on("keyup",'[name="imported_to_dated"]',function() {
    $("#searchDataForm").formValidation('revalidateField', 'imported_to_dated');
});

I have verified that the values are being passed to the JS file correctly, but I’m still getting the date in the ‘2024-09-05’ format (not converting to MM/DD/YYYY format). I can’t figure out what’s causing the issue, even though the code inside the JS file is written within the document.ready function.

Why this Factory function is not working?

I am writing this factory function in the index.js file. But it is not working. In the console it is showing that the ‘rectangle1’ is undefined. Please find the error.
console error

function createRectangle(len,bre) {
    let rectangle = {
        length: len,
        breadth: bre,
   
        draw: function() {
            console.log('drawing rectangle');
        }
    };
    return rectangle;
}

let rectangleObj1 = createRectangle(5,4);

Refactor the Parser [closed]

-Refactor the code in index.ts and fix potential bugs and concurrency issues.
-Although the working code is required, you aren’t required to write production-level code or handle all edge cases. Do not add new features, keep crucial functionality and refactor.
-Make your code as extensible and flexible as possible. Your main goal is to demonstrate the skill of writing extensible and flexible code.
-You may add comments explaining your refactoring decisions to avoid misunderstandings

Crucial functional requirements

  1. Read several files from API(create a mock), each containing string like:
    “Hello world! : 2024-02-22 14:35:30 UTC”
    “Goodbye world! : 2024-02-22 16:35:30 UTC”
    “Hello? : 2024-02-22 08:35:30 UTC”
    “Hi : 2024-02-22 12:35:30 UTC”

  2. Parse each line, wait for a random number of seconds <5, write a message to the console, and send to the API(create a mock) with the corresponding filename

  3. If parsing or writing fails – resolve gracefully, without error

  4. Read and process each file and its lines concurrently
    Fail criteria
    Violation of any criterion would lead to submission failure

Procedural code is not considered a successful solution
The code fails to run
Crucial functionality missing
Fewer than 5 classes and 5 interfaces
Classes with public fields, getters and setters
SOLID, DRY principles violated
Program is not smoothly made up by composing components
(components must compose like in index.ts file in the example)

const mockResponses: Record<string, string> = {
  "file1.txt": `Hello world! : 2024-02-22 14:35:30 UTC
  Goodbye world! : 2024-02-22 16:35:30 UTC
  Hello? : 2024-02-22 08:35:30 UTC
 Hi : 2024-02-22 12:35:30 UTC`,
  "file2.txt": `How are you doing ? : 2024-02-22 13:59:30 UTC
  Fine : 2024-02-22 12:44:30 UTC
  How about you ? : 2024-02-22 22:35:30 UTC
  Same : 2024-02-22 07:39:30 UTC`,
  "file3.txt": `Have you seen high elves ? : 2022-02-22 14:35:30 UTC
  HESOYAM : 2023-02-22 14:35:30 UTC
  BAGUVIX : 2021-02-22 14:35:30 UTC
  THERE IS NO SPOON : 2020-02-22 14:35:30 UTC`,
};

const mockFetch = async (
  filePath: string,
  params?: { body: string; method: string }
): Promise<string> => {
  if (params?.method === "POST") return "";
  return mockResponses[filePath] ?? "";
};

class Parser {
  constructor() {}
  async getContent(file: string): Promise<
    {
      message: string;
      timestamp: string;
    }[]
  > {
    const res = await mockFetch(file);
    const messages = res.split("n");
    const content: { message: string; timestamp: string }[] = [];
    for (let i = 0; i < messages.length; i++) {
      const [message, timestamp] = messages[i].split(":");
      content.push({ message, timestamp });
    }
    return content;
  }
  async saveContent(
    messages: { message: string; timestamp: string }[],
    file: string
  ) {
    const waitGroup: Promise<any>[] = [];
    for (let i = 0; i < messages.length; i++) {
      const promise = new Promise<void>(async (resolve) => {
        await new Promise<void>((resolve) =>
          setTimeout(() => resolve(), Math.random() * 5 * 1000)
        );
        await mockFetch(file, {
          body: JSON.stringify({
            ...messages[i],
            type: messages[i].message.length > 8 ? "long" : "short",
          }),
          method: "POST",
        });
        console.log(
          `Saved message - ${messages[i].message} to ${file} as ${
            messages[i].message.length > 8 ? "long" : "short"
          }`
        );
      });
      waitGroup.push(promise);
    }
    await Promise.all(waitGroup);
  }
}

const main = async () => {
  const files = {
    "file1.txt": "out1.txt",
    "file2.txt": "out2.txt",
    "file3.txt": "out3.txt",
  };
  const parser = new Parser();
  const waitGroup: Promise<any>[] = [];

  for (const [input, output] of Object.entries(files)) {
    const promise = new Promise<void>((resolve) => {
      parser
        .getContent(input)
        .catch((error) => {
          console.error(`Error while getting file ${input} - ${error}`);
          return [];
        })
        .then((messages) => parser.saveContent(messages, output))
        .catch((error) => {
          console.error(`Error while reading file ${input} - ${error}`);
        })
        .then(resolve);
    });
    waitGroup.push(promise);
  }
  await Promise.all(waitGroup);
};

main();

This is how I decided, please tell me if there are any mistakes here and how it can be improved

const mockResponses: Record<string, string> = {
  "file1.txt": `Hello world! : 2024-02-22 14:35:30 UTC
      Goodbye world! : 2024-02-22 16:35:30 UTC
      Hello? : 2024-02-22 08:35:30 UTC
     Hi : 2024-02-22 12:35:30 UTC`,
  "file2.txt": `How are you doing ? : 2024-02-22 13:59:30 UTC
      Fine : 2024-02-22 12:44:30 UTC
      How about you ? : 2024-02-22 22:35:30 UTC
      Same : 2024-02-22 07:39:30 UTC`,
  "file3.txt": `Have you seen high elves ? : 2022-02-22 14:35:30 UTC
      HESOYAM : 2023-02-22 14:35:30 UTC
      BAGUVIX : 2021-02-22 14:35:30 UTC
      THERE IS NO SPOON : 2020-02-22 14:35:30 UTC`,
};

interface IMessage {
  send: (message: IParserMessage, filepath: string) => Promise<void>;
}

interface IParser {
  parse: (content: string) => IParserMessage[];
}

interface IFileFetcher {
  fetch: (filepath: string) => Promise<string>;
}

interface IFileWriter {
  write: (filepath: string, content: string) => Promise<void>;
}

interface IParserMessage {
  message: string;
  timestamp: string;
}

const mockFetch = async (
  filePath: string,
  params?: { body: string; method: string }
): Promise<string> => {
  if (params?.method === "POST") return "";
  return mockResponses[filePath] ?? "";
};

const LONG_MESSAGE = "long";
const SHORT_MESSAGE = "short";
const POST_METHOD = "POST";

class FileFetch implements IFileFetcher {
  async fetch(filepath: string): Promise<string> {
    return mockFetch(filepath);
  }
}

class FileWriter implements IFileWriter {
  async write(filepath: string, content: string): Promise<void> {
    await mockFetch(filepath, { body: content, method: POST_METHOD });
  }
}

class Parser implements IParser {
  parse(content: string): IParserMessage[] {
    return content.split("n").map((line) => {
      const [message, timestamp] = line.trim().split(" : ");
      return { message, timestamp };
    });
  }
}

class ParserMessage implements IMessage {
  private writer: IFileWriter;

  constructor(writer: IFileWriter) {
    this.writer = writer;
  }

  async send(message: IParserMessage, filepath: string): Promise<void> {
    const delay = Math.random() * 5000;
    await new Promise<void>((resolve) => setTimeout(resolve, delay));
    const content = JSON.stringify({
      ...message,
      type: message.message.length > 8 ? LONG_MESSAGE : SHORT_MESSAGE,
    });
    await this.writer.write(filepath, content);
    console.log(`${message.message} : ${message.timestamp} `);
  }
}

class FileHandler {
  private fetcher: IFileFetcher;
  private parser: IParser;
  private processor: IMessage;

  constructor(fetcher: IFileFetcher, parser: IParser, processor: IMessage) {
    this.fetcher = fetcher;
    this.parser = parser;
    this.processor = processor;
  }

  async handle(inputFile: string, outputFile: string): Promise<void> {
    try {
      const content = await this.fetcher.fetch(inputFile);
      const messages = this.parser.parse(content);
      const waitGroup = messages.map((message) =>
        this.processor.send(message, outputFile)
      );
      await Promise.all(waitGroup);
    } catch (error) {
      console.error(`Error processing file ${inputFile}: ${error}`);
    }
  }
}

const main = async () => {
  const files = {
    "file1.txt": "out1.txt",
    "file2.txt": "out2.txt",
    "file3.txt": "out3.txt",
  };

  const fetcher = new FileFetch();
  const writer = new FileWriter();
  const parser = new Parser();
  const processor = new ParserMessage(writer);
  const handler = new FileHandler(fetcher, parser, processor);

  const waitGroup = Object.entries(files).map(([input, output]) =>
    handler.handle(input, output)
  );
  await Promise.all(waitGroup);
};

main();

When I try to login admin its says Connection Refuse and Post request error [closed]

I have a University Dashboard and in that I have some logins such as Admin Login, student login etc. But when I try to put username and passward then its says in inspect POST net::ERR_CONNECTION_REFUSED and message: ‘Network Error’, name: ‘AxiosError’, code: ‘ERR_NETWORK’..
And in the backend side I use MySql and I also provide the database connection but this error happens.

I expecting it will give me login successfully or login.

Aligning Buttons at the Same Line with Tabs in React using Ant Design

I am designing a website, and I need to align buttons and tabs at the same line. When I implement following structure, it does work, but when I add the <Table/> component as children, it does not work.

My first code and its output:

     <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
        <Tabs defaultActiveKey="1" items={[{ label: 'test', key: 'test', children: 'test' }]} />

        <div>
          <Button type="primary" style={{ marginRight: '8px' }}>Add New</Button>
          <Button>Another Button</Button>
        </div>
      </div>

tabs and buttons are at the same line

But when I add a table, it is like that:

     <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
        <Tabs defaultActiveKey="1" items={[{ label: 'test', key: 'test', children: <Table/> }]} />

        <div>
          <Button type="primary" style={{ marginRight: '8px' }}>Add New</Button>
          <Button>Another Button</Button>
        </div>
      </div>

table ruins the structure

How can I fix that problem?

How to log out user from Auth0 if token refresh fails in Next.js using Axios interceptor?

I’m using the Auth0 SDK in my Next.js application to manage authentication, and I’ve set up an Axios interceptor to handle refreshing the access token automatically when it expires. Here’s the basic setup I have for the Axios interceptor:

async function refreshAccessToken() {
  try {
    const { data } = await axios.get(REFRESH_ACCESS_TOKEN_API);
    const { access_token } = data;
    return {
      access_token,
    };
  } catch (error) {
    throw error;
  }
}

export function setupResponseInterceptor(axiosInstance: AxiosInstance) {
  axiosInstance.interceptors.response.use(
    response => response,
    async error => {
      const originalRequest = error.config;
      if (axios.isAxiosError(error) && error.response?.status === 401) {
        if (!isAlreadyFetchingAccessToken) {
          isAlreadyFetchingAccessToken = true;
          try {
            refreshAccessToken().then(res => {
              
            });
          } catch (err) {
            return Promise.reject(err);
          }
        }
        const retryOriginalRequest = new Promise(resolve => {
          addSubscriber((accessToken: any) => {
            originalRequest.headers.Authorization = `Bearer ${accessToken}`;
            resolve(axios(originalRequest));
          });
        });
        return retryOriginalRequest;
      }

      throw error;
    },
  );
}

What I Tried:

I set up an Axios interceptor in my Next.js application to automatically refresh the Auth0 access token when a 401 error occurs. In the interceptor, I attempted to refresh the token using a custom function (refreshAuthToken()). The token refresh generally works, but I’m unsure how to handle scenarios where the token refresh fails. Specifically, I haven’t been able to successfully log out the user from Auth0 when the refresh attempt fails.

What I Expected:

I was expecting to find a way to log out the user from Auth0 within the Axios interceptor if the token refresh fails. Ideally, I want the user to be redirected to a specific URL (e.g., the home page) after being logged out. I need guidance on how to properly invoke the Auth0 logout function in this context and any best practices for handling such failures gracefully.

Improving hover precision on peaks in Plotly.js graphs

Content
I’m working on a project using Plotly.js (version X.X.X) to display frequency data with peaks. I’m encountering an issue with the hover functionality when trying to select specific peaks on the graph.
Current Setup

Using Plotly.js with hovermode: ‘closest’
Graph displays frequency data with multiple peaks
Users need to select specific peaks for further analysis

Issue
When users try to hover over a specific peak, the selected point (indicated by the hover info) often doesn’t align precisely with the cursor position. This makes it difficult for users to select the exact peak they want, especially in dense areas of the graph.
Current Behavior

Hover selects the ‘closest’ point, but this isn’t always the point directly under the cursor
Users have to move the cursor around carefully to select the desired peak
The discrepancy between cursor position and selected point is noticeable and frustrating for users

Desired Behavior

More precise hovering, where the selected point aligns more closely with the cursor position
Easier selection of specific peaks, especially in dense areas of the graph

Question

Is there a way to improve the precision of the hover functionality in Plotly.js, particularly for selecting peaks?
Are there any configuration options or workarounds to make the hover selection more accurate?
If precise hovering is a limitation of Plotly.js, are there any recommended strategies to improve the user experience for peak selection?

Additional Information

We’re constrained to using Plotly.js for this project, so switching to a different library isn’t an option at this time.
Any solutions that can be implemented within Plotly.js or with minimal additional JavaScript would be ideal.

Thank you in advance for any insights or solutions you can provide!

Sending form Information to Email for Contact Page [duplicate]

Hello this is a code I wrote for my contact page. I would like to send the information inputted by the user to the email ([email protected]) whenever they click the button send. The form should also reset whenever they click the button send

This is my whole source code including the css and javascript

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Contact Form</title>
    <link rel="stylesheet" href="style.css" />
    <script
      src="https://kit.fontawesome.com/64d58efce2.js"
      crossorigin="anonymous"
    ></script>
  </head>

  <style>
    @import url("https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
input,
textarea {
  font-family: "Poppins", sans-serif;
}

.container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  padding: 2rem;
  background-color: #fafafa;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form {
  width: 100%;
  max-width: 820px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  overflow: hidden;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.contact-form {
  background-color: #1abc9c;
  position: relative;
}

.circle {
  border-radius: 50%;
  background: linear-gradient(135deg, transparent 20%, #149279);
  position: absolute;
}

.circle.one {
  width: 130px;
  height: 130px;
  top: 130px;
  right: -40px;
}

.circle.two {
  width: 80px;
  height: 80px;
  top: 10px;
  right: 30px;
}

.contact-form:before {
  content: "";
  position: absolute;
  width: 26px;
  height: 26px;
  background-color: #1abc9c;
  transform: rotate(45deg);
  top: 50px;
  left: -13px;
}

form {
  padding: 2.3rem 2.2rem;
  z-index: 10;
  overflow: hidden;
  position: relative;
}

.title {
  color: #fff;
  font-weight: 500;
  font-size: 1.5rem;
  line-height: 1;
  margin-bottom: 0.7rem;
}

.input-container {
  position: relative;
  margin: 1rem 0;
}

.input {
  width: 100%;
  outline: none;
  border: 2px solid #fafafa;
  background: none;
  padding: 0.6rem 1.2rem;
  color: #fff;
  font-weight: 500;
  font-size: 0.95rem;
  letter-spacing: 0.5px;
  border-radius: 25px;
  transition: 0.3s;
}

textarea.input {
  padding: 0.8rem 1.2rem;
  min-height: 150px;
  border-radius: 22px;
  resize: none;
  overflow-y: auto;
}

.input-container label {
  position: absolute;
  top: 50%;
  left: 15px;
  transform: translateY(-50%);
  padding: 0 0.4rem;
  color: #fafafa;
  font-size: 0.9rem;
  font-weight: 400;
  pointer-events: none;
  z-index: 1000;
  transition: 0.5s;
}

.input-container.textarea label {
  top: 1rem;
  transform: translateY(0);
}

.btn {
  padding: 0.6rem 1.3rem;
  background-color: #fff;
  border: 2px solid #fafafa;
  font-size: 0.95rem;
  color: #1abc9c;
  line-height: 1;
  border-radius: 25px;
  outline: none;
  cursor: pointer;
  transition: 0.3s;
  margin: 0;
}

.btn:hover {
  background-color: transparent;
  color: #fff;
}

.input-container span {
  position: absolute;
  top: 0;
  left: 25px;
  transform: translateY(-50%);
  font-size: 0.8rem;
  padding: 0 0.4rem;
  color: transparent;
  pointer-events: none;
  z-index: 500;
}

.input-container span:before,
.input-container span:after {
  content: "";
  position: absolute;
  width: 10%;
  opacity: 0;
  transition: 0.3s;
  height: 5px;
  background-color: #1abc9c;
  top: 50%;
  transform: translateY(-50%);
}

.input-container span:before {
  left: 50%;
}

.input-container span:after {
  right: 50%;
}

.input-container.focus label {
  top: 0;
  transform: translateY(-50%);
  left: 25px;
  font-size: 0.8rem;
}

.input-container.focus span:before,
.input-container.focus span:after {
  width: 50%;
  opacity: 1;
}

.contact-info {
  padding: 2.3rem 2.2rem;
  position: relative;
}

.contact-info .title {
  color: #1abc9c;
}

.text {
  color: #333;
  margin: 1.5rem 0 2rem 0;
}

.information {
  display: flex;
  color: #555;
  margin: 0.7rem 0;
  align-items: center;
  font-size: 0.95rem;
}

.icon {
  width: 28px;
  margin-right: 0.7rem;
}

.social-media {
  padding: 2rem 0 0 0;
}

.social-media p {
  color: #333;
}

.social-icons {
  display: flex;
  margin-top: 0.5rem;
}

.social-icons a {
  width: 35px;
  height: 35px;
  border-radius: 5px;
  background: linear-gradient(45deg, #1abc9c, #149279);
  color: #fff;
  text-align: center;
  line-height: 35px;
  margin-right: 0.5rem;
  transition: 0.3s;
}

.social-icons a:hover {
  transform: scale(1.05);
}

.contact-info:before {
  content: "";
  position: absolute;
  width: 110px;
  height: 100px;
  border: 22px solid #1abc9c;
  border-radius: 50%;
  bottom: -77px;
  right: 50px;
  opacity: 0.3;
}

.big-circle {
  position: absolute;
  width: 500px;
  height: 500px;
  border-radius: 50%;
  background: linear-gradient(to bottom, #1cd4af, #159b80);
  bottom: 50%;
  right: 50%;
  transform: translate(-40%, 38%);
}

.big-circle:after {
  content: "";
  position: absolute;
  width: 360px;
  height: 360px;
  background-color: #fafafa;
  border-radius: 50%;
  top: calc(50% - 180px);
  left: calc(50% - 180px);
}

.square {
  position: absolute;
  height: 400px;
  top: 50%;
  left: 50%;
  transform: translate(181%, 11%);
  opacity: 0.2;
}

@media (max-width: 850px) {
  .form {
    grid-template-columns: 1fr;
  }

  .contact-info:before {
    bottom: initial;
    top: -75px;
    right: 65px;
    transform: scale(0.95);
  }

  .contact-form:before {
    top: -13px;
    left: initial;
    right: 70px;
  }

  .square {
    transform: translate(140%, 43%);
    height: 350px;
  }

  .big-circle {
    bottom: 75%;
    transform: scale(0.9) translate(-40%, 30%);
    right: 50%;
  }

  .text {
    margin: 1rem 0 1.5rem 0;
  }

  .social-media {
    padding: 1.5rem 0 0 0;
  }
}

@media (max-width: 480px) {
  .container {
    padding: 1.5rem;
  }

  .contact-info:before {
    display: none;
  }

  .square,
  .big-circle {
    display: none;
  }

  form,
  .contact-info {
    padding: 1.7rem 1.6rem;
  }

  .text,
  .information,
  .social-media p {
    font-size: 0.8rem;
  }

  .title {
    font-size: 1.15rem;
  }

  .social-icons a {
    width: 30px;
    height: 30px;
    line-height: 30px;
  }

  .icon {
    width: 23px;
  }

  .input {
    padding: 0.45rem 1.2rem;
  }

  .btn {
    padding: 0.45rem 1.2rem;
  }
}
  </style>
  
  <body>
    <div class="container">
      <span class="big-circle"></span>
      <img src="img/shape.png" class="square" alt="" />
      <div class="form">
        <div class="contact-info">
          <h3 class="title">Let's get in touch</h3>
          <p class="text">
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe
            dolorum adipisci recusandae praesentium dicta!
          </p>

          <div class="info">
            <div class="information">
              <img src="img/location.png" class="icon" alt="" />
              <p>92 Cherry Drive Uniondale, NY 11553</p>
            </div>
            <div class="information">
              <img src="img/email.png" class="icon" alt="" />
              <p>[email protected]</p>
            </div>
            <div class="information">
              <img src="img/phone.png" class="icon" alt="" />
              <p>123-456-789</p>
            </div>
          </div>

          <div class="social-media">
            <p>Connect with us :</p>
            <div class="social-icons">
              <a href="#">
                <i class="fab fa-facebook-f"></i>
              </a>
              <a href="#">
                <i class="fab fa-twitter"></i>
              </a>
              <a href="#">
                <i class="fab fa-instagram"></i>
              </a>
              <a href="#">
                <i class="fab fa-linkedin-in"></i>
              </a>
            </div>
          </div>
        </div>

        <div class="contact-form">
          <span class="circle one"></span>
          <span class="circle two"></span>

          <form action="index.html" autocomplete="off">
            <h3 class="title">Contact us</h3>
            <div class="input-container">
              <input type="text" name="name" class="input" />
              <label for="">Username</label>
              <span>Username</span>
            </div>
            <div class="input-container">
              <input type="email" name="email" class="input" />
              <label for="">Email</label>
              <span>Email</span>
            </div>
            <div class="input-container">
              <input type="tel" name="phone" class="input" />
              <label for="">Phone</label>
              <span>Phone</span>
            </div>
            <div class="input-container textarea">
              <textarea name="message" class="input"></textarea>
              <label for="">Message</label>
              <span>Message</span>
            </div>
            <input type="submit" value="Send" class="btn" />
          </form>
        </div>
      </div>
    </div>

    <script>
         const inputs = document.querySelectorAll(".input");

            function focusFunc() {
            let parent = this.parentNode;
            parent.classList.add("focus");
            }

            function blurFunc() {
            let parent = this.parentNode;
            if (this.value == "") {
                parent.classList.remove("focus");
            }
            }

            inputs.forEach((input) => {
            input.addEventListener("focus", focusFunc);
            input.addEventListener("blur", blurFunc);
            });
    </script>

  </body>
</html>

Adding CSS styles to dynamically created HTML elements in JavaScript [duplicate]

I’m working on a Django project and I have an index.html file where I’ve connected a JavaScript file using the following script tag:

<script src="{% static 'assets/js/bubble.js' %}"></script>

In my JavaScript file, I have the following code:

console.log("Bubble");

// Get the speech bubble container
const speechBubbleContainer = document.querySelector('.speech-bubble-container');

// Function to create a speech bubble
function createSpeechBubble(message) {
  const speechBubble = document.createElement('div');
  speechBubble.style = `
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    font-size: 16px;
    font-weight: bold;
    color: #333;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    opacity: 1;
    transition: opacity 2s;
  `;
  speechBubble.textContent = message;

  speechBubbleContainer.appendChild(speechBubble);

  // Remove the speech bubble after 2 seconds
  setTimeout(() => {
    speechBubble.style.opacity = 0;
    setTimeout(() => {
      speechBubble.remove();
    }, 2000);
  }, 2000);
}

// Create a speech bubble every 30 seconds
setInterval(() => {
  createSpeechBubble('Hi');
}, 3000);

And here’s my HTML code:

<div class="floating-button" style="..."> <!-- button styles -->
  <img src="..." alt="Button Image" style="..."> <!-- image styles -->
  <div class="speech-bubble-container" style="..."></div>
</div>

I want to add CSS styles to the dynamically created speech-bubble elements, but I’m not sure how to do it. I’ve tried adding the styles directly to the HTML elements, but it’s not working as expected.

Can someone help me figure out how to add the CSS styles to the dynamically created speech-bubble elements?

Edit: I’ve tried adding the styles directly to the JavaScript code like this:

speechBubble.style = `
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  animation: fadeOut 2s forwards;
`;

But I’m not sure if this is the best approach, and I’m still having issues with the animation. Any help would be appreciated!

A regex to test whether an input contains two specified strings and the part between them does not contain any element of the set of specified strings

Given two strings (denoted by A and B) and a set N of strings, I need to write a regular expression to test whether a given input string W contains a substring S, where S is any substring that satisfies all of the following three conditions: 1. starts with A; 2. ends with B; 3. any element of N does not occur in the part between A and B (this part does not overlap with A and B).

For example, I chose "ab" as A, "bc" as B, ["a", "cb", "cd"] as N. If "ec" is the inner part, then "abecbc" is the string that satisfies all of the three conditions: if W contains such a substring, the regex must return true. My first variant is the following regex:

var T = /(?=ab.*bc)(?=(?!ab.*a.*bc))(?=(?!ab.*cb.*bc))(?=(?!ab.*cd.*bc))/;  

I chose W = S = "abecbc". This regex works as expected:

T.test("abecbc");
// true

But I am interested in the following problem: how to write a functionally equivalent regex without using the positive lookahead (?=) as the AND operator?

So my second variant is the following:

var R = /ab(?!.*?(?:a|cb|cd).*)bc/;

But R.test("abecbc") evaluates to false. So let us split R into three parts:

/ab(.*)/.test("abecbc")

returns true.

Then

/(.*)bc/.test("abecbc")

returns true.

The inner part (i.e. the part between "ab" and "bc") is "ec". And

/(?!.*?(?:a|cb|cd).*)/.test("ec")

returns true, which is expected. So there must be three truths, and there are no more parts in R. Then why does

/ab(?!.*?(?:a|cb|cd).*)bc/.test("abecbc")

evaluate to false? And how to write a correct regex that solves the problem described in the first paragraph of the post without using the positive lookahead (?=) as the AND operator?

TradingView JS – UNIX timestamp data error when passing from PHP

I’m working with TradingView.js

https://github.com/tradingview/lightweight-charts

https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js

When I format data with yyyy-mm-dd format it works fine. When I try to use UNIX time, which is supported in their documentation, the data doesn’t format. Can’t figure out why

const chart = LightweightCharts.createChart(document.getElementById('chart'), {
width: 600,
height: 300,
timeScale: {
    timeVisible: true,
    secondsVisible: true,
},
});

const lineSeries = chart.addLineSeries();

var examplePrices = [{ time: '2019-04-11', value: 80.01 },
    { time: '2019-04-12', value: 96.63 },
    { time: '2019-04-13', value: 76.64 },
    { time: '2019-04-14', value: 81.89 },
    { time: '2019-04-15', value: 74.43 },
    { time: '2019-04-16', value: 80.01 },
    { time: '2019-04-17', value: 96.63 },
    { time: '2019-04-18', value: 76.64 },
    { time: '2019-04-19', value: 81.89 },
    { time: '2019-04-20', value: 74.43 }];


var fiveDayPrices = [{"time":1725463800,"value":408.76},{"time":1725462000,"value":409.60}];

//lineSeries.setData(examplePrices);
lineSeries.setData(fiveDayPrices);

Here is how I’m generating the fiveDayPrices data with PHP

<?php

        $fiveDayPricesAndTimes = array();
        foreach($fiveDayStockPrices as $index => $dailyPriceInterval){
            $priceTime = strtotime($dailyPriceInterval["datetime"]); // This is already in seconds
            $priceValue = $dailyPriceInterval["close"];
            $fiveDayPricesAndTimes[$index]["time"] = intval($priceTime); // Now in seconds
            $fiveDayPricesAndTimes[$index]["value"] = floatval($priceValue);
        }
        
        $fiveDayPricesAndTimes = json_encode($fiveDayPricesAndTimes, true);

?>

SvelteKit Router Not Generating Routes After Build

I am currently working on a mini web app and trying to deploy it to a VM. Everything works fine via npm run dev, but routes do not work when running VS Code live server on the dist after npm run build or npx serve dist in the root directory.

The only way I can get any routes besides the root to work is via npx serve dist --single.

I also want to note that specific route directories are not generated in the dist folder after npm run build. Here is my current directory structure under src.

src
├── app.d.ts
├── app.html
├── globals.css
├── lib
│   └── components
│       ├── Image.svelte
│       ├── Light.svelte
│       └── ThreeJSWindow.svelte
└── routes
    ├── +layout.svelte
    ├── +page.svelte
    ├── tree
    │   └── +page.svelte
    └── v1
        └── +page.svelte

No directories are generated in dist corresponding to the /tree or /v1 routes.

My main goal is to deploy this to a VM as a static html server using nginx without having to configure this as a node server. I tried doing that and could not get it working either.

I figure if I cannot run this app via live server in the dist directory, I should not try deploying it yet.

I originally assumed that this was an issue with my svelte.config.js file, but nothing has worked so far:

import adapter from '@sveltejs/adapter-static';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  kit: {
    adapter: adapter({
      pages: 'dist', 
      assets: 'dist',
      fallback: 'index.html', 
    }),
    paths: {
      base: '', 
    },
    prerender: {
      entries: ['*'],  
    },
  },
  preprocess: vitePreprocess(),
};

export default config;

Is there any way/candy/library to run async function in sync code block in init progress

First thing of first: Only in startup/init progress. I’m not trying find something to break the world.

I have do some research with js promise and await/async. And found something like this

Here is a demo in kotlin:

suspend fun readFile(path: Path) = withContext(Dispatchers.IO) {
  Files.readString(path)
}!!

fun main() {
  val runtimeInfo = runBlocking {
    val config = readFile(Paths.get("config.properties")) // suspend async code
    return@runBlocking MyFramework.RuntimeInfo.of(config) // Another async code
  }
  MyFramework.service(runtimeInfo) {
    withContext(Dispatchers.IO) {
      Files.readString(Paths.get("foo-bar"))
    }
  }
}

But in JS/TS, Things not that easy (BTW: I’m using Tauri + React):

new Promise((resolve, reject) => {

  // Tauri invoke return a promise.
  invoke('read_file', {path: 'config.json', defaultConfig: '{"version":1}'})
    .then(it => resolve(it))
    .catch(it => reject(it));
  // ↑ This is really easy to make mistake (typo/forget)
  // And this is really bad feeling with it: promise in promosie

}).then(it => {

  const runtime = something(it as string);

  ReactDOM.createRoot(document.getElementById("root")!!).render(
    <React.StrictMode>
      <App runtime={runtime}/>
    </React.StrictMode>
  );

}).catch((reject) => {
  alert(reject);
});

Question: Is there any elegant way to archive async/sync conversion in JS/TS?

Threejs with gsap zoon phone carousel react-three/fiber

How would I go about creating this type of 3D phone carousel.
enter image description here

I would need to create prev/next buttons — to control the direction – would have all the phones render within a limited width canvas. How to control the phone zooming in and out using gsap ?

This version here – uses threejs and renders the video in the phones – but something is happening with the references – and its only rendering the same video, but upside down? I am unsure on active slide how to zoom the phone in to make it pop the same.

https://codesandbox.io/p/sandbox/r3f-scroll-rig-sticky-box-forked-ths46t

import React, { useRef, useState, useEffect } from 'react'
import { Canvas, useThree } from '@react-three/fiber'
import { useGLTF, OrbitControls } from '@react-three/drei'
import gsap from 'gsap'
import * as THREE from 'three'

// Import Swiper React components
import { Swiper, SwiperSlide } from 'swiper/react'

// Import Swiper styles
import 'swiper/css'
import 'swiper/css/pagination'

// import required modules
import { Pagination } from 'swiper/modules'

import './styles.css'

const IphoneModel = (mediaAsset) => {
  const group = useRef()
  const { nodes, materials } = useGLTF('/Iphone15.glb')

  useEffect(() => {
    const video = document.createElement('video')
    video.src = mediaAsset.mediaAsset.videoUrl
    video.crossOrigin = 'anonymous'
    video.loop = true
    video.muted = true
    video.play()

    const videoTexture = new THREE.VideoTexture(video)
    videoTexture.minFilter = THREE.LinearFilter
    videoTexture.magFilter = THREE.LinearFilter
    videoTexture.encoding = THREE.sRGBEncoding

    materials.Screen.map = videoTexture
    materials.Screen.needsUpdate = true
  }, [materials.Screen])

  return (
    <group ref={group} dispose={null} scale={0.2} rotation={[Math.PI / 2, 0, Math.PI * 2]}>
      <mesh geometry={nodes.M_Cameras.geometry} material={materials.cam} />
      <mesh geometry={nodes.M_Glass.geometry} material={materials['glass.001']} />
      <mesh geometry={nodes.M_Metal_Rough.geometry} material={materials.metal_rough} />
      <mesh geometry={nodes.M_Metal_Shiny.geometry} material={materials.metal_Shiny} />
      <mesh geometry={nodes.M_Plastic.geometry} material={materials.metal_rough} />
      <mesh geometry={nodes.M_Portal.geometry} material={materials['M_Base.001']} />
      <mesh geometry={nodes.M_Screen.geometry} material={materials.Screen} />
      <mesh geometry={nodes.M_Speakers.geometry} material={materials.metal_rough} />
      <mesh geometry={nodes.M_USB.geometry} material={materials.metal_rough} />
    </group>
  )
}

const Background = () => {
  const { scene } = useThree()
  useEffect(() => {
    scene.background = new THREE.Color('#555555')
  }, [scene])

  return null
}

const ThreeScene = (mediaAsset) => {
  const phone = useRef()
  return (
    <div ref={phone} style={{ width: '100vw', height: '500px' }}>
      <Canvas camera={{ position: [0, 0, 10], fov: 45 }} gl={{ antialias: true, alpha: false }}>
        <ambientLight intensity={0.4} />
        <directionalLight position={[5, 10, 7.5]} intensity={1} />
        <IphoneModel mediaAsset={mediaAsset.mediaAsset} />
        <Background />
      </Canvas>
    </div>
  )
}

const App = () => {
  let items = [
    { videoUrl: 'https://cdn.pixabay.com/video/2024/07/14/221180_tiny.mp4' },
    { videoUrl: 'https://cdn.pixabay.com/video/2024/08/30/228847_large.mp4' },
    {
      videoUrl: 'https://cdn.pixabay.com/video/2020/06/04/41127-427876264_large.mp4'
    },
    {
      videoUrl: 'https://cdn.pixabay.com/video/2020/06/04/41128-427876270_large.mp4'
    },
    { videoUrl: 'https://cdn.pixabay.com/video/2024/07/14/221180_tiny.mp4' },
    { videoUrl: 'https://cdn.pixabay.com/video/2024/08/30/228847_large.mp4' },
    {
      videoUrl: 'https://cdn.pixabay.com/video/2020/06/04/41127-427876264_large.mp4'
    },
    {
      videoUrl: 'https://cdn.pixabay.com/video/2020/06/04/41128-427876270_large.mp4'
    }
  ]

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '400vh' }}>
      <div className="swiperWrapper">
        <Swiper
          slidesPerView={3}
          spaceBetween={30}
          pagination={{
            clickable: true
          }}
          modules={[Pagination]}
          className="mySwiper">
          {items.map((item, i) => {
            return (
              <SwiperSlide key={i}>
                <ThreeScene mediaAsset={item} />
              </SwiperSlide>
            )
          })}
        </Swiper>
      </div>
    </div>
  )
}

export default App

this renders one phone with the video in a scroll trigger

https://codesandbox.io/p/sandbox/r3f-scroll-rig-sticky-box-forked-jns24q

app.js

import React, { useRef, useEffect } from 'react'
import { Canvas, useThree } from '@react-three/fiber'
import { useGLTF, OrbitControls } from '@react-three/drei'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import * as THREE from 'three'

gsap.registerPlugin(ScrollTrigger)

const IphoneModel = () => {
  const group = useRef()
  const { nodes, materials } = useGLTF('/Iphone15.glb')

  useEffect(() => {
    const video = document.createElement('video')
    video.src = 'https://cdn.pixabay.com/video/2024/07/14/221180_tiny.mp4'
    video.crossOrigin = 'anonymous'
    video.loop = true
    video.muted = true
    video.play()

    const videoTexture = new THREE.VideoTexture(video)
    videoTexture.minFilter = THREE.LinearFilter
    videoTexture.magFilter = THREE.LinearFilter
    videoTexture.encoding = THREE.sRGBEncoding

    materials.Screen.map = videoTexture
    materials.Screen.needsUpdate = true

    const tl = gsap.timeline({
      scrollTrigger: {
        trigger: '#three-canvas-container',
        scrub: 1,
        markers: true,
        pin: true,
        start: 'top top',
        end: 'bottom top'
      }
    })

    tl.to(group.current.rotation, { z: Math.PI * 2, duration: 2 })
  }, [materials.Screen])

  return (
    <group ref={group} dispose={null} scale={0.2} rotation={[Math.PI / 2, 0, -Math.PI / 8]}>
      <mesh geometry={nodes.M_Cameras.geometry} material={materials.cam} />
      <mesh geometry={nodes.M_Glass.geometry} material={materials['glass.001']} />
      <mesh geometry={nodes.M_Metal_Rough.geometry} material={materials.metal_rough} />
      <mesh geometry={nodes.M_Metal_Shiny.geometry} material={materials.metal_Shiny} />
      <mesh geometry={nodes.M_Plastic.geometry} material={materials.metal_rough} />
      <mesh geometry={nodes.M_Portal.geometry} material={materials['M_Base.001']} />
      <mesh geometry={nodes.M_Screen.geometry} material={materials.Screen} />
      <mesh geometry={nodes.M_Speakers.geometry} material={materials.metal_rough} />
      <mesh geometry={nodes.M_USB.geometry} material={materials.metal_rough} />
    </group>
  )
}

const Background = () => {
  const { scene } = useThree()
  useEffect(() => {
    scene.background = new THREE.Color('#555555')
  }, [scene])

  return null
}

const TextSection = () => {
  const textRefs = useRef([])

  useEffect(() => {
    gsap.fromTo(
      textRefs.current,
      { opacity: 0 },
      {
        opacity: 1,
        stagger: 0.1,
        scrollTrigger: {
          trigger: '#text-trigger',
          start: 'top bottom',
          end: 'center center',
          scrub: 1,
          markers: false
        }
      }
    )
  }, [])

  const texts = ['Ready 5', 'Ready 4', 'Ready 3', 'Ready 2', 'Ready 1']

  return (
    <div
      id="text-trigger"
      style={{
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        position: 'relative',
        top: '500px'
      }}>
      {texts.map((text, index) => (
        <h1 key={index} ref={(el) => (textRefs.current[index] = el)} style={{ opacity: 0 }}>
          {text}
        </h1>
      ))}
    </div>
  )
}

const ThreeScene = () => (
  <div id="three-canvas-container" style={{ width: '100vw', height: '500px' }}>
    <Canvas camera={{ position: [0, 0, 10], fov: 45 }} gl={{ antialias: true, alpha: false }}>
      <ambientLight intensity={0.4} />
      <directionalLight position={[5, 10, 7.5]} intensity={1} />
      <IphoneModel />
      <OrbitControls enableZoom={false} />
      <Background />
    </Canvas>
  </div>
)

const App = () => (
  <div style={{ display: 'flex', flexDirection: 'column', height: '400vh' }}>
    <div className="some-content" style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <h1>ACTION</h1>
    </div>
    <ThreeScene />
    <TextSection />
  </div>
)

export default App

I’ve seen this code that may use a combination of swiper and gsap?

import { useInView } from 'framer-motion';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/dist/ScrollTrigger';
import { useEffect, useRef, useState } from 'react';
import Swiper from 'swiper';
import 'swiper/css';
import { SwiperOptions } from 'swiper/types';

import { Asset, AssetCollection, AssetFragment, Maybe, Sys } from '~/cms';
import { CMSImage } from '~/components/ui';
import { useIsLandscape } from '~/hooks';
import { cx } from '~/utils';

import VideoAltText from '../VideoAltText';
import styles from './PhoneCarousel.module.scss';

ScrollTrigger.config({
  ignoreMobileResize: true,
});

gsap.registerPlugin(ScrollTrigger);

const PhoneCarousel = ({
  items,
  scrollTriggerElement,
  scrollTriggerStart,
  scrollTriggerEnd,
}: {
  items:
    | (Pick<Asset, 'contentType' | 'url' | 'description' | 'width' | 'height'> & {
        sys: Pick<Sys, 'id'>;
      })[];
  scrollTriggerElement?: HTMLElement | string;
  scrollTriggerStart?: string;
  scrollTriggerEnd?: string;
}) => {
  const carouselElementRef = useRef<HTMLDivElement | null>(null);
  const carouselRef = useRef<Swiper | null>(null);
  const [currentItems, setCurrentItems] = useState([...items, ...items]);
  // const currentItems = useRef(ITEMS);
  const [resizeKey, setResizeKey] = useState<number | null>(null);
  const [activeIndex, setActiveIndex] = useState(items?.length);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const navigationRef = useRef<HTMLDivElement | null>(null);
  const buttonsRef = useRef<HTMLDivElement | null>(null);
  const slidesChangedTimeout = useRef<ReturnType<typeof setTimeout> | null>();
  const remountTimeout = useRef<ReturnType<typeof setTimeout> | null>();
  const isInView = useInView(containerRef, { margin: '1000px 0px 1000px 0px' });
  const isDesktop = useIsLandscape();
  const [sliderInitialized, setSliderInitialized] = useState(false);
  const timelineRef = useRef<GSAPTimeline | null>(null);
  const scrollTrigger = useRef<ScrollTrigger>();
  const swiperInstance = useRef<any>(null);
  const [scrollTriggerComplete, setScrollTriggerComplete] = useState(false);
  const hasDoneMobileSlideHack = useRef(false);

  useEffect(() => {
    if (
      !sliderInitialized ||
      !containerRef.current ||
      !buttonsRef.current ||
      !navigationRef.current
    )
      return;

    if (scrollTrigger.current) {
      scrollTrigger.current.kill();
    }

    if (timelineRef.current) {
      timelineRef.current.kill();
    }

    const queryClass = styles.phoneContainerInner;
    const allInnerItems = containerRef.current.querySelectorAll(`.${queryClass}`);
    allInnerItems.forEach((el) => {
      if (el) {
        gsap.set(el, { clearProps: 'all' });
      }
    });

    gsap.set([buttonsRef.current, navigationRef.current], { clearProps: 'all' });

    if (!swiperInstance.current?.slides?.length) return;

    const leftItem = swiperInstance.current.slides[swiperInstance.current.activeIndex - 1];
    const centerItem = swiperInstance.current.slides[swiperInstance.current.activeIndex];
    const rightItem = swiperInstance.current.slides[swiperInstance.current.activeIndex + 1];

    // if (!leftItem || !centerItem || !rightItem) return;

    const items = [leftItem, centerItem, rightItem];
    const innerItems: any = [];
    items.forEach((el) => {
      if (!el) return;
      const innerDiv = el.querySelectorAll(`.${queryClass}`)[0];
      if (innerDiv) {
        innerItems.push(innerDiv);
      }
    });

    if (!isDesktop || scrollTriggerComplete) return;

    timelineRef.current = gsap.timeline();

    timelineRef.current.fromTo(
      innerItems,
      {
        y: 175,
      },
      {
        y: 0,
        stagger: 0.1,
      }
    );

    timelineRef.current.fromTo(
      [buttonsRef.current, navigationRef.current],
      {
        autoAlpha: 0,
      },
      {
        autoAlpha: 1,
      }
    );

    scrollTrigger.current = new ScrollTrigger({
      trigger: scrollTriggerElement ? scrollTriggerElement : containerRef.current,
      start: scrollTriggerStart ? scrollTriggerStart : 'top bottom',
      end: scrollTriggerEnd ? scrollTriggerEnd : `bottom+=${window.innerHeight * 0.3} bottom`,
      animation: timelineRef.current,
      scrub: true,
      onLeave: () => {
        setScrollTriggerComplete(true);
      },
    });
  }, [
    sliderInitialized,
    isDesktop,
    scrollTriggerElement,
    scrollTriggerStart,
    scrollTriggerEnd,
    scrollTriggerComplete,
  ]);

  useEffect(() => {
    return () => {
      if (scrollTrigger.current) {
        scrollTrigger.current.kill();
      }

      if (timelineRef.current) {
        timelineRef.current.kill();
      }
    };
  }, []);

  useEffect(() => {
    if (!items?.length) return;

    if (isDesktop) {
      setCurrentItems([...items, ...items]);
    } else {
      setCurrentItems(items);
    }
  }, [isDesktop, items]);

  useEffect(() => {
    return;
    if (!sliderInitialized) return;
    if (swiperInstance.current?.slides?.length && !isDesktop && !hasDoneMobileSlideHack.current) {
      hasDoneMobileSlideHack.current = true;
      const interval = 10;
      swiperInstance.current.slides.forEach((_: any, i: number) => {
        setTimeout(() => {
          swiperInstance.current.slideTo(i, 0);

          setTimeout(() => {
            if (i === swiperInstance.current.slides.length - 1) {
              swiperInstance.current.slideTo(0, 0);
            }
          }, interval);
        }, i * interval);
      });
    }
  }, [isDesktop, sliderInitialized]);

  useEffect(() => {
    if (!isInView || !containerRef.current) return;

    const videos = containerRef.current.querySelectorAll('video');
    if (videos.length) {
      videos.forEach((el) => {
        if (!el) return;
        // el.src = el.dataset.src || '';
        // el.load();
      });

      if (carouselRef?.current?.slides?.length) {
        carouselRef.current.slides.forEach((el) => {
          const video = el.querySelectorAll('video')[0];
          if (el.classList.contains('swiper-slide-active') && video) {
            video.play();
          }
        });
      }
    }
  }, [isInView, isDesktop]);

  useEffect(() => {
    const handleResize = () => {
      setResizeKey(new Date().getTime());
    };

    window.removeEventListener('resize', handleResize);

    if (!isDesktop) return;

    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [isDesktop]);

  useEffect(() => {
    if (!carouselElementRef.current) return;

    if (remountTimeout.current) {
      clearTimeout(remountTimeout.current);
    }

    setSliderInitialized(false);

    if (carouselRef.current) {
      carouselRef.current.destroy();
    }

    remountTimeout.current = setTimeout(() => {
      const onSlideChange = (swiper: any) => {
        setActiveIndex(swiper.realIndex);

        if (slidesChangedTimeout.current) {
          clearTimeout(slidesChangedTimeout.current);
        }

        slidesChangedTimeout.current = setTimeout(() => {
          if (!swiper?.slides?.length) return;
          swiper.slides.forEach((el: any) => {
            const video = el.querySelectorAll('video')[0] as HTMLVideoElement | undefined;
            if (!video) return;
            if (el.classList.contains('swiper-slide-active')) {
              video.playbackRate = 1;
              video.play();
            } else {
              // Using playbackrate instead of pause to prevent the blackscreen issue in safari
              video.playbackRate = 0;
              video.play();
            }
          });
        }, 0);
      };

      let settings: SwiperOptions = {
        slidesPerView: 3,
        loop: true,
        centeredSlides: true,
        initialSlide: items.length,
        on: {
          afterInit: function (swiper) {
            swiperInstance.current = swiper;
            setTimeout(() => {
              setSliderInitialized(true);
            }, 600);
          },
          slideChange: function (swiper) {
            swiperInstance.current = swiper;
            onSlideChange(swiper);
          },
        },
      };

      if (!isDesktop) {
        settings = {
          slidesPerView: 3,
          spaceBetween: 20,
          centeredSlides: true,
          on: {
            afterInit: function (swiper) {
              swiperInstance.current = swiper;

              setTimeout(() => {
                setSliderInitialized(true);
              }, 600);
            },
            slideChange: function (swiper) {
              swiperInstance.current = swiper;
              onSlideChange(swiper);
            },
          },
        };
      }

      carouselRef.current = new Swiper(carouselElementRef.current as HTMLElement, settings);
    }, 100);

    return () => {
      if (carouselRef.current) {
        carouselRef.current.destroy();
      }
    };
  }, [resizeKey, isDesktop, currentItems, items]);

  if (!currentItems.length) return null;

  return (
    <div className={styles.PhoneCarousel} ref={containerRef}>
      <div ref={carouselElementRef} className={cx(styles.swiper, 'swiper')}>
        <ul className={cx(styles.swiperWrapper, 'swiper-wrapper')}>
          {currentItems.map((item, i) => {
            return (
              <li className={cx(styles.swiperSlide, 'swiper-slide')} key={i}>
                <Phone mediaAsset={item} />
              </li>
            );
          })}
        </ul>
        <div className={styles.navigation} ref={navigationRef}>
          {items.map((_, i) => {
            return (
              <div
                key={i}
                className={cx(styles.navigationItem, {
                  [styles.active]: activeIndex === i || activeIndex === i + items.length,
                })}
                onClick={() => {
                  if (!swiperInstance.current) return;
                  const realIndex =
                    activeIndex >= items.length ? activeIndex - items.length : activeIndex;
                  if (i === realIndex) return;
                  const diff = Math.abs(realIndex - i);
                  const isAfter = i > realIndex;

                  // slideTo api does not work well with looped items
                  // as we are faking the loop on desktop by
                  // multiplying items by 2
                  for (let index = 0; index < diff; index++) {
                    setTimeout(() => {
                      if (isAfter) {
                        swiperInstance.current.slideNext(0);
                      } else {
                        swiperInstance.current.slidePrev(0);
                      }
                    }, 0);
                  }
                }}
              />
            );
          })}
        </div>
      </div>
      <div ref={buttonsRef} className={styles.buttonsContainer}>
        <PhoneCarouselButton
          direction="left"
          className={styles.leftButton}
          onClick={() => {
            if (carouselRef.current) {
              carouselRef.current.slidePrev();
            }
          }}
        />
        <PhoneCarouselButton
          direction="right"
          className={styles.rightButton}
          onClick={() => {
            if (carouselRef.current) {
              carouselRef.current.slideNext();
            }
          }}
        />
      </div>
    </div>
  );
};

PhoneCarousel.displayName = 'PhoneCarousel';

const PhoneCarouselButton = ({
  direction,
  onClick,
  className,
}: {
  direction: 'left' | 'right';
  onClick: () => void;
  className?: string;
}) => {
  return (
    <button
      className={cx(styles.PhoneCarouselButton, styles[direction], className)}
      onClick={() => {
        if (onClick) onClick();
      }}
    >
      <span className={styles.iconContainer}>
        <svg viewBox="0 0 11 18" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M10.5122 0.878906L1.48782 9.00086L10.5122 17.1228"
            stroke="currentColor"
            stroke-width="0.902439"
          />
        </svg>
      </span>
    </button>
  );
};

PhoneCarouselButton.displayName = 'PhoneCarouselButton';

function Phone({
  mediaAsset,
  className,
}: {
  className?: string;
  mediaAsset: Maybe<AssetFragment>;
}) {
  const videoRef = useRef<HTMLVideoElement | null>(null);

  if (!mediaAsset) return null;

  return (
    <div className={cx(className, styles.phoneContainer)}>
      <div className={styles.phoneContainerInner}>
        <img
          alt=""
          src={'/assets/images/iphone-hollow.webp'}
          className={styles.phoneContainer__hollowPhone}
          // loading="lazy"
        />

        <div className={styles.mediaContainer}>
          {mediaAsset.contentType?.includes('video') && (
            <>
              <VideoAltText text={mediaAsset.description} describes={videoRef.current} />
              <video
                src={`${mediaAsset.url}#t=0.001`}
                data-src={`${mediaAsset.url}#t=0.001`}
                playsInline
                preload="auto"
                autoPlay={false}
                muted
                loop
                className={styles.media}
                ref={videoRef}
              />
            </>
          )}
          {mediaAsset.contentType?.includes('image') && (
            <CMSImage
              width={400}
              height={800}
              className={styles.media}
              asset={mediaAsset}
              // loading="lazy"
            />
          )}
        </div>
      </div>
    </div>
  );
}

export default PhoneCarousel;

chartjs error Uncaught SyntaxError: expected expression, got ‘&’

I’m trying to integrate data from a database into Chart.js, but I’m encountering an error: Uncaught SyntaxError: expected expression, got ‘&’

Here is the code in the controller:

for (int i = 1; i <= days; i++)
{
     daysMonth.Add(string.Format(""Day {0}"", i));
}
ViewBag.XLabelCommission = string.Join(", ", daysMonth);

This is the returned result values of @ViewBag.XLabelCommission: "Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7", "Day 8", "Day 9", "Day 10", "Day 11", "Day 12", "Day 13", "Day 14", "Day 15", "Day 16", "Day 17", "Day 18", "Day 19", "Day 20", "Day 21", "Day 22", "Day 23", "Day 24", "Day 25", "Day 26", "Day 27", "Day 28", "Day 29", "Day 30", "Day 31"

And when I put it into the chart as label.

var myChart1 = new Chart(ctx1, {
            type: 'line',
            data: {
                labels: [@ViewBag.XLabelCommission],
                datasets: [{