Untitled

mail@pastecode.io avatar
unknown
javascript
8 months ago
4.8 kB
5
Indexable
Never
// Function to initialize localStorage with an empty array if it doesn't exist
function initLocalStorage() {
  const userInteractionData = JSON.stringify([]);
  localStorage.setItem('userInteractionData', userInteractionData);
}

// Check if 'userInteractionData' key exists in localStorage
if (!localStorage.getItem('userInteractionData')) {
  // If not, initialize it with an empty array
  initLocalStorage();
}

// Function to clean and format a username
function cleanUsername(username) {
  // Remove any leading or trailing whitespace and special symbols
  return username.trim().replace(/<|>/g, '') + ', ';
}

// Add a click event listener to all .username elements
const usernameElements = document.querySelectorAll('.username');

usernameElements.forEach((usernameElement) => {
  // Add a click event listener to each .username element
  usernameElement.addEventListener('click', () => {
    // Get the username's textContent and clean it
    const usernameText = cleanUsername(usernameElement.textContent);

    // Retrieve the current data from localStorage
    const userInteractionData = JSON.parse(localStorage.getItem('userInteractionData'));

    // Find the index of the username in the array
    const index = userInteractionData.findIndex((data) => data.username === usernameText);

    if (index !== -1) {
      // If the username exists in the array, increment the click count
      userInteractionData[index].appeals += 1;
    } else {
      // If the username doesn't exist in the array, add it with a click count of 1
      userInteractionData.push({ username: usernameText, appeals: 1 });
    }

    // Store the updated data back in localStorage
    localStorage.setItem('userInteractionData', JSON.stringify(userInteractionData));

    // Log the username and the updated click count to the console
    console.log(`Username: ${usernameText}, Click Count: ${userInteractionData[index]?.appeals || 1}`);
  });
});

// Add an event listener to the text input field
const textInput = document.querySelector('.text');
let currentIndex = -1; // Initialize the index for cycling through usernames
let isTypingNickname = false; // Flag to track if user is typing a nickname

textInput.addEventListener('keydown', (e) => {
  const inputText = cleanUsername(textInput.value); // Clean the input text

  if (e.key === ' ' && isTypingNickname) {
    // Prevent the default space key behavior (adding a space)
    e.preventDefault();

    // Retrieve the current data from localStorage
    const userInteractionData = JSON.parse(localStorage.getItem('userInteractionData'));

    if (userInteractionData.length > 0) {
      // Sort the usernames based on appeal values in descending order
      userInteractionData.sort((a, b) => b.appeals - a.appeals);

      // If currentIndex is -1 or greater than or equal to the length of userInteractionData, set it to 0
      if (currentIndex === -1 || currentIndex >= userInteractionData.length) {
        currentIndex = 0;
      }

      // Set the input value to the current username
      textInput.value = userInteractionData[currentIndex].username;

      // Increment currentIndex for the next cycle
      currentIndex++;
    }
  } else if (e.key === 'Enter') {
    // Clear the currentIndex when Enter is pressed
    currentIndex = -1;
    // Focus on the text input after pressing Enter
    textInput.focus();
  } else if (e.key === 'Backspace' && inputText === ', ') {
    // Clear the currentIndex when Backspace is pressed and the input is just a comma
    currentIndex = -1;
  } else if (e.key.length === 1 && inputText !== ', ') {
    // Stop listing when a letter or any non-space character is typed after the nickname
    currentIndex = -1;
    isTypingNickname = false;
  } else if (e.key === ' ' && inputText === ', ') {
    // Start listing when space is pressed immediately after a comma
    isTypingNickname = true;
  }
});

// Add an input event listener to check if the input value matches any localStorage username
textInput.addEventListener('input', () => {
  const inputText = cleanUsername(textInput.value); // Clean the input text

  if (inputText === ', ') {
    // Enable listing if the input value is just a comma
    isTypingNickname = true;
  } else if (inputText.trim() === '') {
    // Disable listing if the input value is empty (no characters except spaces)
    isTypingNickname = false;
  }
});

// Function to check if the input value matches any username in localStorage
function localStorageContainsUsername(inputText) {
  const userInteractionData = JSON.parse(localStorage.getItem('userInteractionData'));
  return userInteractionData.some((data) => data.username === inputText);
}