<commit_before>/**
 * @author <NAME>
 * @copyright 2016 - 2017
 */
/** --------------------------------------- Modules --------------------------------------- **/
//---- Electron ----
const {
  ipcRenderer,
  remote
} = require('electron');

//---- own ----
const PLAYER = require('./factory')('player');
const {
    configFile,
    langFile,
    listSongs
} = require('./config').init();
require('./dom');

/** --------------------------------------- Variables --------------------------------------- **/
//---- constants ----
const LAPSE_POPUP = 4500; // Duration of info popups
const LAPSE_SCROLLING = 60; // Lapse before do scrolling
const MAX_ELEMENTS = 20; // Max of elementos to display when is filtering a song [searching bar]
const BTN_FILTER_SONGS = [ // Elements to use as a items into the slide
  $('div').clone(false).addClass('grid-25 mobile-grid-25'),
  $('div').clone(false).addClass('search-results'),
  $('div').clone(false).addClass('results')
];

//---- normals ----
let lang = langFile[configFile.lang];
let clickedElement = null; // When you do click on the name of the song
let positionElement = null; // Where is the song that you clicked on.
let isSearchDisplayed = false; // Checks if it was launched the searching bar
let totalResults = 0; // Amount of songs filtered
let searchValue = ''; // The input text to search for
let tempSlide = 0; // To create the pagination
let countSlide = 0;
let searchBy = 'title';
let fragmentSlide = null; // DocumentFragment() slide container
let fragmentItems = null; // DocumentFragment() button container
let slide = 0; // Amount of slides to make
let regex = null; // The name of the song to searching for as a regular expression
let list = null; // Filtered songs.

/** --------------------------------------- Functions --------------------------------------- **/
// Check if there's a new version to download
function getActualVersion() {
  const xhtr = new XMLHttpRequest();
  xhtr.open('GET', 'https://api.github.com/repos/dracotmolver/soube/releases/latest', true);
  xhtr.onload = () => {
    const RESPONSE = JSON.parse(xhtr.response);
    if (remote.app.getVersion().toString() !== RESPONSE.tag_name) {
      $('#pop-up-container')
      .replaceClass('hide', '')
      .child(0)
      .addClass('pop-up-anim')
      .text(
        `<a href="http://soube.diegomolina.cl">${lang.alerts.newVersion}</a>`
      );

      $(':a').on({
        click: function (e) {
          e.preventDefault();
          shell.openExternal(this.href);
        }
      });

      let tout = setTimeout(() => {
        $('#pop-up-container')
        .addClass('hide')
        .child(0)
        .replaceClass('pop-up-anim', '');

        if (Object.keys(listSongs).length !== 0) checkNewSongs();

        clearTimeout(tout);
      }, LAPSE_POPUP);
    }
  };
  xhtr.send(null);
}

// Main function!!
function loadSongs() {
  // Enable shuffle
  if (configFile.shuffle) $('#shuffle-icon').css('fill:#FBFCFC');

  getActualVersion();
  if (Object.keys(listSongs).length === 0) {
    $('#list-songs').text(
      `<div id="init-message">${lang.alerts.welcome}</div>`
    );
  } else {
    // Render the list of songs
    PLAYER.createView(PLAYER);
  }
}
loadSongs();

function hideSearchInputData() {
  $('#search-result').empty();
  $('#search-container').addClass('hide');
  $('#search-wrapper').replaceClass('search-wrapper-anim', '');
  $($('.grid-container').get(0)).rmAttr('style');
  $('#search').replaceClass('input-search-anim', '');
  isSearchDisplayed = false;
}

// This function is use into the function itemSlide
function selectedSong (position) {
  PLAYER.controls.playSongAtPosition(position);
  hideSearchInputData();
}

