<commit_before>// @flow

import overrideRequire from 'override-require';
import {
  SourceMapConsumer
} from 'source-map';
import createCompiler from './createCompiler';
import createCompilerCallback from './createCompilerCallback';
import createCompilerConfiguration from './createCompilerConfiguration';
import createIsomorphicWebpackConfiguration from './createIsomorphicWebpackConfiguration';
import isRequestResolvable from './../utilities/isRequestResolvable';
import resolveRequest from './../utilities/resolveRequest';
import runCode from './../utilities/runCode';

export default (webpackConfiguration, userIsomorphicWebpackConfiguration) => {
  const isomorphicWebpackConfiguration = createIsomorphicWebpackConfiguration(userIsomorphicWebpackConfiguration);

  const compilerConfiguration = createCompilerConfiguration(webpackConfiguration);

  const compiler = createCompiler(compilerConfiguration);

  let restoreOriginalRequire;
  let bundleSourceMapConsumer;

  const compilerCallback = createCompilerCallback(compiler, ({
    bundleCode,
    bundleSourceMap,
    requestMap
  }) => {
    bundleSourceMapConsumer = new SourceMapConsumer(bundleSourceMap);

    const module = runCode(bundleCode);

    const isOverride = (request, parent) => {
      const override = isRequestResolvable(compiler.options.context, requestMap, request, parent.filename);

      if (override) {
        const matchedRequest = resolveRequest(compiler.options.context, requestMap, request, parent.filename);

        if (isomorphicWebpackConfiguration.isOverride && !isomorphicWebpackConfiguration.isOverride(matchedRequest)) {
          return false;
        }
      }

      return override;
    };

    const resolveOverride = (request, parent) => {
      const matchedRequest = resolveRequest(compiler.options.context, requestMap, request, parent.filename);
      const moduleId = requestMap[matchedRequest];

      return module(moduleId);
    };

    if (restoreOriginalRequire) {
      restoreOriginalRequire();
    }

    restoreOriginalRequire = overrideRequire(isOverride, resolveOverride);
  });

  compiler.watch({}, compilerCallback);

  type ErrorPositionType = {|
    column: number,
    line: number,
    source: string
  |};

  const getOriginalPosition = (lineNumber: number, columnNumber: number): ErrorPositionType => {
    const originalPosition = bundleSourceMapConsumer.originalPositionFor({
      column: columnNumber,
      line: lineNumber
    });

    return {
      column: originalPosition.column,
      line: originalPosition.line,
      source: originalPosition.source.replace('webpack://', webpackConfiguration.context)
    };
  };

  const formatErrorStack = (errorStack: string): string => {
    return errorStack.replace(/\(isomorphic-webpack:(\d+):(\d+)\)/g, (match, lineNumber, columnNumber) => {
      const originalPosition = getOriginalPosition(Number(lineNumber), Number(columnNumber));

      if (originalPosition.source === null || originalPosition.line === null || originalPosition.column === null) {
        return match;
      }

      return '(' + originalPosition.source + ':' + originalPosition.line + ':' + originalPosition.column + ')';
    });
  };

  return {
    formatErrorStack
  };
};
<commit_msg>fix: check if original position is discoverable (fixes #5)<commit_after>// @flow

import overrideRequire from 'override-require';
import {
  SourceMapConsumer
} from 'source-map';
import createCompiler from './createCompiler';
import createCompilerCallback from './createCompilerCallback';
import createCompilerConfiguration from './createCompilerConfiguration';
import createIsomorphicWebpackConfiguration from './createIsomorphicWebpackConfiguration';
import isRequestResolvable from './../utilities/isRequestResolvable';
import resolveRequest from './../utilities/resolveRequest';
import runCode from './../utilities/runCode';

export default (webpackConfiguration, userIsomorphicWebpackConfiguration) => {
  const isomorphicWebpackConfiguration = createIsomorphicWebpackConfiguration(userIsomorphicWebpackConfiguration);

  const compilerConfiguration = createCompilerConfiguration(webpackConfiguration);

  const compiler = createCompiler(compilerConfiguration);

  let restoreOriginalRequire;
  let bundleSourceMapConsumer;

  const compilerCallback = createCompilerCallback(compiler, ({
    bundleCode,
    bundleSourceMap,
    requestMap
  }) => {
    bundleSourceMapConsumer = new SourceMapConsumer(bundleSourceMap);

    const module = runCode(bundleCode);

    const isOverride = (request, parent) => {
      const override = isRequestResolvable(compiler.options.context, requestMap, request, parent.filename);

      if (override) {
        const matchedRequest = resolveRequest(compiler.options.context, requestMap, request, parent.filename);

        if (isomorphicWebpackConfiguration.isOverride && !isomorphicWebpackConfiguration.isOverride(matchedRequest)) {
          return false;
        }
      }

      return override;
    };

    const resolveOverride = (request, parent) => {
      const matchedRequest = resolveRequest(compiler.options.context, requestMap, request, parent.filename);
      const moduleId = requestMap[matchedRequest];

      return module(moduleId);
    };

    if (restoreOriginalRequire) {
      restoreOriginalRequire();
    }

    restoreOriginalRequire = overrideRequire(isOverride, resolveOverride);
  });

  compiler.watch({}, compilerCallback);

  type ErrorPositionType = {|
    column: number,
    line: number,
    source: string
  |};

  const isOriginalPositionDiscoverable = (lineNumber: number, columnNumber: number): boolean => {
    const originalPosition = bundleSourceMapConsumer.originalPositionFor({
      column: columnNumber,
      line: lineNumber
    });

    return originalPosition.source !== null && originalPosition.line !== null && originalPosition.column !== null;
  };

  const getOriginalPosition = (lineNumber: number, columnNumber: number): ErrorPositionType => {
    const originalPosition = bundleSourceMapConsumer.originalPositionFor({
      column: columnNumber,
      line: lineNumber
    });

    return {
      column: originalPosition.column,
      line: originalPosition.line,
      source: originalPosition.source.replace('webpack://', webpackConfiguration.context)
    };
  };

  const formatErrorStack = (errorStack: string): string => {
    return errorStack.replace(/\(isomorphic-webpack:(\d+):(\d+)\)/g, (match, lineNumber, columnNumber) => {
      const targetLineNumber = Number(lineNumber);
      const targetColumnNumber = Number(columnNumber);

      if (!isOriginalPositionDiscoverable(targetLineNumber, targetColumnNumber)) {
        return match;
      }

      const originalPosition = getOriginalPosition(targetLineNumber, targetColumnNumber);

      return '(' + originalPosition.source + ':' + originalPosition.line + ':' + originalPosition.column + ')';
    });
  };

  return {
    formatErrorStack
  };
};
<|endoftext|>


<commit_before>//Объявление общедоступных переменных
let ContactsArray = [];
let Contact;
let createNewContact = true;
let SearchArray = [];
//Блок событий при отображении списка контактов
document.getElementById('add-contact-button').addEventListener('click', AddNewContact, false);
let inputSearch = document.getElementById('inputsearch');
inputSearch.oninput = function () {

    SearchArray.length = 0;

    let matchValue = /^[a-zA-Z\s]*$/;
    if (!inputSearch.value.match(matchValue) || inputSearch.value.length > 22)
    {
        inputSearch.value = inputSearch.value.substr(0, inputSearch.value.length - 1);
    }

    for (i = 0; i < ContactsArray.length; i++)
    {
        if (ContactsArray[i].name.toLowerCase().indexOf(inputSearch.value) ==  0 )
        {
            SearchArray.push(ContactsArray[i]);
        }
    }
    ReloadContactList(SearchArray);
}
document.getElementById('contact-list').onclick = function (event){
    let target = event.target || event.srcElement
    if (target.id != 'contact-list') {
        if (target.id != '')EditContact(target.id);
    }
    }
document.getElementById('add-contact').onclick = function (event){
    let target = event.target || event.srcElement

    if (target.className == 'button-plus-phone'){
        AddNumber();
    }
    if (target.className == 'button-minus-phone'){
        RemoveNumber(target);
    }
    if (target.className == 'button-plus-email'){
        AddMail();
    }
    if (target.className == 'button-minus-email'){
        RemoveMail(target);
    }
}
//Заливаем базу при первом запуске/релоаде
    if (localStorage.getItem('Contacts'))
    {
        ContactsArray = JSON.parse(localStorage.getItem('Contacts'));
        ReloadContactList(ContactsArray);
    }
//Логика добаления и редактирования контакта
function AddNewContact() {
    createNewContact = true;
    let newContact = {
        id: 0,
        name: '',
        number: [''],
        email: ['']
    }

    OpenContactWindow(newContact);
}
function RemoveContact() {
    ContactsArray.splice(Contact.id, 1);
    CloseContactWindow();
    ReloadContactList(ContactsArray);
}
function EditContact(id) {
    for (i = 0; i < ContactsArray.length; i++){
        if (ContactsArray[i].id == id){
            Contact = ContactsArray[i];
            createNewContact = false;
            OpenContactWindow(Contact);
            break;
        }
    }
}
function SaveContact() {

    let inputName = document.getElementById('name');
    let numberId0 = document.getElementById('number0');
    let emailId0 = document.getElementById('email0');

    SaveInputValue();

        if(inputName.value != '' && numberId0.value != '' && emailId0.value != '')
        {

    if (createNewContact) {
        ContactsArray.push(Contact);
    }

    ReloadContactList(ContactsArray)
    localStorage.setItem('Contacts', JSON.stringify(ContactsArray));

    CloseContactWindow();
        }
        else {
    if (numberId0.value == ''){
        numberId0.setAttribute('placeholder', 'Enter phone number');
    }
    if (emailId0.value == '') {
        emailId0.setAttribute('placeholder', 'Enter e-mail address')
    }
    if (inputName.value == ''){
        inputName.setAttribute('placeholder', 'Enter contact name')
    }
}
}
function SaveInputValue() {
    let inputName = document.getElementById('name');
    Contact.name = inputName.value;
    for(z = 0; z < Contact.number.length; z++){
        let numberId = document.getElementById('number'+z);
        Contact.number[z] = numberId.value;
    }
    for(y = 0; y < Contact.email.length; y++){
        let emailId = document.getElementById('email'+y);
        Contact.email[y] = emailId.value;
    }
}
//Логика переключения между списком контактов и формой добавления/редактирования контакта
function OpenContactWindow(contact) {

    Contact = contact;

    document.getElementById('contact-list').style.display = 'none';
    document.getElementById('header').style.display = 'none';
    document.getElementById('add-contact').style.display = 'flex';
    AddContactDrow();

    document.getElementById('save-contact').addEventListener('click', SaveContact, false);
    document.getElementById('reset-change').addEventListener('click', CloseContactWindow, false);
    if (!createNewContact) document.getElementById('removecontact').addEventListener('click', RemoveContact, false);

}
function CloseContactWindow() {
    document.getElementById('contact-list').style.display = 'flex';
    document.getElementById('header').style.display = 'flex';
    document.getElementById('add-contact').style.display = 'none';
    ContactsArray = JSON.parse(localStorage.getItem('Contacts'));

    ResetAddContactWindow();
    for (i = 0; i < Contact.number.length; i++){
        if (Contact.number[i] == '')
        {
            Contact.number.splice(i, 1);
        }
    }
    for (i = 0; i < Contact.email.length; i++){
        if (Contact.email[i] == '')
        {
            Contact.email.splice(i, 1);
        }
    }
    ReloadContactList(ContactsArray);
}
function ResetAddContactWindow() {
    let inputClean = document.getElementsByTagName('input');
    for (i = 0; i < inputClean.length; i++){
        inputClean[i].value = '';
    }

    let addContact = document.getElementById('add-contact');
    while (addContact.firstChild){
        addContact.removeChild(addContact.firstChild);
    }
}
function ReloadContactList(currentArray) {
    let contactList = document.getElementById('contact-list');
    while (contactList.firstChild){
        contactList.removeChild(contactList.firstChild);
    }

    currentArray.sort(function(x,y){
        if (x.name > y.name)
            return 1;
        if (x.name < y.name)
            return -1;
        return 0;
    });

    if (currentArray != ContactsArray) {
        for (i = 0; i < currentArray.length; i++) {
            ContactListDraw(currentArray[i]);
        }
    }else {
        for (i = 0; i < ContactsArray.length; i++){
            ContactsArray[i].id = i;

            ContactListDraw(currentArray[i]);
        }
    }

}
//Рисуем форму добавления и редактирования контакта
function AddContactDrow() {

    let contactForm = document.getElementById('add-contact');

    let headerDiv = document.createElement('div');
    headerDiv.setAttribute('class', 'text');
    contactForm.appendChild(headerDiv);
    let headerH = document.createElement('h2');
    if (createNewContact) {
        headerH.innerText = 'Add Contact';
    }else {
        headerH.innerText = 'Edit Contact';
        let removeContact = document.createElement('div');
        removeContact.setAttribute('id', 'removecontact');
        removeContact.innerText = 'Remove Contact';
        contactForm.appendChild(removeContact);
    }
    headerDiv.appendChild(headerH);

    for (element in Contact) {
        if (element == 'name') {
            let nameDiv = document.createElement('div');
            nameDiv.setAttribute('class', 'search');
            contactForm.appendChild(nameDiv);

            let nameSpan = document.createElement('span');
            nameSpan.innerText = 'Name';
            nameDiv.appendChild(nameSpan);
            let nameInput = document.createElement('input');
            nameInput.setAttribute('type', 'text');
            nameInput.setAttribute('id', 'name');
            nameDiv.appendChild(nameInput);
            nameInput.value = Contact.name;
            nameInput.oninput = function ()
            {
                let matchValue = /^[a-zA-Z\s]*$/;
                if (!nameInput.value.match(matchValue) || nameInput.value.length > 22)
                {
                    nameInput.value = nameInput.value.substr(0, nameInput.value.length - 1);
                }
            }
        }
        if (element == 'number') {
            for (l = 0; l < Contact.number.length; l++) {
                let phoneDiv = document.createElement('div');
                phoneDiv.setAttribute('class', 'search plus-minus-fields');
                phoneDiv.setAttribute('id', 'phone-number-div');
                contactForm.appendChild(phoneDiv);

                let minusDiv = document.createElement('div');
                minusDiv.setAttribute('class', 'button-minus-phone');
                minusDiv.innerText = '-';
                minusDiv.setAttribute('id', l);
                phoneDiv.appendChild(minusDiv);

                let phoneDivEmpty = document.createElement('div');
                phoneDiv.appendChild(phoneDivEmpty);

                let phoneSpan = document.createElement('span');
                if (l == 0){
                    phoneSpan.innerText = 'Phone Number';
                }else {
                    phoneSpan.innerText = 'More Phone Number';
                }

                phoneDivEmpty.appendChild(phoneSpan);
                let phoneInput = document.createElement('input');
                phoneInput.setAttribute('type', 'text');
                phoneInput.setAttribute('id', 'number'+l);
                phoneDivEmpty.appendChild(phoneInput);
                phoneInput.oninput = function ()
                {
                    if (isNaN(phoneInput.value+1) || phoneInput.value.length > 10)
                    {
                        phoneInput.value = phoneInput.value.substr(0, phoneInput.value.length - 1);
                    }
                }

                let plusDiv = document.createElement('div');
                plusDiv.setAttribute('class', 'button-plus-phone');
                plusDiv.innerText = '+';
                phoneDiv.appendChild(plusDiv);

                phoneInput.value = Contact.number[l];
            }
        }
        if (element == 'email') {
            for (h = 0; h < Contact.email.length; h++) {
                let emailDiv = document.createElement('div');
                emailDiv.setAttribute('class', 'search plus-minus-fields');
                emailDiv.setAttribute('id', 'email-div');
                contactForm.appendChild(emailDiv);

                let minusDiv = document.createElement('div');
                minusDiv.setAttribute('class', 'button-minus-email');
                minusDiv.innerText = '-';
                minusDiv.setAttribute('id', h);
                emailDiv.appendChild(minusDiv);

                let emailDivEmpty = document.createElement('div');
                emailDiv.appendChild(emailDivEmpty);

                let emailSpan = document.createElement('span');
                if (h == 0){
                    emailSpan.innerText = 'E-mail Address';
                }else {
                    emailSpan.innerText = 'More E-mail Address';
                }

                emailDivEmpty.appendChild(emailSpan);
                let emailInput = document.createElement('input');
                emailInput.setAttribute('type', 'text');
                emailInput.setAttribute('id', 'email'+h);
                emailDivEmpty.appendChild(emailInput);
                emailInput.oninput = function ()
                {
                    let matchValue = /^[a-z0-9@._]*$/;
                    if (!emailInput.value.match(matchValue) || emailInput.value.length > 25)
                    {
                        emailInput.value = emailInput.value.substr(0, emailInput.value.length - 1);
                    }
                }

                let plusDiv = document.createElement('div');
                plusDiv.setAttribute('class', 'button-plus-email');
                plusDiv.innerText = '+';
                emailDiv.appendChild(plusDiv);

                emailInput.value = Contact.email[h];
            }
        }
    }

    let buttonDiv = document.createElement('div');
    buttonDiv.setAttribute('class', 'search buttons');
    contactForm.appendChild(buttonDiv);

    let buttonOkDiv = document.createElement('div');
    buttonOkDiv.setAttribute('id', 'save-contact');
    buttonOkDiv.innerText = 'Ok';
    buttonDiv.appendChild(buttonOkDiv);

    let buttonCancelDiv = document.createElement('div');
    buttonCancelDiv.setAttribute('id', 'reset-change');
    buttonCancelDiv.innerText = 'Cancel';
    buttonDiv.appendChild(buttonCancelDiv);
}
function RemoveNumber(element) {
    if (element.id != 0){
        let removeElementParent = element.parentElement;
        let removeElement = removeElementParent.parentElement;
        removeElement.removeChild(removeElementParent);
        Contact.number.splice(element.id, 1);
    }
}
function AddNumber() {
    SaveInputValue();
    Contact.number[Contact.number.length] = '';
    ResetAddContactWindow();
    OpenContactWindow(Contact);

}
function RemoveMail(element) {
    if (element.id != 0) {
        let removeElementParent = element.parentElement;
        let removeElement = removeElementParent.parentElement;
        removeElement.removeChild(removeElementParent);
        Contact.email.splice(element.id, 1);
    }
}
function AddMail() {
    SaveInputValue();
    Contact.email[Contact.email.length] = '';
    ResetAddContactWindow();
    OpenContactWindow(Contact);
}
//Рисуеем список контактов
function ContactListDraw(contact) {

    let contactList = document.getElementById('contact-list');

    let listDiv = document.createElement("div");
    listDiv.setAttribute('class', 'list');
    contactList.appendChild(listDiv);

    let logoDiv = document.createElement("div");
    logoDiv.setAttribute('class', 'logo');
    logoDiv.setAttribute('id', contact.id);
    listDiv.appendChild(logoDiv);
    let logoSpan = document.createElement('span');
    logoSpan.setAttribute('class', 'logospan');
    logoSpan.setAttribute('id', contact.id);
    logoDiv.appendChild(logoSpan);
    logoSpan.innerText ='Z';

    let contactdataDiv = document.createElement("div");
    contactdataDiv.setAttribute('class', 'contactdata');
    listDiv.appendChild(contactdataDiv);

for (element in contact){
    if (element == 'name') CreateName(contactdataDiv, contact);
    if (element == 'number')
    {
        for (j = 0; j < contact.number.length; j++) {
            CreateNumber(contactdataDiv, contact.number[j]);
        }
    }
    if (element == 'email')
    {
        for (k = 0; k < contact.email.length; k++) {
            CreateEmail(contactdataDiv, contact.email[k]);
        }
    }
}

}
function CreateName(Div, contact) {
    let nameDiv = document.createElement("div");
    nameDiv.setAttribute('class', 'name');
    Div.appendChild(nameDiv);
    nameDiv.innerText = contact.name;
}
function CreateNumber(Div, contact) {
    let phoneDiv = document.createElement("div");
    phoneDiv.setAttribute('class', 'phone');
    Div.appendChild(phoneDiv);
    phoneDiv.innerText = contact;
}
function CreateEmail(Div,contact) {
    let emailDiv = document.createElement("div");
    emailDiv.setAttribute('class', 'email');
    Div.appendChild(emailDiv);
    emailDiv.innerText = contact;
}<commit_msg>Contact<commit_after>//Объявление общедоступных переменных
let ContactsArray = [];
let Contact;
let createNewContact = true;
let SearchArray = [];
//Блок событий при отображении списка контактов
document.getElementById('add-contact-button').addEventListener('click', AddNewContact, false);
let inputSearch = document.getElementById('inputsearch');
inputSearch.oninput = function () {

    SearchArray.length = 0;

    let matchValue = /^[a-zA-Z\s]*$/;
    if (!inputSearch.value.match(matchValue) || inputSearch.value.length > 22)
    {
        inputSearch.value = inputSearch.value.substr(0, inputSearch.value.length - 1);
    }

    for (i = 0; i < ContactsArray.length; i++)
    {
        if (ContactsArray[i].name.toLowerCase().indexOf(inputSearch.value) ==  0 )
        {
            SearchArray.push(ContactsArray[i]);
        }
    }
    ReloadContactList(SearchArray);
}
document.getElementById('contact-list').onclick = function (event){
    let target = event.target || event.srcElement
    if (target.id != 'contact-list') {
        if (target.id != '')EditContact(target.id);
    }
    }
document.getElementById('add-contact').onclick = function (event){
    let target = event.target || event.srcElement

    if (target.className == 'button-plus-phone'){
        AddNumber();
    }
    if (target.className == 'button-minus-phone'){
        RemoveNumber(target);
    }
    if (target.className == 'button-plus-email'){
        AddMail();
    }
    if (target.className == 'button-minus-email'){
        RemoveMail(target);
    }
}
//Заливаем базу при первом запуске/релоаде
    if (localStorage.getItem('Contacts'))
    {
        ContactsArray = JSON.parse(localStorage.getItem('Contacts'));
        ReloadContactList(ContactsArray);
    }
//Логика добаления и редактирования контакта
function AddNewContact() {
    createNewContact = true;
    let newContact = {
        id: 0,
        name: '',
        number: [''],
        email: ['']
    }

    OpenContactWindow(newContact);
}
function RemoveContact() {
    ContactsArray.splice(Contact.id, 1);
    localStorage.setItem('Contacts', JSON.stringify(ContactsArray));
    CloseContactWindow();
    ReloadContactList(ContactsArray);
}
function EditContact(id) {
    for (i = 0; i < ContactsArray.length; i++){
        if (ContactsArray[i].id == id){
            Contact = ContactsArray[i];
            createNewContact = false;
            OpenContactWindow(Contact);
            break;
        }
    }
}
function SaveContact() {

    let inputName = document.getElementById('name');
    let numberId0 = document.getElementById('number0');
    let emailId0 = document.getElementById('email0');

    SaveInputValue();

        if(inputName.value != '' && numberId0.value != '' && emailId0.value != '')
        {

    if (createNewContact) {
        ContactsArray.push(Contact);
    }

    ReloadContactList(ContactsArray)
    localStorage.setItem('Contacts', JSON.stringify(ContactsArray));

    CloseContactWindow();
        }
        else {
    if (numberId0.value == ''){
        numberId0.setAttribute('placeholder', 'Enter phone number');
    }
    if (emailId0.value == '') {
        emailId0.setAttribute('placeholder', 'Enter e-mail address')
    }
    if (inputName.value == ''){
        inputName.setAttribute('placeholder', 'Enter contact name')
    }
}
}
function SaveInputValue() {
    let inputName = document.getElementById('name');
    Contact.name = inputName.value;
    for(z = 0; z < Contact.number.length; z++){
        let numberId = document.getElementById('number'+z);
        Contact.number[z] = numberId.value;
    }
    for(y = 0; y < Contact.email.length; y++){
        let emailId = document.getElementById('email'+y);
        Contact.email[y] = emailId.value;
    }
}
//Логика переключения между списком контактов и формой добавления/редактирования контакта
function OpenContactWindow(contact) {

    Contact = contact;

    document.getElementById('contact-list').style.display = 'none';
    document.getElementById('header').style.display = 'none';
    document.getElementById('add-contact').style.display = 'flex';
    AddContactDrow();

    document.getElementById('save-contact').addEventListener('click', SaveContact, false);
    document.getElementById('reset-change').addEventListener('click', CloseContactWindow, false);
    if (!createNewContact) document.getElementById('removecontact').addEventListener('click', RemoveContact, false);

}
function CloseContactWindow() {
    document.getElementById('contact-list').style.display = 'flex';
    document.getElementById('header').style.display = 'flex';
    document.getElementById('add-contact').style.display = 'none';
    ContactsArray = JSON.parse(localStorage.getItem('Contacts'));

    ResetAddContactWindow();
    for (i = 0; i < Contact.number.length; i++){
        if (Contact.number[i] == '')
        {
            Contact.number.splice(i, 1);
        }
    }
    for (i = 0; i < Contact.email.length; i++){
        if (Contact.email[i] == '')
        {
            Contact.email.splice(i, 1);
        }
    }
    ReloadContactList(ContactsArray);
}
function ResetAddContactWindow() {
    let inputClean = document.getElementsByTagName('input');
    for (i = 0; i < inputClean.length; i++){
        inputClean[i].value = '';
    }

    let addContact = document.getElementById('add-contact');
    while (addContact.firstChild){
        addContact.removeChild(addContact.firstChild);
    }
}
function ReloadContactList(currentArray) {
    let contactList = document.getElementById('contact-list');
    while (contactList.firstChild){
        contactList.removeChild(contactList.firstChild);
    }
    currentArray.sort(function (x, y) {
        if (x.name > y.name)
            return 1;
        if (x.name < y.name)
            return -1;
        return 0;
    });

    if (currentArray != ContactsArray) {
        for (i = 0; i < currentArray.length; i++) {
            ContactListDraw(currentArray[i]);
        }
    } else {
        for (i = 0; i < ContactsArray.length; i++) {
            ContactsArray[i].id = i;

            ContactListDraw(currentArray[i]);
        }
    }
}
//Рисуем форму добавления и редактирования контакта
function AddContactDrow() {

    let contactForm = document.getElementById('add-contact');

    let headerDiv = document.createElement('div');
    headerDiv.setAttribute('class', 'text');
    contactForm.appendChild(headerDiv);
    let headerH = document.createElement('h2');
    if (createNewContact) {
        headerH.innerText = 'Add Contact';
    }else {
        headerH.innerText = 'Edit Contact';
        let removeContact = document.createElement('div');
        removeContact.setAttribute('id', 'removecontact');
        removeContact.innerText = 'Remove Contact';
        contactForm.appendChild(removeContact);
    }
    headerDiv.appendChild(headerH);

    for (element in Contact) {
        if (element == 'name') {
            let nameDiv = document.createElement('div');
            nameDiv.setAttribute('class', 'search');
            contactForm.appendChild(nameDiv);

            let nameSpan = document.createElement('span');
            nameSpan.innerText = 'Name';
            nameDiv.appendChild(nameSpan);
            let nameInput = document.createElement('input');
            nameInput.setAttribute('type', 'text');
            nameInput.setAttribute('id', 'name');
            nameDiv.appendChild(nameInput);
            nameInput.value = Contact.name;
            nameInput.oninput = function ()
            {
                let matchValue = /^[a-zA-Z\s]*$/;
                if (!nameInput.value.match(matchValue) || nameInput.value.length > 22)
                {
                    nameInput.value = nameInput.value.substr(0, nameInput.value.length - 1);
                }
            }
        }
        if (element == 'number') {
            for (l = 0; l < Contact.number.length; l++) {
                let phoneDiv = document.createElement('div');
                phoneDiv.setAttribute('class', 'search plus-minus-fields');
                phoneDiv.setAttribute('id', 'phone-number-div');
                contactForm.appendChild(phoneDiv);

                let minusDiv = document.createElement('div');
                minusDiv.setAttribute('class', 'button-minus-phone');
                minusDiv.innerText = '-';
                minusDiv.setAttribute('id', l);
                phoneDiv.appendChild(minusDiv);

                let phoneDivEmpty = document.createElement('div');
                phoneDiv.appendChild(phoneDivEmpty);

                let phoneSpan = document.createElement('span');
                if (l == 0){
                    phoneSpan.innerText = 'Phone Number';
                }else {
                    phoneSpan.innerText = 'More Phone Number';
                }

                phoneDivEmpty.appendChild(phoneSpan);
                let phoneInput = document.createElement('input');
                phoneInput.setAttribute('type', 'text');
                phoneInput.setAttribute('id', 'number'+l);
                phoneDivEmpty.appendChild(phoneInput);
                phoneInput.oninput = function ()
                {
                    if (isNaN(phoneInput.value+1) || phoneInput.value.length > 10)
                    {
                        phoneInput.value = phoneInput.value.substr(0, phoneInput.value.length - 1);
                    }
                }

                let plusDiv = document.createElement('div');
                plusDiv.setAttribute('class', 'button-plus-phone');
                plusDiv.innerText = '+';
                phoneDiv.appendChild(plusDiv);

                phoneInput.value = Contact.number[l];
            }
        }
        if (element == 'email') {
            for (h = 0; h < Contact.email.length; h++) {
                let emailDiv = document.createElement('div');
                emailDiv.setAttribute('class', 'search plus-minus-fields');
                emailDiv.setAttribute('id', 'email-div');
                contactForm.appendChild(emailDiv);

                let minusDiv = document.createElement('div');
                minusDiv.setAttribute('class', 'button-minus-email');
                minusDiv.innerText = '-';
                minusDiv.setAttribute('id', h);
                emailDiv.appendChild(minusDiv);

                let emailDivEmpty = document.createElement('div');
                emailDiv.appendChild(emailDivEmpty);

                let emailSpan = document.createElement('span');
                if (h == 0){
                    emailSpan.innerText = 'E-mail Address';
                }else {
                    emailSpan.innerText = 'More E-mail Address';
                }

                emailDivEmpty.appendChild(emailSpan);
                let emailInput = document.createElement('input');
                emailInput.setAttribute('type', 'text');
                emailInput.setAttribute('id', 'email'+h);
                emailDivEmpty.appendChild(emailInput);
                emailInput.oninput = function ()
                {
                    let matchValue = /^[a-z0-9@._]*$/;
                    if (!emailInput.value.match(matchValue) || emailInput.value.length > 25)
                    {
                        emailInput.value = emailInput.value.substr(0, emailInput.value.length - 1);
                    }
                }

                let plusDiv = document.createElement('div');
                plusDiv.setAttribute('class', 'button-plus-email');
                plusDiv.innerText = '+';
                emailDiv.appendChild(plusDiv);

                emailInput.value = Contact.email[h];
            }
        }
    }

    let buttonDiv = document.createElement('div');
    buttonDiv.setAttribute('class', 'search buttons');
    contactForm.appendChild(buttonDiv);

    let buttonOkDiv = document.createElement('div');
    buttonOkDiv.setAttribute('id', 'save-contact');
    buttonOkDiv.innerText = 'Ok';
    buttonDiv.appendChild(buttonOkDiv);

    let buttonCancelDiv = document.createElement('div');
    buttonCancelDiv.setAttribute('id', 'reset-change');
    buttonCancelDiv.innerText = 'Cancel';
    buttonDiv.appendChild(buttonCancelDiv);
}
function RemoveNumber(element) {
    if (element.id != 0){
        let removeElementParent = element.parentElement;
        let removeElement = removeElementParent.parentElement;
        removeElement.removeChild(removeElementParent);
        Contact.number.splice(element.id, 1);
    }
}
function AddNumber() {
    SaveInputValue();
    Contact.number[Contact.number.length] = '';
    ResetAddContactWindow();
    OpenContactWindow(Contact);

}
function RemoveMail(element) {
    if (element.id != 0) {
        let removeElementParent = element.parentElement;
        let removeElement = removeElementParent.parentElement;
        removeElement.removeChild(removeElementParent);
        Contact.email.splice(element.id, 1);
    }
}
function AddMail() {
    SaveInputValue();
    Contact.email[Contact.email.length] = '';
    ResetAddContactWindow();
    OpenContactWindow(Contact);
}
//Рисуеем список контактов
function ContactListDraw(contact) {

    let contactList = document.getElementById('contact-list');

    let listDiv = document.createElement("div");
    listDiv.setAttribute('class', 'list');
    contactList.appendChild(listDiv);

    let logoDiv = document.createElement("div");
    logoDiv.setAttribute('class', 'logo');
    logoDiv.setAttribute('id', contact.id);
    listDiv.appendChild(logoDiv);
    let logoSpan = document.createElement('span');
    logoSpan.setAttribute('class', 'logospan');
    logoSpan.setAttribute('id', contact.id);
    logoDiv.appendChild(logoSpan);
    logoSpan.innerText ='Z';

    let contactdataDiv = document.createElement("div");
    contactdataDiv.setAttribute('class', 'contactdata');
    listDiv.appendChild(contactdataDiv);

for (element in contact){
    if (element == 'name') CreateName(contactdataDiv, contact);
    if (element == 'number')
    {
        for (j = 0; j < contact.number.length; j++) {
            CreateNumber(contactdataDiv, contact.number[j]);
        }
    }
    if (element == 'email')
    {
        for (k = 0; k < contact.email.length; k++) {
            CreateEmail(contactdataDiv, contact.email[k]);
        }
    }
}

}
function CreateName(Div, contact) {
    let nameDiv = document.createElement("div");
    nameDiv.setAttribute('class', 'name');
    Div.appendChild(nameDiv);
    nameDiv.innerText = contact.name;
}
function CreateNumber(Div, contact) {
    let phoneDiv = document.createElement("div");
    phoneDiv.setAttribute('class', 'phone');
    Div.appendChild(phoneDiv);
    phoneDiv.innerText = contact;
}
function CreateEmail(Div,contact) {
    let emailDiv = document.createElement("div");
    emailDiv.setAttribute('class', 'email');
    Div.appendChild(emailDiv);
    emailDiv.innerText = contact;
}<|endoftext|>


<commit_before>// ==UserScript==
// @name         Apple documentation class link
// @namespace    https://franklinyu.github.io/
// @version      0.2
// @description  create link for classes in code segments
// @icon         https://commons.wikimedia.org/wiki/File:Apple_Store_logo.svg
// @author       Franklin Yu
// @include      https://developer.apple.com/reference/*
// @grant        none
// ==/UserScript==

for (let span of document.getElementsByClassName('syntax-type')) {
	let className = span.textContent;
	if (! /^\w+$/.test(className)) {
		console.warn("class name not recognized in", span);
		continue;
	}
	(async function() {
		const response = await fetch('/search/search_data.php?&q=' + className);
		if (! response.ok) {
			console.error("get %s when searching class %s", response.statusText, className);
			console.info('response:', response);
			throw new Error('Unexpected response');
		}
		const json = await response.json();
		if (json[0].title === className) {
			let anchor = document.createElement('A'); // HTMLAnchorElement
			anchor.href = result.url;
			span.replaceWith(anchor);
			anchor.appendChild(span);
		} else {
			console.warn("can't find %s in search results.", className);
			console.info('response:', response);
		}
	})();
}
<commit_msg>Fix Apple logo<commit_after>// ==UserScript==
// @name         Apple documentation class link
// @namespace    https://franklinyu.github.io/
// @version      0.2
// @description  create link for classes in code segments
// @icon         https://upload.wikimedia.org/wikipedia/commons/4/46/Apple_Store_logo.svg
// @author       Franklin Yu
// @include      https://developer.apple.com/reference/*
// @grant        none
// ==/UserScript==

for (let span of document.getElementsByClassName('syntax-type')) {
	let className = span.textContent;
	if (! /^\w+$/.test(className)) {
		console.warn("class name not recognized in", span);
		continue;
	}
	(async function() {
		const response = await fetch('/search/search_data.php?&q=' + className);
		if (! response.ok) {
			console.error("get %s when searching class %s", response.statusText, className);
			console.info('response:', response);
			throw new Error('Unexpected response');
		}
		const json = await response.json();
		if (json[0].title === className) {
			let anchor = document.createElement('A'); // HTMLAnchorElement
			anchor.href = result.url;
			span.replaceWith(anchor);
			anchor.appendChild(span);
		} else {
			console.warn("can't find %s in search results.", className);
			console.info('response:', response);
		}
	})();
}
<|endoftext|>


<commit_before>// Original source: https://varvy.com/pagespeed/defer-images.html

/* jshint browser:true */

(function() {
    "use strict";

    function imgDefer() {
        var imgElement = document.getElementsByTagName("img");

        for (var i = 0; i < imgElement.length; i++) {
            if (imgElement[i].hasAttribute("data-src")) {
                imgElement[i].setAttribute("src", imgElement[i].getAttribute("data-src"));
                imgElement[i].removeAttribute("data-src");
                imgElement[i].className += " loaded";
            }
        }
    }

    if (window.addEventListener) {
        window.addEventListener("load", imgDefer, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", imgDefer);
    } else {
        window.onload = imgDefer;
    }
}());
<commit_msg>img-defer.js: minor optimization.<commit_after>// Original source: https://varvy.com/pagespeed/defer-images.html

/* jshint browser:true */

(function() {
    "use strict";

    function imgDefer() {
        var imgElement = document.getElementsByTagName("img");

        for (var i = 0, len = imgElement.length; i < len; i++) {
            if (imgElement[i].hasAttribute("data-src")) {
                imgElement[i].setAttribute("src", imgElement[i].getAttribute("data-src"));
                imgElement[i].removeAttribute("data-src");
                imgElement[i].className += " loaded";
            }
        }
    }

    if (window.addEventListener) {
        window.addEventListener("load", imgDefer, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", imgDefer);
    } else {
        window.onload = imgDefer;
    }
}());
<|endoftext|>


<commit_before>import { THREE } from 'three';
import { AssetLoader } from "engine/utils/AssetLoader";
import { Shader } from "engine/model/Shader";
import { Texture } from "engine/model/Texture";

let assetLoader = new AssetLoader();

export class Star {
	constructor(temp, size, position) {
		let Star = this;
		Star.loaded = false;
		Star._mesh;
		Star.flow = 0.0;
		Star.color = temp ? temp : 0xffffff;
		Star.size = size ? size : 5;
		Star.position = position ? position : {x:0,y:0};
		Star.raysFadeToggle = true;
	}

	load() {

		let Star = this;

		let starColor = new THREE.Color(Star.color);

		let loadAllPromise = assetLoader.loadAll([
			new Shader("src/game/resources/shaders/sun.fs.glsl"),
			new Shader("src/game/resources/shaders/sun.vs.glsl"),
			new Shader("src/game/resources/shaders/corona.fs.glsl"),
			new Shader("src/game/resources/shaders/corona.vs.glsl"),
			new Texture("src/game/resources/textures/star/corona.png", "coronaMap"),
			new Texture("src/game/resources/textures/star/blink.png", "raysMap")
		]).then(function(resources) {

			let starMesh = new THREE.Object3D();

			let baseUniforms = {
				flow: { type: 'f', value: 0.01 },
			  	color:     { type: "c", value: new THREE.Color( Star.color ) },
			};

			Star.baseUniforms = baseUniforms;

			let baseGeometry  = new THREE.SphereBufferGeometry(Star.size, 16, 16);

			let baseMaterial = new THREE.ShaderMaterial({
				uniforms:       baseUniforms,
				vertexShader:   resources.shaders.get("sun-vs").program,
				fragmentShader: resources.shaders.get("sun-fs").program
			});
			let baseMesh = new THREE.Mesh(baseGeometry, baseMaterial);
			baseMesh.position.x = Star.position.x;
			baseMesh.position.y = Star.position.y;
			starMesh.add(baseMesh);

			//let coronaGeometry = new THREE.CircleGeometry( Star.size+(Star.size/10), 32 );
			let coronaGeometry = new THREE.CircleGeometry( 1, 64 );

			Star.coronaUniforms = {
				alpha: { type: "f", value: 5 },
				color: { type: "c", value: new THREE.Color( starColor.clone().addScalar(100) ) },
                scale: { type: "v3", value:new THREE.Vector3(Star.size+(Star.size/8),Star.size+(Star.size/8),1)}
            };

            let coronaMaterial = new THREE.ShaderMaterial( {
                uniforms: Star.coronaUniforms,
                vertexShader: resources.shaders.get("corona-vs").program,
                fragmentShader: resources.shaders.get("corona-fs").program,
                transparent: true,
                blending:THREE.AdditiveBlending

            } );

   			//let coronaMaterial = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
            let coronaMesh = new THREE.Mesh( coronaGeometry, coronaMaterial );

            baseMesh.add(coronaMesh);

			let rayOneMaterial = new THREE.SpriteMaterial({
				map: resources.textures.get("raysMap"),
				transparent: true,
				opacity: 1,
				depthWrite: false,
				depthTest: false,
				color: starColor.clone().addScalar(15)
			});
			let rayOneMesh = new THREE.Sprite(rayOneMaterial)

			Star.raysOne = rayOneMesh;
			Star.raysOne.fading = true;
			Star.raysOne.scale.set(Star.size*8,Star.size*8,1);

			baseMesh.add(Star.raysOne);

			let rayTwoMaterial = new THREE.SpriteMaterial({
				map: resources.textures.get("raysMap"),
				transparent: true,
				opacity: 0.25,
				rotation: 7,
				color: starColor.clone().addScalar(0.5)
			});
			let rayTwoMesh = new THREE.Sprite(rayTwoMaterial);

			Star.raysTwo = rayTwoMesh;
			Star.raysTwo.fading = true;
			Star.raysTwo.scale.set(Star.size*10,Star.size*10,1);

			baseMesh.add(Star.raysTwo);

			Star._mesh = starMesh;
			Star.loaded = true;

		});

		return loadAllPromise;

	}

	getMesh() {
		return this._mesh;
	}

	update(delta) {

		let Star = this;
		if(!Star.loaded) return;

		Star.baseUniforms.flow.value = Star.flow;

		Star.flow +=  Math.sin(delta * 0.25);

		let fadeValue = 0.025 * delta
		if(!Star.raysFadeToggle) fadeValue = -(fadeValue);

		Star.raysOne.material.rotation += 0.01 * delta;
		Star.raysOne.material.opacity += fadeValue;

		Star.raysTwo.material.rotation -= 0.005 * delta;
		Star.raysTwo.material.opacity -= fadeValue;

		Star.coronaUniforms.alpha.value += fadeValue*20;

		if(Star.raysOne.material.opacity > 1) Star.raysFadeToggle = false;
		if(Star.raysOne.material.opacity < 0.75) Star.raysFadeToggle = true;

	}

}<commit_msg>Fixed ocilation of opacity on sun rays<commit_after>import { THREE } from 'three';
import { AssetLoader } from "engine/utils/AssetLoader";
import { Shader } from "engine/model/Shader";
import { Texture } from "engine/model/Texture";

let assetLoader = new AssetLoader();

export class Star {
	constructor(temp, size, position) {
		let Star = this;
		Star.loaded = false;
		Star._mesh;
		Star.flow = 0.0;
		Star.color = temp ? temp : 0xffffff;
		Star.size = size ? size : 5;
		Star.position = position ? position : {x:0,y:0};
		Star.raysFadeToggle = true;
	}

	load() {

		let Star = this;

		let starColor = new THREE.Color(Star.color);

		let loadAllPromise = assetLoader.loadAll([
			new Shader("src/game/resources/shaders/sun.fs.glsl"),
			new Shader("src/game/resources/shaders/sun.vs.glsl"),
			new Shader("src/game/resources/shaders/corona.fs.glsl"),
			new Shader("src/game/resources/shaders/corona.vs.glsl"),
			new Texture("src/game/resources/textures/star/corona.png", "coronaMap"),
			new Texture("src/game/resources/textures/star/blink.png", "raysMap")
		]).then(function(resources) {

			let starMesh = new THREE.Object3D();

			let baseUniforms = {
				flow: { type: 'f', value: 0.01 },
			  	color:     { type: "c", value: new THREE.Color( Star.color ) },
			};

			Star.baseUniforms = baseUniforms;

			let baseGeometry  = new THREE.SphereBufferGeometry(Star.size, 16, 16);

			let baseMaterial = new THREE.ShaderMaterial({
				uniforms:       baseUniforms,
				vertexShader:   resources.shaders.get("sun-vs").program,
				fragmentShader: resources.shaders.get("sun-fs").program
			});
			let baseMesh = new THREE.Mesh(baseGeometry, baseMaterial);
			baseMesh.position.x = Star.position.x;
			baseMesh.position.y = Star.position.y;
			starMesh.add(baseMesh);

			//let coronaGeometry = new THREE.CircleGeometry( Star.size+(Star.size/10), 32 );
			let coronaGeometry = new THREE.CircleGeometry( 1, 64 );

			Star.coronaUniforms = {
				alpha: { type: "f", value: 5 },
				color: { type: "c", value: new THREE.Color( starColor.clone().addScalar(100) ) },
                scale: { type: "v3", value:new THREE.Vector3(Star.size+(Star.size/10),Star.size+(Star.size/8),1)}
            };

            let coronaMaterial = new THREE.ShaderMaterial( {
                uniforms: Star.coronaUniforms,
                vertexShader: resources.shaders.get("corona-vs").program,
                fragmentShader: resources.shaders.get("corona-fs").program,
                transparent: true,
                blending:THREE.AdditiveBlending

            } );

   			//let coronaMaterial = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
            let coronaMesh = new THREE.Mesh( coronaGeometry, coronaMaterial );

            baseMesh.add(coronaMesh);

			let rayOneMaterial = new THREE.SpriteMaterial({
				map: resources.textures.get("raysMap"),
				transparent: true,
				opacity: 1,
				depthWrite: false,
				depthTest: false,
				color: starColor.clone().addScalar(15)
			});
			let rayOneMesh = new THREE.Sprite(rayOneMaterial)

			Star.raysOne = rayOneMesh;
			Star.raysOne.fading = true;
			Star.raysOne.scale.set(Star.size*8,Star.size*8,1);

			baseMesh.add(Star.raysOne);

			let rayTwoMaterial = new THREE.SpriteMaterial({
				map: resources.textures.get("raysMap"),
				transparent: true,
				opacity: 0.25,
				rotation: 7,
				color: starColor.clone().addScalar(0.5)
			});
			let rayTwoMesh = new THREE.Sprite(rayTwoMaterial);

			Star.raysTwo = rayTwoMesh;
			Star.raysTwo.fading = true;
			Star.raysTwo.scale.set(Star.size*10,Star.size*10,1);

			baseMesh.add(Star.raysTwo);

			Star._mesh = starMesh;
			Star.loaded = true;

		});

		return loadAllPromise;

	}

	getMesh() {
		return this._mesh;
	}

	update(delta) {

		let Star = this;
		if(!Star.loaded) return;

		Star.baseUniforms.flow.value = Star.flow;

		Star.flow +=  delta * 0.25;

		Star.raysOne.material.rotation = Star.flow/25;
		Star.raysOne.material.opacity = Math.abs(0.3 * Math.sin(Star.flow))+0.5;

		Star.raysTwo.material.rotation = -(Star.flow/20);
		Star.raysTwo.material.opacity = Math.abs(0.3 * Math.cos(Star.flow))+0.25;

	}

}<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2022 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var NOOP = require('../../../utils/NOOP');

if (typeof WEBGL_RENDERER)
{
    renderWebGL = require('./StarWebGLRenderer');
}

if (typeof CANVAS_RENDERER)
{
    renderCanvas = require('./StarCanvasRenderer');
}

module.exports = {

    renderWebGL: renderWebGL,
    renderCanvas: renderCanvas

};
<commit_msg>Fix copy-paste error in StarRender.<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2022 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var NOOP = require('../../../utils/NOOP');
var renderWebGL = NOOP, renderCanvas = NOOP;

if (typeof WEBGL_RENDERER)
{
    renderWebGL = require('./StarWebGLRenderer');
}

if (typeof CANVAS_RENDERER)
{
    renderCanvas = require('./StarCanvasRenderer');
}

module.exports = {

    renderWebGL: renderWebGL,
    renderCanvas: renderCanvas

};
<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');
var Engine = require('../../../engine');

var NON_RESETEABLE_DEFAULT_ATTRS = ['state', 'visible'];

var LegendModelBase = Backbone.Model.extend({
  defaults: function () {
    return {
      visible: false,
      title: '',
      preHTMLSnippet: '',
      postHTMLSnippet: '',
      state: this.constructor.STATE_LOADING
    };
  },

  initialize: function (attrs, deps) {
    if (!deps.engine) throw new Error('engine is required');
    var self = this;
    deps.engine.on(Engine.Events.RELOAD_STARTED, function () {
      self.set('state', self.constructor.STATE_LOADING);
    });
  },

  isLoading: function () {
    return this.get('state') === this.constructor.STATE_LOADING;
  },

  isError: function () {
    return this.get('state') === this.constructor.STATE_ERROR;
  },

  isSuccess: function () {
    return this.get('state') === this.constructor.STATE_SUCCESS;
  },

  show: function () {
    this.set('visible', true);
  },

  hide: function () {
    this.set('visible', false);
  },

  isVisible: function () {
    return this.get('visible');
  },

  update: function (attrs) {
    this.set(attrs);
  },

  getNonResettableAttrs: function () {
    return NON_RESETEABLE_DEFAULT_ATTRS;
  },

  reset: function () {
    var defaults = _.omit(this.defaults(),
      this.getNonResettableAttrs()
    );
    this.set(defaults);
  },

  isAvailable: function () {
    return false;
  }
}, {
  STATE_LOADING: 'loading',
  STATE_SUCCESS: 'success',
  STATE_ERROR: 'error'
});

module.exports = LegendModelBase;
<commit_msg>Stop using self<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var Engine = require('../../../engine');

var NON_RESETEABLE_DEFAULT_ATTRS = ['state', 'visible'];

var LegendModelBase = Backbone.Model.extend({
  defaults: function () {
    return {
      visible: false,
      title: '',
      preHTMLSnippet: '',
      postHTMLSnippet: '',
      state: this.constructor.STATE_LOADING
    };
  },

  initialize: function (attrs, deps) {
    if (!deps.engine) throw new Error('engine is required');

    deps.engine.on(Engine.Events.RELOAD_STARTED, function () {
      this.set('state', this.constructor.STATE_LOADING);
    }.bind(this));
  },

  isLoading: function () {
    return this.get('state') === this.constructor.STATE_LOADING;
  },

  isError: function () {
    return this.get('state') === this.constructor.STATE_ERROR;
  },

  isSuccess: function () {
    return this.get('state') === this.constructor.STATE_SUCCESS;
  },

  show: function () {
    this.set('visible', true);
  },

  hide: function () {
    this.set('visible', false);
  },

  isVisible: function () {
    return this.get('visible');
  },

  update: function (attrs) {
    this.set(attrs);
  },

  getNonResettableAttrs: function () {
    return NON_RESETEABLE_DEFAULT_ATTRS;
  },

  reset: function () {
    var defaults = _.omit(this.defaults(),
      this.getNonResettableAttrs()
    );
    this.set(defaults);
  },

  isAvailable: function () {
    return false;
  }
}, {
  STATE_LOADING: 'loading',
  STATE_SUCCESS: 'success',
  STATE_ERROR: 'error'
});

module.exports = LegendModelBase;
<|endoftext|>


<commit_before>export default function Vector(x, y, immutable) {
    this.immutable = immutable || false;
    this.x = x || 0;
    this.y = y || 0;
}

Vector.prototype = {
    /**
     *  Utility
     */
    clone: function () {
        return new Vector(this.x, this.y);
    },

    equals: function (vector) {
        return this.x === vector.x && this.y === vector.y;
    },

    /**
     *  Properties
     */
    get length() {
        return Math.sqrt(this.dot(this));
    },

    set length(value) {
        this.normalize().multiply(value);
    },

    get angle() {
        return this.radians * 180 / Math.PI;
    },

    set angle(value) {
        this.radians(value * Math.PI / 180);
    },

    get radians() {
        return Math.atan2(this.y, this.x);
    },

    set radians(value) {
        this.set(
            Math.cos(value) * this.length,
            Math.sin(value) * this.length
        );
    },

    /**
     *  Manipulation
     */
    set: function () {
        vectorArg(arguments, (x, y) => {
            this.x = x;
            this.y = y;
        });
        return this;
    },

    add: function (value) {
        vectorArg(value, (x, y) => {
            this.x += x;
            this.y += y;
        });
        return this;
    },

    subtract: function (value) {
        vectorArg(value, (x, y) => {
            this.x -= x;
            this.y -= y;
        });
        return this;
    },

    multiply: function (value) {
        vectorArg(value, (x, y) => {
            this.x *= x;
            this.y *= y;
        });
        return this;
    },

    divide: function (value) {
        vectorArg(value, (x, y) => {
            if (x !== 0) this.x /= x;
            if (y !== 0) this.y /= y;
        });
        return this;
    },

    negate: function () {
        this.x *= -1;
        this.y *= -1;
        return this;
    },

    normalize: function (value = 1) {
        this.multiply(value / this.length);
        return this;
    },

    limit: function (value) {
        if (this.length > value) {
            this.normalize(value);
        }
        return this;
    },

    magnitude: function (value) {
        this.length = value;
        return this;
    },

    rotate: function (angle) {
        if (angle) {
            const rad = (this.angle + angle) * Math.PI / 180;
            const length = this.length;
            this.x = Math.cos(rad) * length;
            this.y = Math.sin(rad) * length;
        }
        return this;
    },

    /**
     *  Products
     */
    dot: function (vector) {
        return this.x * vector.x + this.y * vector.y;
    },

    cross: function (vector) {
        return this.x * vector.y - this.y * vector.x
    },

    distance: function (vector) {
        const x = this.x - vector.x;
        const y = this.y - vector.y;
        return Math.sqrt((x * x) + (y * y));
    },

    angleTo: function (vector) {
        return this.radiansTo(vector) * 180 / Math.PI;
    },

    radiansTo: function (vector) {
        const length = this.length * vector.length;
        return length === 0 ? NaN : Math.acos(this.dot(vector) / length);
    }
}

Vector.random = function (a = 1, b = 1) {
    return new Vector(a * Math.random(), b * Math.random());
}

function vectorArg(value, callback) {
    if (typeof value === 'number') {
        callback(value, value);

    } else if (value instanceof Vector) {
        callback(value.x, value.y);

    } else if (isArguments(value)) {
        const x = value[0];
        if (x !== undefined) {
            const y = value[1] !== undefined
                ? value[1]
                : value[0];
            callback(x, y);
        }
    }
}

function isZero(vector) {
    return vector.x === 0 && vector.y === 0;
}

function isArguments(value) {
    return value && value.hasOwnProperty('callee') || false;
}<commit_msg>immutable methods and fallback of new operator<commit_after>function Vector(x, y) {
    if (!(this instanceof Vector)) {
        return new Vector(x, y);
    }
    this.x = x || 0;
    this.y = y || 0;
}

const prototypes = {
    /**
     *  Utility
     */
    clone: function () {
        return new Vector(this.x, this.y);
    },

    equals: function (vector) {
        return this.x === vector.x && this.y === vector.y;
    },

    /**
     *  Properties
     */
    get length() {
        return Math.sqrt(this.dot(this));
    },

    set length(value) {
        this.normalize().multiply(value);
    },

    get angle() {
        return this.radians * 180 / Math.PI;
    },

    set angle(value) {
        this.radians(value * Math.PI / 180);
    },

    get radians() {
        return Math.atan2(this.y, this.x);
    },

    set radians(value) {
        this.set(
            Math.cos(value) * this.length,
            Math.sin(value) * this.length
        );
    },

    /**
     *  Manipulation
     */
    set: function () {
        vectorArg(arguments, (x, y) => {
            this.x = x;
            this.y = y;
        });
        return this;
    },

    add: function (value) {
        vectorArg(value, (x, y) => {
            this.x += x;
            this.y += y;
        });
        return this;
    },

    subtract: function (value) {
        vectorArg(value, (x, y) => {
            this.x -= x;
            this.y -= y;
        });
        return this;
    },

    multiply: function (value) {
        vectorArg(value, (x, y) => {
            this.x *= x;
            this.y *= y;
        });
        return this;
    },

    divide: function (value) {
        vectorArg(value, (x, y) => {
            if (x !== 0) this.x /= x;
            if (y !== 0) this.y /= y;
        });
        return this;
    },

    negate: function () {
        this.x *= -1;
        this.y *= -1;
        return this;
    },

    normalize: function (value = 1) {
        this.multiply(value / this.length);
        return this;
    },

    limit: function (value) {
        if (this.length > value) {
            this.normalize(value);
        }
        return this;
    },

    magnitude: function (value) {
        this.length = value;
        return this;
    },

    rotate: function (angle) {
        if (angle) {
            const rad = (this.angle + angle) * Math.PI / 180;
            const length = this.length;
            this.x = Math.cos(rad) * length;
            this.y = Math.sin(rad) * length;
        }
        return this;
    },

    /**
     *  Products
     */
    dot: function (vector) {
        return this.x * vector.x + this.y * vector.y;
    },

    cross: function (vector) {
        return this.x * vector.y - this.y * vector.x
    },

    distance: function (vector) {
        const x = this.x - vector.x;
        const y = this.y - vector.y;
        return Math.sqrt((x * x) + (y * y));
    },

    angleTo: function (vector) {
        return this.radiansTo(vector) * 180 / Math.PI;
    },

    radiansTo: function (vector) {
        const length = this.length * vector.length;
        return length === 0 ? NaN : Math.acos(this.dot(vector) / length);
    }
}

Vector.random = function (a = 1, b = 1) {
    return new Vector(a * Math.random(), b * Math.random());
}

Vector.prototype = addImmutable(prototypes, [
    'set',
    'add',
    'subtract',
    'multiply',
    'divide',
    'negate',
    'normalize',
    'limit',
    'magnitude',
    'rotate',
]);

function vectorArg(value, callback) {
    if (typeof value === 'number') {
        callback(value, value);

    } else if (value instanceof Vector) {
        callback(value.x, value.y);

    } else if (isArguments(value)) {
        const x = value[0];
        if (x !== undefined) {
            const y = value[1] !== undefined
                ? value[1]
                : value[0];
            callback(x, y);
        }
    }
}

function immutable(method) {
    return function () {
        const next = this.clone();
        return next[method].apply(next, arguments);
    }
}

function addImmutable(proto, methods) {
    for (let i = 0; i < methods.length; i++) {
        let name = methods[i];
        proto['i' + name] = immutable(name);
    }
    return proto;
}

function isArguments(value) {
    return value && value.hasOwnProperty('callee') || false;
}

module.exports = Vector;<|endoftext|>


<commit_before>
XMOT.namespace("XMOT.interaction.behaviors");

/** A plane sensor is a pointing device sensor that maps the movement of
 *  the pointing device on a plane. Listeners can be registered for the
 *  event "translchanged", which is raised whenever the pointing
 *  device changed the position on that plane.
 *  In this case the translation property gives the translation since the
 *  start of dragging.
 *
 *  In addition a constraint can be specified to adjust the calculated translation.
 *
 *  One handy thing is the getCanonicalTranslation() method. No matter what the
 *  current plane origin or normal is, this returns the translation in the
 *  canonical [o: (0,0,0), d: (0,0,1)] plane. This comes in handy when
 *  you need to rely on two dimensions (often the case with mouse).
 *
 *  @extends XMOT.interaction.behaviors.PDSensor
 */

XMOT.interaction.behaviors.PlaneSensor = new XMOT.Class(
    XMOT.interaction.behaviors.PDSensor,
{
    /** Constructor of PlaneSensor
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *
     *  @param {string} id the id of this sensor
     *  @param {Array.<Object>} grps the groups this sensor should look for
     *  @param {window.XML3DVec3|!Object=} planeOrient the group or vector the sensor takes to decide where the plane
     * 			normal should reside. If it's a group the local z=0 plane of the given group is taken.
     * 			If a vector is given, the vector directly is taken. If not specified a plane
     * 			parallel to the user's view is taken.
     *  @param {Object=} translationConstraint constraint that is applied to the final translation output
     */
    initialize: function(id, grps, planeOrient, translationConstraint)
    {
        this.callSuper(id, grps);

        // the translation in the plane during a drag operation
        this.translation = new window.XML3DVec3(0,0,0);

        this._plane = new XMOT.util.Plane(this.xml3d);
        this._plane.setOrientation(planeOrient);

        this._canonicalPlane = new XMOT.util.Plane(this.xml3d);
        this._canonicalPlane.normal(new XML3DVec3(0,0,1));

        /** The translation constraint for constraining the final output value */
        if(translationConstraint !== undefined && translationConstraint !== null)
            this._translationConstraint = translationConstraint;
        else
            this._translationConstraint = new XMOT.BoxedTranslationConstraint();

        // setup listeners
        this.addListenerTypes("translchanged");

        this.addListener("dragstart", this.callback("_onPlaneDragStart"));
        this.addListener("drag", this.callback("_onPlaneDrag"));
        this.addListener("dragend", this.callback("_onPlaneDragEnd"));
    },

    /** retrieve the current translation value in the canonical
     *  plane [o: (0,0,0), d: (0,0,1)] no matter what the current origin or
     *  normal is.
     *
     *  In this method no constraints are applied!
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *
     *  @return {XML3DVec3}
     */
    getCanonicalTranslation: function()
    {
        /*
        var mat = XMOT.math.getTransformPlaneToPlane(this._plane.origin(), this._plane.normal());

        var torig = mat.multiplyPt(this._plane.origin());
        var tp = mat.multiplyPt(this._plane.origin().add(this.translation));
        tp = tp.subtract(torig);

        return tp;
        */

        return this.canonicalTranslation;
    },

    // ========================================================================
    // --- Private ---
    // ========================================================================

    // --- Drag methods ---
    /** Callback for PDSensor's dragstart event
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @param {XMOT.interaction.behaviors.PDSensor} sensor
     */
    _onPlaneDragStart: function(sensor)
    {
        this._plane.origin(sensor.curHitPoint);
        this._planeHitPoint = this._plane.origin();

        this._canonicalPlane.origin(sensor.curHitPoint);
        this._canonicalPlaneHitPoint = this._canonicalPlane.origin();
    },

    /** Callback for PDSensor's drag event
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @param {XMOT.interaction.behaviors.PDSensor} sensor
     */
    _onPlaneDrag: function(sensor)
    {
        var hitP = this._calcPlaneHitPoint();
        if(!hitP)
            return;
        this._planeHitPoint = hitP;

        var canHitP = this._calcCanonicalPlaneHitPoint();
        if(canHitP)
            this._canonicalPlaneHitPoint = canHitP;

        this._calcTranslation();

        this.notifyListeners("translchanged", this);
    },

    /** Callback for PDSensor's dragend event
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @param {XMOT.interaction.behaviors.PDSensor} sensor
     */
    _onPlaneDragEnd: function(sensor)
    {
    },

    /** Calculate the hit point on the sensor's plane.
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @return {XML3DVec3} the hit point or null in case no hit occured
     */
    _calcPlaneHitPoint: function()
    {
        // intersect ray with view plane norm
        var intersectHitP = new window.XML3DVec3();

        if(1 !== XMOT.math.intersectRayPlane(this.pdPose,
            this._plane.origin(), this._plane.normal(), intersectHitP))
        {
            // either didnt hit or whole ray lies on plane
            // ignore it
            return null;
        }

        return intersectHitP;
    },

    /** Calculate the hit point on the sensor's plane.
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @return {XML3DVec3} the hit point or null in case no hit occured
     */
    _calcCanonicalPlaneHitPoint: function()
    {
        // intersect ray with view plane norm
        var intersectHitP = new window.XML3DVec3();

        if(1 !== XMOT.math.intersectRayPlane(this.pdPose,
            this._canonicalPlane.origin(), this._canonicalPlane.normal(), intersectHitP))
        {
            // either didnt hit or whole ray lies on plane
            // ignore it
            return null;
        }

        return intersectHitP;
    },

    /** Calculate translation based on the current _planeHitPoint
     *  and apply translation offset and constrain it. It will set
     *  the translation property of this instance.
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     */
    _calcTranslation: function()
    {
        var transl = this._planeHitPoint.subtract(this._plane.origin());
        var canTransl = this._canonicalPlaneHitPoint.subtract(this._canonicalPlane.origin());

        if(this._translationConstraint.constrainTranslation(transl))
        {
            this.translation.set(transl);
            this.canonicalTranslation = canTransl;
        }
    }
});
<commit_msg>interaction-planesensor: fixed a return value<commit_after>
XMOT.namespace("XMOT.interaction.behaviors");

/** A plane sensor is a pointing device sensor that maps the movement of
 *  the pointing device on a plane. Listeners can be registered for the
 *  event "translchanged", which is raised whenever the pointing
 *  device changed the position on that plane.
 *  In this case the translation property gives the translation since the
 *  start of dragging.
 *
 *  In addition a constraint can be specified to adjust the calculated translation.
 *
 *  One handy thing is the getCanonicalTranslation() method. No matter what the
 *  current plane origin or normal is, this returns the translation in the
 *  canonical [o: (0,0,0), d: (0,0,1)] plane. This comes in handy when
 *  you need to rely on two dimensions (often the case with mouse).
 *
 *  @extends XMOT.interaction.behaviors.PDSensor
 */

XMOT.interaction.behaviors.PlaneSensor = new XMOT.Class(
    XMOT.interaction.behaviors.PDSensor,
{
    /** Constructor of PlaneSensor
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *
     *  @param {string} id the id of this sensor
     *  @param {Array.<Object>} grps the groups this sensor should look for
     *  @param {window.XML3DVec3|!Object=} planeOrient the group or vector the sensor takes to decide where the plane
     * 			normal should reside. If it's a group the local z=0 plane of the given group is taken.
     * 			If a vector is given, the vector directly is taken. If not specified a plane
     * 			parallel to the user's view is taken.
     *  @param {Object=} translationConstraint constraint that is applied to the final translation output
     */
    initialize: function(id, grps, planeOrient, translationConstraint)
    {
        this.callSuper(id, grps);

        // the translation in the plane during a drag operation
        this.translation = new window.XML3DVec3(0,0,0);

        this._plane = new XMOT.util.Plane(this.xml3d);
        this._plane.setOrientation(planeOrient);

        this._canonicalPlane = new XMOT.util.Plane(this.xml3d);
        this._canonicalPlane.normal(new XML3DVec3(0,0,1));

        /** The translation constraint for constraining the final output value */
        if(translationConstraint !== undefined && translationConstraint !== null)
            this._translationConstraint = translationConstraint;
        else
            this._translationConstraint = new XMOT.BoxedTranslationConstraint();

        // setup listeners
        this.addListenerTypes("translchanged");

        this.addListener("dragstart", this.callback("_onPlaneDragStart"));
        this.addListener("drag", this.callback("_onPlaneDrag"));
        this.addListener("dragend", this.callback("_onPlaneDragEnd"));
    },

    /** retrieve the current translation value in the canonical
     *  plane [o: (0,0,0), d: (0,0,1)] no matter what the current origin or
     *  normal is.
     *
     *  In this method no constraints are applied!
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *
     *  @return {XML3DVec3}
     */
    getCanonicalTranslation: function()
    {
        /*
        var mat = XMOT.math.getTransformPlaneToPlane(this._plane.origin(), this._plane.normal());

        var torig = mat.multiplyPt(this._plane.origin());
        var tp = mat.multiplyPt(this._plane.origin().add(this.translation));
        tp = tp.subtract(torig);

        return tp;
        */

        return new XML3DVec3(this.canonicalTranslation);
    },

    // ========================================================================
    // --- Private ---
    // ========================================================================

    // --- Drag methods ---
    /** Callback for PDSensor's dragstart event
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @param {XMOT.interaction.behaviors.PDSensor} sensor
     */
    _onPlaneDragStart: function(sensor)
    {
        this._plane.origin(sensor.curHitPoint);
        this._planeHitPoint = this._plane.origin();

        this._canonicalPlane.origin(sensor.curHitPoint);
        this._canonicalPlaneHitPoint = this._canonicalPlane.origin();
    },

    /** Callback for PDSensor's drag event
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @param {XMOT.interaction.behaviors.PDSensor} sensor
     */
    _onPlaneDrag: function(sensor)
    {
        var hitP = this._calcPlaneHitPoint();
        if(!hitP)
            return;
        this._planeHitPoint = hitP;

        var canHitP = this._calcCanonicalPlaneHitPoint();
        if(canHitP)
            this._canonicalPlaneHitPoint = canHitP;

        this._calcTranslation();

        this.notifyListeners("translchanged", this);
    },

    /** Callback for PDSensor's dragend event
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @param {XMOT.interaction.behaviors.PDSensor} sensor
     */
    _onPlaneDragEnd: function(sensor)
    {
    },

    /** Calculate the hit point on the sensor's plane.
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @return {XML3DVec3} the hit point or null in case no hit occured
     */
    _calcPlaneHitPoint: function()
    {
        // intersect ray with view plane norm
        var intersectHitP = new window.XML3DVec3();

        if(1 !== XMOT.math.intersectRayPlane(this.pdPose,
            this._plane.origin(), this._plane.normal(), intersectHitP))
        {
            // either didnt hit or whole ray lies on plane
            // ignore it
            return null;
        }

        return intersectHitP;
    },

    /** Calculate the hit point on the sensor's plane.
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     *
     *  @return {XML3DVec3} the hit point or null in case no hit occured
     */
    _calcCanonicalPlaneHitPoint: function()
    {
        // intersect ray with view plane norm
        var intersectHitP = new window.XML3DVec3();

        if(1 !== XMOT.math.intersectRayPlane(this.pdPose,
            this._canonicalPlane.origin(), this._canonicalPlane.normal(), intersectHitP))
        {
            // either didnt hit or whole ray lies on plane
            // ignore it
            return null;
        }

        return intersectHitP;
    },

    /** Calculate translation based on the current _planeHitPoint
     *  and apply translation offset and constrain it. It will set
     *  the translation property of this instance.
     *
     *  @this {XMOT.interaction.behaviors.PlaneSensor}
     *  @private
     */
    _calcTranslation: function()
    {
        var transl = this._planeHitPoint.subtract(this._plane.origin());
        var canTransl = this._canonicalPlaneHitPoint.subtract(this._canonicalPlane.origin());

        if(this._translationConstraint.constrainTranslation(transl))
        {
            this.translation.set(transl);
            this.canonicalTranslation = canTransl;
        }
    }
});
<|endoftext|>


<commit_before>const BinaryPjax = require('./binary_pjax');
const pages_config = require('./binary_pages');
const Client = require('./client');
const Header = require('./header');
const NetworkMonitor = require('./network_monitor');
const Page = require('./page');
const BinarySocket = require('./socket');
const ContentVisibility = require('../common/content_visibility');
const GTM = require('../../_common/base/gtm');
const Login = require('../../_common/base/login');
const LiveChat = require('../../_common/base/livechat');
const getElementById = require('../../_common/common_functions').getElementById;
const urlLang = require('../../_common/language').urlLang;
const localizeForLang = require('../../_common/localize').forLang;
const localize = require('../../_common/localize').localize;
const ScrollToAnchor = require('../../_common/scroll_to_anchor');
const isStorageSupported = require('../../_common/storage').isStorageSupported;
const ThirdPartyLinks = require('../../_common/third_party_links');
const urlFor = require('../../_common/url').urlFor;
const createElement = require('../../_common/utility').createElement;

const BinaryLoader = (() => {
    let container;
    let active_script = null;

    const init = () => {
        if (!/\.html$/i.test(window.location.pathname)) {
            window.location.pathname += '.html';
            return;
        }

        if (!isStorageSupported(localStorage) || !isStorageSupported(sessionStorage)) {
            Header.displayNotification(localize('[_1] requires your browser\'s web storage to be enabled in order to function properly. Please enable it or exit private browsing mode.', 'Binary.com'),
                true, 'STORAGE_NOT_SUPPORTED');
            getElementById('btn_login').classList.add('button-disabled');
        }

        localizeForLang(urlLang());

        checkAppidAndQAserver();

        Page.showNotificationOutdatedBrowser();

        Client.init();
        NetworkMonitor.init();
        container = getElementById('content-holder');
        container.addEventListener('binarypjax:before', beforeContentChange);
        window.addEventListener('beforeunload', beforeContentChange);
        container.addEventListener('binarypjax:after', afterContentChange);
        BinaryPjax.init(container, '#content');
        ThirdPartyLinks.init();

    };

    const checkAppidAndQAserver = () => {
        const urlParams = new URLSearchParams(window.location.search);
        const qa_server = urlParams.get('qa_server');
        const app_id = urlParams.get('app_id');
        if (qa_server && app_id) {
            localStorage.setItem('config.server_url', qa_server);
            localStorage.setItem('config.app_id', app_id);
        }
    };

    const beforeContentChange = () => {
        if (active_script) {
            BinarySocket.removeOnDisconnect();
            BinarySocket.removeOnReconnect();
            if (typeof active_script.onUnload === 'function') {
                active_script.onUnload();
            }
            active_script = null;
        }

        ScrollToAnchor.cleanup();
    };

    const afterContentChange = (e) => {
        Page.onLoad();

        const this_page = e.detail.getAttribute('data-page');
        if (Object.prototype.hasOwnProperty.call(pages_config, this_page)) {
            loadHandler(this_page);
        } else if (/\/get-started\//i.test(window.location.pathname)) {
            loadHandler('get-started');
        }

        // Make sure content is properly loaded or visible before scrolling to anchor.
        ContentVisibility.init().then(() => {
            BinarySocket.wait('authorize', 'website_status', 'landing_company').then(() => {
                GTM.pushDataLayer({ event: 'page_load' }); // we need website_status.clients_country

                // reroute LiveChat group
                LiveChat.rerouteGroup();

                // first time load.
                const last_image = $('#content img').last();
                if (last_image) {
                    last_image.on('load', () => {
                        ScrollToAnchor.init();
                    });
                }

                ScrollToAnchor.init();

                ContentVisibility.centerAlignSelect(true);
            });
        });

        if (active_script) {
            BinarySocket.setOnReconnect(active_script.onReconnect);
        }
    };

    const error_messages = {
        login            : () => localize('Please [_1]log in[_2] or [_3]sign up[_4] to view this page.', [`<a href="${'javascript:;'}">`, '', `<a href="${urlFor('new-account')}">`, '']),
        only_virtual     : () => localize('This feature is available to demo accounts only.'),
        only_real        : () => localize('This feature is not relevant to demo-money accounts.'),
        not_authenticated: () => localize('This page is only available to logged out clients.'),
        no_mf            : () => localize('Binary options trading is not available in your financial account.'),
        options_blocked  : () => localize('Binary options trading is not available in your country.'),
        residence_blocked: () => localize('This page is not available in your country of residence.'),
        not_deactivated  : () => localize('Page not available, you did not deactivate your account.'),
    };

    const loadHandler = (this_page) => {
        const config = { ...pages_config[this_page] };
        active_script = config.module;
        if (config.is_authenticated) {
            if (!Client.isLoggedIn()) {
                displayMessage(error_messages.login());
            } else {
                BinarySocket.wait('authorize')
                    .then((response) => {
                        if (response.error) {
                            displayMessage(error_messages.login());
                        } else if (config.only_virtual && !Client.get('is_virtual')) {
                            displayMessage(error_messages.only_virtual());
                        } else if (config.only_real && Client.get('is_virtual')) {
                            displayMessage(error_messages.only_real());
                        } else {
                            loadActiveScript(config);
                        }
                    });
            }
        } else if (config.not_authenticated && Client.isLoggedIn()) {
            if (this_page === 'home' || this_page === 'new-account') {
                BinaryPjax.load(`${Client.defaultRedirectUrl()}${window.location.search}`, true);
            } else {
                handleNotAuthenticated();
            }
        } else {
            loadActiveScript(config);
        }
        if (config.no_mf && Client.isLoggedIn() && Client.isAccountOfType('financial')) {
            BinarySocket.wait('authorize').then(() => {
                if (config.msg_residence_blocked) {
                    displayMessage(error_messages.residence_blocked());
                } else {
                    displayMessage(error_messages.no_mf());
                }
            });
        }
        if (this_page === 'deactivated-account' && Client.isLoggedIn()) {
            displayMessage(error_messages.not_deactivated());
        }

        BinarySocket.wait('authorize').then(() => {
            if (config.no_blocked_country && Client.isLoggedIn() && Client.isOptionsBlocked()) {
                if (config.msg_residence_blocked) {
                    displayMessage(error_messages.residence_blocked());
                } else {
                    displayMessage(error_messages.options_blocked());
                }
            }
        });

        BinarySocket.setOnDisconnect(active_script.onDisconnect);
    };

    const loadActiveScript = (config) => {
        if (active_script && typeof active_script.onLoad === 'function') {
            // only pages that call formatMoney should wait for website_status
            if (config.needs_currency) {
                BinarySocket.wait('website_status').then(() => {
                    active_script.onLoad();
                });
            } else {
                active_script.onLoad();
            }
        }
    };

    const displayMessage = (localized_message) => {
        const content = container.querySelector('#content');

        if (!content) {
            return;
        }
        content.classList.add('container');

        const div_container = createElement('div', { class: 'logged_out_title_container', html: Client.isAccountOfType('financial') || Client.isOptionsBlocked() ? '' : content.getElementsByTagName('h1')[0] || '' });
        const div_notice = createElement('p', { class: 'center-text notice-msg', html: localized_message });

        div_container.appendChild(div_notice);

        content.html(div_container);

        const link = content.getElementsByTagName('a')[0];
        if (link) {
            link.addEventListener('click', () => { Login.redirectToLogin(); });
        }
    };

    const handleNotAuthenticated = () => {
        const content = container.querySelector('#content');
        if (!content) {
            return;
        }
        content.classList.add('container');

        const outer_container = createElement('div', { class: 'logged_out_title_container' });
        outer_container.appendChild(container.querySelector('#page_info'));
        outer_container.appendChild(container.getElementsByTagName('h1')[0]);

        const rowDiv = (element) => {
            const row_element = createElement('div', { class: 'gr-padding-10' });
            row_element.appendChild(element);
            return row_element;
        };
        const inner_container = createElement('div', { class: 'center-text' });
        const error_msg = createElement('div', { class: 'center-text notice-msg', text: error_messages.not_authenticated() });
        const logout_cta = createElement('button');
        const logout_span = createElement('span', { text: localize('Sign out') });

        logout_cta.addEventListener('click', () => { Client.doLogout({ logout: 1 }); });
        logout_cta.appendChild(logout_span);
        inner_container.appendChild(rowDiv(error_msg));
        inner_container.appendChild(rowDiv(logout_cta));
        outer_container.append(inner_container);
        content.html(outer_container);
    };

    return {
        init,
    };
})();

module.exports = BinaryLoader;
<commit_msg>changed demo-money to demo (#6631)<commit_after>const BinaryPjax = require('./binary_pjax');
const pages_config = require('./binary_pages');
const Client = require('./client');
const Header = require('./header');
const NetworkMonitor = require('./network_monitor');
const Page = require('./page');
const BinarySocket = require('./socket');
const ContentVisibility = require('../common/content_visibility');
const GTM = require('../../_common/base/gtm');
const Login = require('../../_common/base/login');
const LiveChat = require('../../_common/base/livechat');
const getElementById = require('../../_common/common_functions').getElementById;
const urlLang = require('../../_common/language').urlLang;
const localizeForLang = require('../../_common/localize').forLang;
const localize = require('../../_common/localize').localize;
const ScrollToAnchor = require('../../_common/scroll_to_anchor');
const isStorageSupported = require('../../_common/storage').isStorageSupported;
const ThirdPartyLinks = require('../../_common/third_party_links');
const urlFor = require('../../_common/url').urlFor;
const createElement = require('../../_common/utility').createElement;

const BinaryLoader = (() => {
    let container;
    let active_script = null;

    const init = () => {
        if (!/\.html$/i.test(window.location.pathname)) {
            window.location.pathname += '.html';
            return;
        }

        if (!isStorageSupported(localStorage) || !isStorageSupported(sessionStorage)) {
            Header.displayNotification(localize('[_1] requires your browser\'s web storage to be enabled in order to function properly. Please enable it or exit private browsing mode.', 'Binary.com'),
                true, 'STORAGE_NOT_SUPPORTED');
            getElementById('btn_login').classList.add('button-disabled');
        }

        localizeForLang(urlLang());

        checkAppidAndQAserver();

        Page.showNotificationOutdatedBrowser();

        Client.init();
        NetworkMonitor.init();
        container = getElementById('content-holder');
        container.addEventListener('binarypjax:before', beforeContentChange);
        window.addEventListener('beforeunload', beforeContentChange);
        container.addEventListener('binarypjax:after', afterContentChange);
        BinaryPjax.init(container, '#content');
        ThirdPartyLinks.init();

    };

    const checkAppidAndQAserver = () => {
        const urlParams = new URLSearchParams(window.location.search);
        const qa_server = urlParams.get('qa_server');
        const app_id = urlParams.get('app_id');
        if (qa_server && app_id) {
            localStorage.setItem('config.server_url', qa_server);
            localStorage.setItem('config.app_id', app_id);
        }
    };

    const beforeContentChange = () => {
        if (active_script) {
            BinarySocket.removeOnDisconnect();
            BinarySocket.removeOnReconnect();
            if (typeof active_script.onUnload === 'function') {
                active_script.onUnload();
            }
            active_script = null;
        }

        ScrollToAnchor.cleanup();
    };

    const afterContentChange = (e) => {
        Page.onLoad();

        const this_page = e.detail.getAttribute('data-page');
        if (Object.prototype.hasOwnProperty.call(pages_config, this_page)) {
            loadHandler(this_page);
        } else if (/\/get-started\//i.test(window.location.pathname)) {
            loadHandler('get-started');
        }

        // Make sure content is properly loaded or visible before scrolling to anchor.
        ContentVisibility.init().then(() => {
            BinarySocket.wait('authorize', 'website_status', 'landing_company').then(() => {
                GTM.pushDataLayer({ event: 'page_load' }); // we need website_status.clients_country

                // reroute LiveChat group
                LiveChat.rerouteGroup();

                // first time load.
                const last_image = $('#content img').last();
                if (last_image) {
                    last_image.on('load', () => {
                        ScrollToAnchor.init();
                    });
                }

                ScrollToAnchor.init();

                ContentVisibility.centerAlignSelect(true);
            });
        });

        if (active_script) {
            BinarySocket.setOnReconnect(active_script.onReconnect);
        }
    };

    const error_messages = {
        login            : () => localize('Please [_1]log in[_2] or [_3]sign up[_4] to view this page.', [`<a href="${'javascript:;'}">`, '', `<a href="${urlFor('new-account')}">`, '']),
        only_virtual     : () => localize('This feature is available to demo accounts only.'),
        only_real        : () => localize('This feature is not relevant to demo accounts.'),
        not_authenticated: () => localize('This page is only available to logged out clients.'),
        no_mf            : () => localize('Binary options trading is not available in your financial account.'),
        options_blocked  : () => localize('Binary options trading is not available in your country.'),
        residence_blocked: () => localize('This page is not available in your country of residence.'),
        not_deactivated  : () => localize('Page not available, you did not deactivate your account.'),
    };

    const loadHandler = (this_page) => {
        const config = { ...pages_config[this_page] };
        active_script = config.module;
        if (config.is_authenticated) {
            if (!Client.isLoggedIn()) {
                displayMessage(error_messages.login());
            } else {
                BinarySocket.wait('authorize')
                    .then((response) => {
                        if (response.error) {
                            displayMessage(error_messages.login());
                        } else if (config.only_virtual && !Client.get('is_virtual')) {
                            displayMessage(error_messages.only_virtual());
                        } else if (config.only_real && Client.get('is_virtual')) {
                            displayMessage(error_messages.only_real());
                        } else {
                            loadActiveScript(config);
                        }
                    });
            }
        } else if (config.not_authenticated && Client.isLoggedIn()) {
            if (this_page === 'home' || this_page === 'new-account') {
                BinaryPjax.load(`${Client.defaultRedirectUrl()}${window.location.search}`, true);
            } else {
                handleNotAuthenticated();
            }
        } else {
            loadActiveScript(config);
        }
        if (config.no_mf && Client.isLoggedIn() && Client.isAccountOfType('financial')) {
            BinarySocket.wait('authorize').then(() => {
                if (config.msg_residence_blocked) {
                    displayMessage(error_messages.residence_blocked());
                } else {
                    displayMessage(error_messages.no_mf());
                }
            });
        }
        if (this_page === 'deactivated-account' && Client.isLoggedIn()) {
            displayMessage(error_messages.not_deactivated());
        }

        BinarySocket.wait('authorize').then(() => {
            if (config.no_blocked_country && Client.isLoggedIn() && Client.isOptionsBlocked()) {
                if (config.msg_residence_blocked) {
                    displayMessage(error_messages.residence_blocked());
                } else {
                    displayMessage(error_messages.options_blocked());
                }
            }
        });

        BinarySocket.setOnDisconnect(active_script.onDisconnect);
    };

    const loadActiveScript = (config) => {
        if (active_script && typeof active_script.onLoad === 'function') {
            // only pages that call formatMoney should wait for website_status
            if (config.needs_currency) {
                BinarySocket.wait('website_status').then(() => {
                    active_script.onLoad();
                });
            } else {
                active_script.onLoad();
            }
        }
    };

    const displayMessage = (localized_message) => {
        const content = container.querySelector('#content');

        if (!content) {
            return;
        }
        content.classList.add('container');

        const div_container = createElement('div', { class: 'logged_out_title_container', html: Client.isAccountOfType('financial') || Client.isOptionsBlocked() ? '' : content.getElementsByTagName('h1')[0] || '' });
        const div_notice = createElement('p', { class: 'center-text notice-msg', html: localized_message });

        div_container.appendChild(div_notice);

        content.html(div_container);

        const link = content.getElementsByTagName('a')[0];
        if (link) {
            link.addEventListener('click', () => { Login.redirectToLogin(); });
        }
    };

    const handleNotAuthenticated = () => {
        const content = container.querySelector('#content');
        if (!content) {
            return;
        }
        content.classList.add('container');

        const outer_container = createElement('div', { class: 'logged_out_title_container' });
        outer_container.appendChild(container.querySelector('#page_info'));
        outer_container.appendChild(container.getElementsByTagName('h1')[0]);

        const rowDiv = (element) => {
            const row_element = createElement('div', { class: 'gr-padding-10' });
            row_element.appendChild(element);
            return row_element;
        };
        const inner_container = createElement('div', { class: 'center-text' });
        const error_msg = createElement('div', { class: 'center-text notice-msg', text: error_messages.not_authenticated() });
        const logout_cta = createElement('button');
        const logout_span = createElement('span', { text: localize('Sign out') });

        logout_cta.addEventListener('click', () => { Client.doLogout({ logout: 1 }); });
        logout_cta.appendChild(logout_span);
        inner_container.appendChild(rowDiv(error_msg));
        inner_container.appendChild(rowDiv(logout_cta));
        outer_container.append(inner_container);
        content.html(outer_container);
    };

    return {
        init,
    };
})();

module.exports = BinaryLoader;
<|endoftext|>


<commit_before>import React from 'react';
import Carousel from 'react-bootstrap/Carousel'
import { faGithub } from '@fortawesome/free-brands-svg-icons';
import { faArrowCircleRight } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import slide1 from '../img/board-1.png'
import slide2 from '../img/board-2.png'
import slide3 from '../img/board-3.png'
import slide4 from '../img/board-4.png'

class MuHome extends React.Component {
  render() {
    const renderCarousel = () => {
      return (
        <Carousel>
          <Carousel.Item interval={2000}>

          </Carousel.Item>
          <Carousel.Item interval={2000}>

          </Carousel.Item>
          <Carousel.Item interval={2000}>

          </Carousel.Item>
          <Carousel.Item interval={2000}>

          </Carousel.Item>
        </Carousel>
      );
    }
    return (

Be the Sprint Champion

Track and manage sprint user stories in story boards.

          {renderCarousel()}

            View Source
            <FontAwesomeIcon icon={faGithub} style={{ marginLeft: '0.4em' }} />

            Story Board
            <FontAwesomeIcon icon={faArrowCircleRight} style={{ marginLeft: '0.4em' }} />

    );
  }
}

export default MuHome;<commit_msg>Fix className attribute<commit_after>import React from 'react';
import Carousel from 'react-bootstrap/Carousel'
import { faGithub } from '@fortawesome/free-brands-svg-icons';
import { faArrowCircleRight } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import slide1 from '../img/board-1.png'
import slide2 from '../img/board-2.png'
import slide3 from '../img/board-3.png'
import slide4 from '../img/board-4.png'

class MuHome extends React.Component {
  render() {
    const renderCarousel = () => {
      return (
        <Carousel>
          <Carousel.Item interval={2000}>

          </Carousel.Item>
          <Carousel.Item interval={2000}>

          </Carousel.Item>
          <Carousel.Item interval={2000}>

          </Carousel.Item>
          <Carousel.Item interval={2000}>

          </Carousel.Item>
        </Carousel>
      );
    }
    return (

Be the Sprint Champion

Track and manage sprint user stories in story boards.

          {renderCarousel()}

            View Source
            <FontAwesomeIcon icon={faGithub} style={{ marginLeft: '0.4em' }} />

            Story Board
            <FontAwesomeIcon icon={faArrowCircleRight} style={{ marginLeft: '0.4em' }} />

    );
  }
}

export default MuHome;<|endoftext|>