// will be executed every time the user hit down a keyword
// So, I carefully tried to do a clean, cheaper and faster code :).
function searchInputData(e) {
  searchValue = this.value.trim();

  if (searchValue !== '') {
    countSlide = 0;
    // Complete the text
    if (e.key === 'ArrowRight' && searchValue.length > 1)
      this.value = $('#search-result').text();

    if (e.key === 'Enter') selectedSong(list[0].position);

    regex = new RegExp(`^${searchValue.replace(/\s+/g, '&nbsp;')}+`, 'ig');
    list = listSongs.filter(v => regex.test(v[searchBy]));

    // Show possibles results
    totalResults = list.length - 1;
    tempSlide = slide = totalResults > MAX_ELEMENTS ? Math.floor(totalResults / MAX_ELEMENTS) : 1;
    fragmentSlide = fragmentItems = document.createDocumentFragment();

    // Make an slide with all the filtered coincidences
    const FILTERED_SONGS = totalResults < MAX_ELEMENTS ? totalResults + 1 : MAX_ELEMENTS;
    while (slide--) {
      for (var i = 0; i < FILTERED_SONGS; i++ , totalResults--) {
        fragmentItems.appendChild(
          BTN_FILTER_SONGS[0].clone(true)
          .insert(
            BTN_FILTER_SONGS[1].clone(true)
            .text(list[totalResults][searchBy])
          )
          .data({ position: list[totalResults].position })
          .on({
            click: function() {
              selectedSong($(this).data('position'));
            }
          }).get()
        );
      }

      // All the buttons into the slides
      fragmentSlide.appendChild(
        BTN_FILTER_SONGS[2].clone(true)
        .insert(fragmentItems)
        .css(`width:${document.body.clientWidth}px`).get()
      );
      fragmentItems = document.createDocumentFragment();
    }

    // Add pagination if there's more than one slide
    tempSlide > 1 ?
    $('#pagination').replaceClass('hide', '').child(1).addClass('arrow-open-anim') :
    $('#pagination').addClass('hide');

    // Display all the filtered songs
    $('#wrapper-results').empty()
    .insert(fragmentSlide)
    .css(`width:${tempSlide * document.body.clientWidth}px`);
  } else {
    // Clean if there's no coincidence
    $('#wrapper-results').empty();
    $('#pagination').addClass('hide');
  }

  // Show the first coincidence to show as a "ghost text".
  $('#search-result').text(searchValue !== '' ? list[0][searchBy] : '');
}

// Check if there are new songs to be added
function checkNewSongs() {
  PLAYER.addSongFolder(configFile.musicFolder, () => {
    // show pop-up
    $('#pop-up-container')
    .replaceClass('hide', '')
    .child(0)
    .addClass('pop-up-anim');
  }, (i, maxlength) => {
    $('#pop-up').text(`${langFile[configFile.lang].alerts.newSongsFound}${i} / ${maxlength}`);

    if (i === maxlength) {
      // hide pop-up
      $('#pop-up-container').addClass('hide').child(0).replaceClass('pop-up-anim');
      window.location.reload(true);
    }
  });
}

function clickBtnControls() {
  $(this).addClass('click-controls')
    .on({
      animationend: function () {
        $(this).replaceClass('click-controls', '');
      }
    });

  if (listSongs.length !== 0) {
    switch (this.id) {<commit_msg>edited the regex when we searching for a song<commit_after>/**
 * @author <NAME>
 * @copyright 2016 - 2017
 */
/** --------------------------------------- Modules --------------------------------------- **/
//---- Electron ----
const {
  ipcRenderer,
  remote
} = require('electron');

//---- own ----
const PLAYER = require('./factory')('player');
const {
    configFile,
    langFile,
    listSongs
} = require('./config').init();
require('./dom');

/** --------------------------------------- Variables --------------------------------------- **/
//---- constants ----
const LAPSE_POPUP = 4500; // Duration of info popups
const LAPSE_SCROLLING = 60; // Lapse before do scrolling
const MAX_ELEMENTS = 20; // Max of elementos to display when is filtering a song [searching bar]
const BTN_FILTER_SONGS = [ // Elements to use as a items into the slide
  $('div').clone(false).addClass('grid-25 mobile-grid-25'),
  $('div').clone(false).addClass('search-results'),
  $('div').clone(false).addClass('results')
];

//---- normals ----
let lang = langFile[configFile.lang];
let clickedElement = null; // When you do click on the name of the song
let positionElement = null; // Where is the song that you clicked on.
let isSearchDisplayed = false; // Checks if it was launched the searching bar
let totalResults = 0; // Amount of songs filtered
let searchValue = ''; // The input text to search for
let tempSlide = 0; // To create the pagination
let countSlide = 0;
let searchBy = 'title';
let fragmentSlide = null; // DocumentFragment() slide container
let fragmentItems = null; // DocumentFragment() button container
let slide = 0; // Amount of slides to make
let regex = null; // The name of the song to searching for as a regular expression
let list = null; // Filtered songs.

/** --------------------------------------- Functions --------------------------------------- **/
// Check if there's a new version to download
function getActualVersion() {
  const xhtr = new XMLHttpRequest();
  xhtr.open('GET', 'https://api.github.com/repos/dracotmolver/soube/releases/latest', true);
  xhtr.onload = () => {
    const RESPONSE = JSON.parse(xhtr.response);
    if (remote.app.getVersion().toString() !== RESPONSE.tag_name) {
      $('#pop-up-container')
      .replaceClass('hide', '')
      .child(0)
      .addClass('pop-up-anim')
      .text(
        `<a href="http://soube.diegomolina.cl">${lang.alerts.newVersion}</a>`
      );

      $(':a').on({
        click: function (e) {
          e.preventDefault();
          shell.openExternal(this.href);
        }
      });

      let tout = setTimeout(() => {
        $('#pop-up-container')
        .addClass('hide')
        .child(0)
        .replaceClass('pop-up-anim', '');

        if (Object.keys(listSongs).length !== 0) checkNewSongs();

        clearTimeout(tout);
      }, LAPSE_POPUP);
    }
  };
  xhtr.send(null);
}

// Main function!!
function loadSongs() {
  // Enable shuffle
  if (configFile.shuffle) $('#shuffle-icon').css('fill:#FBFCFC');

  getActualVersion();
  if (Object.keys(listSongs).length === 0) {
    $('#list-songs').text(
      `<div id="init-message">${lang.alerts.welcome}</div>`
    );
  } else {
    // Render the list of songs
    PLAYER.createView(PLAYER);
  }
}
loadSongs();

function hideSearchInputData() {
  $('#search-result').empty();
  $('#search-container').addClass('hide');
  $('#search-wrapper').replaceClass('search-wrapper-anim', '');
  $($('.grid-container').get(0)).rmAttr('style');
  $('#search').replaceClass('input-search-anim', '');
  isSearchDisplayed = false;
}

// This function is use into the function itemSlide
function selectedSong (position) {
  PLAYER.controls.playSongAtPosition(position);
  hideSearchInputData();
}

// will be executed every time the user hit down a keyword
// So, I carefully tried to do a clean, cheaper and faster code :).
function searchInputData(e) {
  searchValue = this.value.trim();

  if (searchValue !== '') {
    countSlide = 0;
    // Complete the text
    if (e.key === 'ArrowRight' && searchValue.length > 1)
      this.value = $('#search-result').text();


    regex = new RegExp(`${searchValue.replace(/\s+/g, '&nbsp;')}`, 'ig');
    list = listSongs.filter(v => regex.test(v[searchBy]));

    if (e.key === 'Enter') selectedSong(list[list.length - 1].position);

    // Show possibles results
    totalResults = list.length - 1;
    tempSlide = slide = totalResults > MAX_ELEMENTS ? Math.floor(totalResults / MAX_ELEMENTS) : 1;
    fragmentSlide = fragmentItems = document.createDocumentFragment();

    // Make an slide with all the filtered coincidences
    const FILTERED_SONGS = totalResults < MAX_ELEMENTS ? totalResults + 1 : MAX_ELEMENTS;
    while (slide--) {
      for (var i = 0; i < FILTERED_SONGS; i++ , totalResults--) {
        fragmentItems.appendChild(
          BTN_FILTER_SONGS[0].clone(true)
          .insert(
            BTN_FILTER_SONGS[1].clone(true)
            .text(list[totalResults][searchBy])
          )
          .data({ position: list[totalResults].position })
          .on({
            click: function() {
              selectedSong($(this).data('position'));
            }
          }).get()
        );
      }

      // All the buttons into the slides
      fragmentSlide.appendChild(
        BTN_FILTER_SONGS[2].clone(true)
        .insert(fragmentItems)
        .css(`width:${document.body.clientWidth}px`).get()
      );
      fragmentItems = document.createDocumentFragment();
    }

    // Add the pagination if there's more than one slide
    tempSlide > 1 ?
    $('#pagination').replaceClass('hide', '').child(1).addClass('arrow-open-anim') :
    $('#pagination').addClass('hide');

    // Display all the filtered songs
    $('#wrapper-results').empty()
    .insert(fragmentSlide)
    .css(`width:${tempSlide * document.body.clientWidth}px`);
  } else {
    // Clean if there's no coincidence
    $('#wrapper-results').empty();
    $('#pagination').addClass('hide');
  }

  // Show the first coincidence to show as a "ghost text".
  $('#search-result').text(searchValue !== '' ? list[list.length - 1][searchBy] : '');
}

// Check if there are new songs to be added
function checkNewSongs() {
  PLAYER.addSongFolder(configFile.musicFolder, () => {
    // show pop-up
    $('#pop-up-container')
    .replaceClass('hide', '')
    .child(0)
    .addClass('pop-up-anim');
  }, (i, maxlength) => {
    $('#pop-up').text(`${langFile[configFile.lang].alerts.newSongsFound}${i} / ${maxlength}`);

    if (i === maxlength) {
      // hide pop-up
      $('#pop-up-container').addClass('hide').child(0).replaceClass('pop-up-anim');
      window.location.reload(true);
    }
  });
}

function clickBtnControls() {
  $(this).addClass('click-controls')
    .on({
      animationend: function () {
        $(this).replaceClass('click-controls', '');
      }
    });

  if (listSongs.length !== 0) {
    switch (this.id) {
{'fraction_non_alphanumeric': 0.20333551817056297, 'fraction_numerical': 0.006554511688879178, 'mean_word_length': 2.599475753604194, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 29, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2718521', 'n_tokens_mistral': 4257, 'n_tokens_neox': 4092, 'n_words': 961}