<commit_before>;(function() {
    function Tablesort(el, options) {
        if (!el) throw new Error('Element not found');
        if (el.tagName !== 'TABLE') throw new Error('Element must be a table');
        this.init(el, options || {});
    }

    Tablesort.prototype = {

        init: function(el, options) {
            var that = this,
                firstRow;
            this.thead = false;
            this.options = options;

            if (el.rows && el.rows.length > 0) {
                if (el.tHead && el.tHead.rows.length > 0) {
                    firstRow = el.tHead.rows[el.tHead.rows.length - 1];
                    that.thead = true;
                } else {
                    firstRow = el.rows[0];
                }
            }

            if (!firstRow) return;

            var onClick = function() {
                if (that.current && that.current !== this) {
                    if (that.current.classList.contains(classSortUp)) {
                        that.current.classList.remove(classSortUp);
                    }
                    else if (that.current.classList.contains(classSortDown)) {
                        that.current.classList.remove(classSortDown);
                    }
                }

                that.current = this;
                that.sortTable(this);
            };

            var defaultSort;

            // Assume first row is the header and attach a click handler to each.
            for (var i = 0; i < firstRow.cells.length; i++) {
                var cell = firstRow.cells[i];
                if (!cell.classList.contains('no-sort')) {
                    cell.classList.add('sort-header');
                    cell.addEventListener('click', onClick, false);

                    if (cell.classList.contains('sort-default')) {
                        defaultSort = cell;
                    }
                }
            }

            if (defaultSort) {
                that.current = defaultSort;
                that.sortTable(defaultSort, true);
            }
        },

        getFirstDataRowIndex: function() {
            // If table does not have a <thead>, assume that first row is
            // a header and skip it.
            if (!this.thead) {
                return 1;
            } else {
                return 0;
            }
        },

        sortTable: function(header, update) {
            var that = this,
                column = header.cellIndex,
                sortFunction,
                t = getParent(header, 'table'),
                item = '',
                items = [],
                i = that.getFirstDataRowIndex();

            if (t.rows.length <= 1) return;

            while (items.length < 3 && i < t.tBodies[0].rows.length) {
                item = getInnerText(t.tBodies[0].rows[i].cells[column]);
                item = item.trim();
                // Exclude cell values where commented out HTML exists
                if (item.substr(0, 4) !== '<!--' && item.length !== 0) {
                    items.push(item);
                }
                i++;
            }

            if (!items) return;

            // Possible sortFunction scenarios
            var sortCaseInsensitive = function(a, b) {
                var aa = getInnerText(a.cells[that.col]).toLowerCase(),
                    bb = getInnerText(b.cells[that.col]).toLowerCase();

                if (aa === bb) return 0;
                if (aa < bb) return 1;

                return -1;
            };

            var sortNumber = function(a, b) {
                var aa = getInnerText(a.cells[that.col]),
                    bb = getInnerText(b.cells[that.col]);

                aa = cleanNumber(aa);
                bb = cleanNumber(bb);
                return compareNumber(bb, aa);
            };

            var sortDate = function(a, b) {
                var aa = getInnerText(a.cells[that.col]).toLowerCase(),
                    bb = getInnerText(b.cells[that.col]).toLowerCase();
                return parseDate(bb) - parseDate(aa);
            };

            var sortDotSep = function(a, b) {
                var aa = getInnerText(a.cells[that.col]).split('.'),
                    bb = getInnerText(b.cells[that.col]).split('.');

                for (var i = 0, len = aa.length; i < len; i++) {
                    var aai = parseInt(aa[i]),
                        bbi = parseInt(bb[i]);

                    if (aai == bbi) continue;
                    if (aai > bbi) return -1;
                    if (aai < bbi) return 1;
                }
                return 0;
            };

            var sortFilesize = function(a, b) {
                var aa = filesize2num(getInnerText(a.cells[that.col]))
                    bb = filesize2num(getInnerText(b.cells[that.col]));

                return compareNumber(bb, aa);
            };

            // Sort dot separated numbers, e.g. ip addresses or version numbers
            if (items.every(testDotSeparatedNumbers)) {
                sortFunction = sortDotSep;
            }
            // sort filesize, e.g. "123.45 MB"
            else if (items.every(testFilesize)) {
                sortFunction = sortFilesize;
            }
            // Sort as number if a currency key exists or number
            else if (items.every(testNumber)) {
                sortFunction = sortNumber;
            } else if (items.every(testDate)) {
                sortFunction = sortDate;
            } else {
                sortFunction = sortCaseInsensitive;
            }

            this.col = column;
            var newRows = [],
                noSorts = {},
                j,
                totalRows = 0;

            for (i = 0; i < t.tBodies.length; i++) {
                for (j = 0; j < t.tBodies[i].rows.length; j++) {
                    var tr = t.tBodies[i].rows[j];
                    if (tr.classList.contains('no-sort')) {
                        // keep no-sorts in separate list to be able to insert
                        // them back at their original position later
                        noSorts[totalRows] = tr;
                    } else {
                        // Save the index for stable sorting
                        newRows.push({
                            tr: tr,
                            index: totalRows
                        });
                    }
                    totalRows++;
                }
            }

            var sortUp   = that.options.descending ? classSortDown : classSortUp,
                sortDown = that.options.descending ? classSortUp : classSortDown;

            if (!update) {
                if (header.classList.contains(sortUp)) {
                    header.classList.remove(sortUp);
                    header.classList.add(sortDown);
                } else {
                    header.classList.remove(sortDown);
                    header.classList.add(sortUp);
                }
            } else if (!header.classList.contains(sortUp) && !header.classList.contains(sortDown)) {
                header.classList.add(sortUp);
            }

            // Make a stable sort function
            var stabilize = function(sort) {
                return function(a, b) {
                    var unstableResult = sort(a.tr, b.tr);
                    if (unstableResult === 0) {
                        return a.index - b.index;
                    }
                    return unstableResult;
                };
            };

            // Make an `anti-stable` sort function. If two elements are equal
            // under the original sort function, then there relative order is
            // reversed.
            var antiStabilize = function(sort) {
                return function(a, b) {
                    var unstableResult = sort(a.tr, b.tr);
                    if (unstableResult === 0) {
                        return b.index - a.index;
                    }
                    return unstableResult;
                };
            };

            // Before we append should we reverse the new array or not?
            // If we reverse, the sort needs to be `anti-stable` so that
            // the double negatives cancel out
            if (header.classList.contains(classSortDown)) {
                newRows.sort(antiStabilize(sortFunction));
                newRows.reverse();
            } else {
                newRows.sort(stabilize(sortFunction));
            }

            // append rows that already exist rather than creating new ones
            var noSortsSoFar = 0;
            for (i = 0; i < totalRows; i++) {
                var whatToInsert;
                if (noSorts[i]) {
                    // We have a no-sort row for this position, insert it here.
                    whatToInsert = noSorts[i];
                    noSortsSoFar++;
                } else {
                    whatToInsert = newRows[i - noSortsSoFar].tr;
                }
                // appendChild(x) moves x if already present somewhere else in the DOM
                t.tBodies[0].appendChild(whatToInsert);
            }
            // callback
            if (that.options.callback && typeof that.options.callback === 'function') {
                that.options.callback(header);
            }
        },

        refresh: function() {
            if (this.current !== undefined) {
                this.sortTable(this.current, true);
            }
        }
    };

    var classSortUp   = 'sort-up',
        classSortDown = 'sort-down';

    var week       = /(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\.?\,?\s*/i,
        commonDate = /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/,
        month      = /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i;

    var testDotSeparatedNumbers = function(item){
        return /^(\d+\.)+\d+$/.test(item);
    };

    var testFilesize = function(item){
        return /^\d+(\.\d+)? ?(k|M|G|T|P|E|Z|Y)?i?B?$/i.test(item);
    };

    var testNumber = function(item){
        return item.match(/^-?[£\x24Û¢´€]?\d+\s*([,\.]\d{0,2})/) || // prefixed currency
               item.match(/^-?\d+\s*([,\.]\d{0,2})?[£\x24Û¢´€]/) || // suffixed currency
               item.match(/^-?(\d)*-?([,\.]){0,1}-?(\d)+([E,e][\-+][\d]+)?%?$/); // number
    };

    var testDate = function(date) {
            return (
                date.search(week) !== -1 ||
                date.search(commonDate) !== -1  ||
                date.search(month !== -1)
            ) !== -1 && !isNaN(parseDate(date));
        },

        parseDate = function(date) {
            date = date.replace(/\-/g, '/');
            date = date.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, '$1/$2/$3'); // format before getTime
            return new Date(date).getTime();
        },

        getParent = function(el, pTagName) {
            if (el === null) {
                return null;
            } else if (el.nodeType === 1 && el.tagName.toLowerCase() === pTagName.toLowerCase()) {
                return el;
            } else {
                return getParent(el.parentNode, pTagName);
            }
        },

        getInnerText = function(el) {
            var that = this;

            if (typeof el === 'string' || typeof el === 'undefined') return el;

            var str = el.getAttribute('data-sort') || '';

            if (str) {
                return str;
            } else if (el.textContent) {
                return el.textContent;
            } else if (el.innerText) {
                return el.innerText;
            }

            var cs = el.childNodes,
                l = cs.length;

            for (var i = 0; i < l; i++) {
                switch (cs[i].nodeType) {
                    case 1:
                        // ELEMENT_NODE
                        if (cs[i].tagName === 'IMG' || cs[i].tagName === 'SPAN') {
                            str += (cs[i].alt || cs[i].title || "");
                        } else {
                            str += that.getInnerText(cs[i]);
                        }
                    break;
                    case 3:
                        // TEXT_NODE
                        str += cs[i].nodeValue;
                    break;
                }
            }

            return str;
        },

        compareNumber = function(a, b) {
            var aa = parseFloat(a),
                bb = parseFloat(b);

            a = isNaN(aa) ? 0 : aa;
            b = isNaN(bb) ? 0 : bb;
            return a - b;
        },

        cleanNumber = function(i) {
            return i.replace(/[^\-?0-9.]/g, '');
        };

        // Converts filesize to bytes
        // Ex. filesize2num("123 KB") -> 123000
        // Ex. filesize2num("123 KiB") -> 125952
        filesize2num = function(filesize) {
            var matches = filesize.match(/^(\d+(\.\d+)?) ?((k|M|G|T|P|E|Z|Y)?i?B?)$/i);

            var num    = parseFloat(cleanNumber(matches[1])),
                suffix = matches[3];

            return num * suffix2num(suffix);
        };

        // Returns suffix multiplier
        // Ex. suffix2num("KB") -> 1000
        // Ex. suffix2num("KiB") -> 1024
        suffix2num = function(suffix) {
            suffix = suffix.toLowerCase();
            var base = suffix[1] === "i" ? 1024 : 1000;

            switch(suffix[0]) {
                case "k":
                    return Math.pow(base, 2);
                case "m":
                    return Math.pow(base, 3);
                case "g":
                    return Math.pow(base, 4);
                case "t":
                    return Math.pow(base, 5);
                case "p":
                    return Math.pow(base, 6);
                case "e":
                    return Math.pow(base, 7);
                case "z":
                    return Math.pow(base, 8);
                case "y":
                    return Math.pow(base, 9);
                default:
                    return base;
            }
        };

    if (typeof module !== 'undefined' && module.exports) {
        module.exports = Tablesort;
    } else {
        window.Tablesort = Tablesort;
    }
})();
<commit_msg>Simpler getInnerText without recursion<commit_after>;(function() {
    function Tablesort(el, options) {
        if (!el) throw new Error('Element not found');
        if (el.tagName !== 'TABLE') throw new Error('Element must be a table');
        this.init(el, options || {});
    }

    Tablesort.prototype = {

        init: function(el, options) {
            var that = this,
                firstRow;
            this.thead = false;
            this.options = options;

            if (el.rows && el.rows.length > 0) {
                if (el.tHead && el.tHead.rows.length > 0) {
                    firstRow = el.tHead.rows[el.tHead.rows.length - 1];
                    that.thead = true;
                } else {
                    firstRow = el.rows[0];
                }
            }

            if (!firstRow) return;

            var onClick = function() {
                if (that.current && that.current !== this) {
                    if (that.current.classList.contains(classSortUp)) {
                        that.current.classList.remove(classSortUp);
                    }
                    else if (that.current.classList.contains(classSortDown)) {
                        that.current.classList.remove(classSortDown);
                    }
                }

                that.current = this;
                that.sortTable(this);
            };

            var defaultSort;

            // Assume first row is the header and attach a click handler to each.
            for (var i = 0; i < firstRow.cells.length; i++) {
                var cell = firstRow.cells[i];
                if (!cell.classList.contains('no-sort')) {
                    cell.classList.add('sort-header');
                    cell.addEventListener('click', onClick, false);

                    if (cell.classList.contains('sort-default')) {
                        defaultSort = cell;
                    }
                }
            }

            if (defaultSort) {
                that.current = defaultSort;
                that.sortTable(defaultSort, true);
            }
        },

        getFirstDataRowIndex: function() {
            // If table does not have a <thead>, assume that first row is
            // a header and skip it.
            if (!this.thead) {
                return 1;
            } else {
                return 0;
            }
        },

        sortTable: function(header, update) {
            var that = this,
                column = header.cellIndex,
                sortFunction,
                t = getParent(header, 'table'),
                item = '',
                items = [],
                i = that.getFirstDataRowIndex();

            if (t.rows.length <= 1) return;

            while (items.length < 3 && i < t.tBodies[0].rows.length) {
                item = getInnerText(t.tBodies[0].rows[i].cells[column]);
                item = item.trim();
                // Exclude cell values where commented out HTML exists
                if (item.substr(0, 4) !== '<!--' && item.length !== 0) {
                    items.push(item);
                }
                i++;
            }

            if (!items) return;

            // Possible sortFunction scenarios
            var sortCaseInsensitive = function(a, b) {
                var aa = getInnerText(a.cells[that.col]).toLowerCase(),
                    bb = getInnerText(b.cells[that.col]).toLowerCase();

                if (aa === bb) return 0;
                if (aa < bb) return 1;

                return -1;
            };

            var sortNumber = function(a, b) {
                var aa = getInnerText(a.cells[that.col]),
                    bb = getInnerText(b.cells[that.col]);

                aa = cleanNumber(aa);
                bb = cleanNumber(bb);
                return compareNumber(bb, aa);
            };

            var sortDate = function(a, b) {
                var aa = getInnerText(a.cells[that.col]).toLowerCase(),
                    bb = getInnerText(b.cells[that.col]).toLowerCase();
                return parseDate(bb) - parseDate(aa);
            };

            var sortDotSep = function(a, b) {
                var aa = getInnerText(a.cells[that.col]).split('.'),
                    bb = getInnerText(b.cells[that.col]).split('.');

                for (var i = 0, len = aa.length; i < len; i++) {
                    var aai = parseInt(aa[i]),
                        bbi = parseInt(bb[i]);

                    if (aai == bbi) continue;
                    if (aai > bbi) return -1;
                    if (aai < bbi) return 1;
                }
                return 0;
            };

            var sortFilesize = function(a, b) {
                var aa = filesize2num(getInnerText(a.cells[that.col]))
                    bb = filesize2num(getInnerText(b.cells[that.col]));

                return compareNumber(bb, aa);
            };

            // Sort dot separated numbers, e.g. ip addresses or version numbers
            if (items.every(testDotSeparatedNumbers)) {
                sortFunction = sortDotSep;
            }
            // sort filesize, e.g. "123.45 MB"
            else if (items.every(testFilesize)) {
                sortFunction = sortFilesize;
            }
            // Sort as number if a currency key exists or number
            else if (items.every(testNumber)) {
                sortFunction = sortNumber;
            } else if (items.every(testDate)) {
                sortFunction = sortDate;
            } else {
                sortFunction = sortCaseInsensitive;
            }

            this.col = column;
            var newRows = [],
                noSorts = {},
                j,
                totalRows = 0;

            for (i = 0; i < t.tBodies.length; i++) {
                for (j = 0; j < t.tBodies[i].rows.length; j++) {
                    var tr = t.tBodies[i].rows[j];
                    if (tr.classList.contains('no-sort')) {
                        // keep no-sorts in separate list to be able to insert
                        // them back at their original position later
                        noSorts[totalRows] = tr;
                    } else {
                        // Save the index for stable sorting
                        newRows.push({
                            tr: tr,
                            index: totalRows
                        });
                    }
                    totalRows++;
                }
            }

            var sortUp   = that.options.descending ? classSortDown : classSortUp,
                sortDown = that.options.descending ? classSortUp : classSortDown;

            if (!update) {
                if (header.classList.contains(sortUp)) {
                    header.classList.remove(sortUp);
                    header.classList.add(sortDown);
                } else {
                    header.classList.remove(sortDown);
                    header.classList.add(sortUp);
                }
            } else if (!header.classList.contains(sortUp) && !header.classList.contains(sortDown)) {
                header.classList.add(sortUp);
            }

            // Make a stable sort function
            var stabilize = function(sort) {
                return function(a, b) {
                    var unstableResult = sort(a.tr, b.tr);
                    if (unstableResult === 0) {
                        return a.index - b.index;
                    }
                    return unstableResult;
                };
            };

            // Make an `anti-stable` sort function. If two elements are equal
            // under the original sort function, then there relative order is
            // reversed.
            var antiStabilize = function(sort) {
                return function(a, b) {
                    var unstableResult = sort(a.tr, b.tr);
                    if (unstableResult === 0) {
                        return b.index - a.index;
                    }
                    return unstableResult;
                };
            };

            // Before we append should we reverse the new array or not?
            // If we reverse, the sort needs to be `anti-stable` so that
            // the double negatives cancel out
            if (header.classList.contains(classSortDown)) {
                newRows.sort(antiStabilize(sortFunction));
                newRows.reverse();
            } else {
                newRows.sort(stabilize(sortFunction));
            }

            // append rows that already exist rather than creating new ones
            var noSortsSoFar = 0;
            for (i = 0; i < totalRows; i++) {
                var whatToInsert;
                if (noSorts[i]) {
                    // We have a no-sort row for this position, insert it here.
                    whatToInsert = noSorts[i];
                    noSortsSoFar++;
                } else {
                    whatToInsert = newRows[i - noSortsSoFar].tr;
                }
                // appendChild(x) moves x if already present somewhere else in the DOM
                t.tBodies[0].appendChild(whatToInsert);
            }
            // callback
            if (that.options.callback && typeof that.options.callback === 'function') {
                that.options.callback(header);
            }
        },

        refresh: function() {
            if (this.current !== undefined) {
                this.sortTable(this.current, true);
            }
        }
    };

    var classSortUp   = 'sort-up',
        classSortDown = 'sort-down';

    var week       = /(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\.?\,?\s*/i,
        commonDate = /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/,
        month      = /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i;

    var testDotSeparatedNumbers = function(item){
        return /^(\d+\.)+\d+$/.test(item);
    };

    var testFilesize = function(item){
        return /^\d+(\.\d+)? ?(k|M|G|T|P|E|Z|Y)?i?B?$/i.test(item);
    };

    var testNumber = function(item){
        return item.match(/^-?[£\x24Û¢´€]?\d+\s*([,\.]\d{0,2})/) || // prefixed currency
               item.match(/^-?\d+\s*([,\.]\d{0,2})?[£\x24Û¢´€]/) || // suffixed currency
               item.match(/^-?(\d)*-?([,\.]){0,1}-?(\d)+([E,e][\-+][\d]+)?%?$/); // number
    };

    var testDate = function(date) {
            return (
                date.search(week) !== -1 ||
                date.search(commonDate) !== -1  ||
                date.search(month !== -1)
            ) !== -1 && !isNaN(parseDate(date));
        },

        parseDate = function(date) {
            date = date.replace(/\-/g, '/');
            date = date.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, '$1/$2/$3'); // format before getTime
            return new Date(date).getTime();
        },

        getParent = function(el, pTagName) {
            if (el === null) {
                return null;
            } else if (el.nodeType === 1 && el.tagName.toLowerCase() === pTagName.toLowerCase()) {
                return el;
            } else {
                return getParent(el.parentNode, pTagName);
            }
        },

        getInnerText = function(el) {
            if (typeof el === 'string' || typeof el === 'undefined') return el;

            return el.getAttribute('data-sort') || el.textContent || el.innerText || '';
        },

        compareNumber = function(a, b) {
            var aa = parseFloat(a),
                bb = parseFloat(b);

            a = isNaN(aa) ? 0 : aa;
            b = isNaN(bb) ? 0 : bb;
            return a - b;
        },

        cleanNumber = function(i) {
            return i.replace(/[^\-?0-9.]/g, '');
        };

        // Converts filesize to bytes
        // Ex. filesize2num("123 KB") -> 123000
        // Ex. filesize2num("123 KiB") -> 125952
        filesize2num = function(filesize) {
            var matches = filesize.match(/^(\d+(\.\d+)?) ?((k|M|G|T|P|E|Z|Y)?i?B?)$/i);

            var num    = parseFloat(cleanNumber(matches[1])),
                suffix = matches[3];

            return num * suffix2num(suffix);
        };

        // Returns suffix multiplier
        // Ex. suffix2num("KB") -> 1000
        // Ex. suffix2num("KiB") -> 1024
        suffix2num = function(suffix) {
            suffix = suffix.toLowerCase();
            var base = suffix[1] === "i" ? 1024 : 1000;

            switch(suffix[0]) {
                case "k":
                    return Math.pow(base, 2);
                case "m":
                    return Math.pow(base, 3);
                case "g":
                    return Math.pow(base, 4);
                case "t":
                    return Math.pow(base, 5);
                case "p":
                    return Math.pow(base, 6);
                case "e":
                    return Math.pow(base, 7);
                case "z":
                    return Math.pow(base, 8);
                case "y":
                    return Math.pow(base, 9);
                default:
                    return base;
            }
        };

    if (typeof module !== 'undefined' && module.exports) {
        module.exports = Tablesort;
    } else {
        window.Tablesort = Tablesort;
    }
})();
<|endoftext|>


<commit_before>import React from 'react';

import SocialNetworks from '../social/SocialNetworks';

export default props => (

<SocialNetworks locale={props.locale}/>

      © 2017 - Marc Ed. Raffalli - Credits

);
<commit_msg>Added link for project info / credits<commit_after>import React from 'react';

import SocialNetworks from '../social/SocialNetworks';

export default props => (

<SocialNetworks locale={props.locale}/>

      © 2017 - Marc Ed. Raffalli - Info - Credits

);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import './Contact.css';

class Contact extends Component {

  renderField(field) {
    const { meta: { touched, error } } = field
    const className = '';
    // console.log('className ', className);
    return (

        <input className="form-control"
          type={field.type}
          placeholder={field.placeholder}
          {...field.input} />

          {touched ? error : ''}

    );
  }

  onSubmit(values) {
    alert('Sua mensagem foi enviada!')
    // this.props.history.push('/'); // -> uncomment this line to redirect user to "/"(home)
    values.nome = '';
    values.email='';
    values.telefone = '';
    values.message = '';
  }

  render() {
    const { handleSubmit } = this.props;
    return (

Entre em contato conosco

          <form className="form-group" onSubmit={handleSubmit(this.onSubmit.bind(this))}>
            <Field
              name="nome"
              type="text"
              component={
                  ({input}) => (
                      <input {...input} className="form-control" placeholder="Nome"/>
                  )}
            />
            <Field
              name="email"
              type="text"
              component={
                  ({input}) => (
                      <input {...input} className="form-control" placeholder="E-mail"/>

                  )}
            />
            <Field
              name="telefone"
              type="text"
              component={
                  ({input}) => (
                      <input {...input} className="form-control" placeholder="Telefone" />
                  )}
            />
            <Field
              name="message"
              type="input"
              component={
                ({ input }) => (
                  <textarea {...input} className="form-control message" rows="7" id="mensagem" placeholder="Mensagem" />)}
            />

            <button className="btn btn-success">Enviar</button>
          </form>

    );
  }
}

export default reduxForm({
  form: 'Contact'
})(
  connect(null, {})(Contact)
  );<commit_msg>Added contact form fields verification<commit_after>import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import './Contact.css';

class Contact extends Component {

  renderField(field) {
    const { meta: { touched, error } } = field
    const className = '';
    // console.log('className ', className);
    return (

        <input className="form-control"
          type={field.type}
          placeholder={field.placeholder}
          {...field.input} />

          {touched ? error : ''}

    );
  }

  verifyFields(values){
    if(values.nome === undefined){
      alert('Por favor, insira um nome')
    } else if(values.email === undefined){
      alert('Por favor, insira um e-mail')
    } else if(values.email.indexOf('@') === -1){
      alert('Por favor, insira um e-mail válido')
    } else if(values.telefone === undefined){
      alert('Por favor, insira um telefone')
    } else if(values.message === undefined){
      alert('Por favor, insira uma mensagem')
    } else {
      return true;
    }
    return false;
  }

  onSubmit(values) {
    if(this.verifyFields(values)){
      alert('Sua mensagem foi enviada!')
      // this.props.history.push('/'); // -> uncomment this line to redirect user to "/"(home)
      values.nome = '';
      values.email='';
      values.telefone = '';
      values.message = '';
    }
  }

  render() {
    const { handleSubmit } = this.props;
    return (

Entre em contato conosco

          <form className="form-group" onSubmit={handleSubmit(this.onSubmit.bind(this))}>
            <Field
              name="nome"
              type="text"
              component={
                  ({input}) => (
                      <input {...input} className="form-control" placeholder="Nome"/>
                  )}
            />
            <Field
              name="email"
              type="text"
              component={
                  ({input}) => (
                      <input {...input} className="form-control" placeholder="E-mail"/>

                  )}
            />
            <Field
              name="telefone"
              type="text"
              component={
                  ({input}) => (
                      <input {...input} className="form-control" placeholder="Telefone" />
                  )}
            />
            <Field
              name="message"
              type="input"
              component={
                ({ input }) => (
                  <textarea {...input} className="form-control message" rows="7" id="mensagem" placeholder="Mensagem" />)}
            />

            <button className="btn btn-success">Enviar</button>
          </form>

    );
  }
}

export default reduxForm({
  form: 'Contact'
})(
  connect(null, {})(Contact)
  );<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var DropTarget = require('react-dnd').DropTarget;
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');
var UnreadStatus = require('matrix-react-sdk/lib/UnreadStatus');

// turn this on for drop & drag console debugging galore
var debug = false;

var roomListTarget = {
    canDrop: function() {
        return true;
    },

    drop: function(props, monitor, component) {
        if (debug) console.log("dropped on sublist")
    },

    hover: function(props, monitor, component) {
        var item = monitor.getItem();

        if (component.state.sortedList.length == 0 && props.editable) {
            if (debug) console.log("hovering on sublist " + props.label + ", isOver=" + monitor.isOver());

            if (item.targetList !== component) {
                 item.targetList.removeRoomTile(item.room);
                 item.targetList = component;
            }

            component.moveRoomTile(item.room, 0);
        }
    },
};

var RoomSubList = React.createClass({
    displayName: 'RoomSubList',

    debug: debug,

    propTypes: {
        list: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
        label: React.PropTypes.string.isRequired,
        tagName: React.PropTypes.string,
        editable: React.PropTypes.bool,
        order: React.PropTypes.string.isRequired,
        selectedRoom: React.PropTypes.string.isRequired,
        activityMap: React.PropTypes.object.isRequired,
        startAsHidden: React.PropTypes.bool,
        showSpinner: React.PropTypes.bool, // true to show a spinner if 0 elements when expanded

        // TODO: Fix the name of this. This is too easily confused with the
        // "hidden" state which is the expanded (or not) view of the list of rooms.
        // What this prop *really* does is control whether the room name is displayed
        // so it should be named as such.
        collapsed: React.PropTypes.bool.isRequired,
        onHeaderClick: React.PropTypes.func,
        alwaysShowHeader: React.PropTypes.bool,
        incomingCall: React.PropTypes.object
    },

    getInitialState: function() {
        return {
            hidden: this.props.startAsHidden || false,
            sortedList: [],
        };
    },

    getDefaultProps: function() {
        return {
            onHeaderClick: function() {} // NOP
        };
    },

    componentWillMount: function() {
        this.sortList(this.props.list, this.props.order);
    },

    componentWillReceiveProps: function(newProps) {
        // order the room list appropriately before we re-render
        //if (debug) console.log("received new props, list = " + newProps.list);
        this.sortList(newProps.list, newProps.order);
    },

    onClick: function(ev) {
        var isHidden = !this.state.hidden;
        this.setState({ hidden : isHidden });
        this.props.onHeaderClick(isHidden);
    },

    tsOfNewestEvent: function(room) {
        for (var i = room.timeline.length - 1; i >= 0; --i) {
            var ev = room.timeline[i];
            // logic copied from RoomList.js for when we do/don't highlight
            if (UnreadStatus.eventTriggersUnreadCount(ev)) {
                return ev.getTs();
            }
        }

        // we might only have events that don't trigger the unread indicator,
        // in which case use the oldest event even if normally it wouldn't count.
        // This is better than just assuming the last event was forever ago.
        if (room.timeline.length) {
            return room.timeline[0].getTs();
        } else {
            return Number.MAX_SAFE_INTEGER;
        }
    },

    // TODO: factor the comparators back out into a generic comparator
    // so that view_prev_room and view_next_room can do the right thing

    recentsComparator: function(roomA, roomB) {
        return this.tsOfNewestEvent(roomB) - this.tsOfNewestEvent(roomA);
    },

    manualComparator: function(roomA, roomB) {
        if (!roomA.tags[this.props.tagName] || !roomB.tags[this.props.tagName]) return 0;
        var a = roomA.tags[this.props.tagName].order;
        var b = roomB.tags[this.props.tagName].order;
        return a == b ? this.recentsComparator(roomA, roomB) : ( a > b  ? 1 : -1);
    },

    sortList: function(list, order) {
        if (list === undefined) list = this.state.sortedList;
        if (order === undefined) order = this.props.order;
        var comparator;
        list = list || [];
        if (order === "manual") comparator = this.manualComparator;
        if (order === "recent") comparator = this.recentsComparator;

        //if (debug) console.log("sorting list for sublist " + this.props.label + " with length " + list.length + ", this.props.list = " + this.props.list);
        this.setState({ sortedList: list.sort(comparator) });
    },

    moveRoomTile: function(room, atIndex) {
        if (debug) console.log("moveRoomTile: id " + room.roomId + ", atIndex " + atIndex);
        //console.log("moveRoomTile before: " + JSON.stringify(this.state.rooms));
        var found = this.findRoomTile(room);
        var rooms = this.state.sortedList;
        if (found.room) {
            if (debug) console.log("removing at index " + found.index + " and adding at index " + atIndex);
            rooms.splice(found.index, 1);
            rooms.splice(atIndex, 0, found.room);
        }
        else {
            if (debug) console.log("Adding at index " + atIndex);
            rooms.splice(atIndex, 0, room);
        }
        this.setState({ sortedList: rooms });
        // console.log("moveRoomTile after: " + JSON.stringify(this.state.rooms));
    },

    // XXX: this isn't invoked via a property method but indirectly via
    // the roomList property method.  Unsure how evil this is.
    removeRoomTile: function(room) {
        if (debug) console.log("remove room " + room.roomId);
        var found = this.findRoomTile(room);
        var rooms = this.state.sortedList;
        if (found.room) {
            rooms.splice(found.index, 1);
        }
        else {
            console.warn("Can't remove room " + room.roomId + " - can't find it");
        }
        this.setState({ sortedList: rooms });
    },

    findRoomTile: function(room) {
        var index = this.state.sortedList.indexOf(room);
        if (index >= 0) {
            // console.log("found: room: " + room.roomId + " with index " + index);
        }
        else {
            if (debug) console.log("didn't find room");
            room = null;
        }
        return ({
            room: room,
            index: index,
        });
    },

    calcManualOrderTagData: function(room) {
        var index = this.state.sortedList.indexOf(room);

        // we sort rooms by the lexicographic ordering of the 'order' metadata on their tags.
        // for convenience, we calculate this for now a floating point number between 0.0 and 1.0.

        var orderA = 0.0; // by default we're next to the beginning of the list
        if (index > 0) {
            var prevTag = this.state.sortedList[index - 1].tags[this.props.tagName];
            if (!prevTag) {
                console.error("Previous room in sublist is not tagged to be in this list. This should never happen.")
            }
            else if (prevTag.order === undefined) {
                console.error("Previous room in sublist has no ordering metadata. This should never happen.");
            }
            else {
                orderA = prevTag.order;
            }
        }

        var orderB = 1.0; // by default we're next to the end of the list too
        if (index < this.state.sortedList.length - 1) {
            var nextTag = this.state.sortedList[index + 1].tags[this.props.tagName];
            if (!nextTag) {
                console.error("Next room in sublist is not tagged to be in this list. This should never happen.")
            }
            else if (nextTag.order === undefined) {
                console.error("Next room in sublist has no ordering metadata. This should never happen.");
            }
            else {
                orderB = nextTag.order;
            }
        }

        var order = (orderA + orderB) / 2.0;
        if (order === orderA || order === orderB) {
            console.error("Cannot describe new list position.  This should be incredibly unlikely.");
            // TODO: renumber the list
        }

        return order;
    },

    makeRoomTiles: function() {
        var self = this;
        var RoomTile = sdk.getComponent("rooms.RoomTile");
        return this.state.sortedList.map(function(room) {
            var selected = room.roomId == self.props.selectedRoom;
            // XXX: is it evil to pass in self as a prop to RoomTile?
            return (
                <RoomTile
                    room={ room }
                    roomSubList={ self }
                    key={ room.roomId }
                    collapsed={ self.props.collapsed || false}
                    selected={ selected }
                    unread={ self.props.activityMap[room.roomId] === 1 }
                    highlight={ room.unread_notification_count > 0 || self.props.label === 'Invites' }
                    isInvite={ self.props.label === 'Invites' }
                    incomingCall={ self.props.incomingCall && (self.props.incomingCall.roomId === room.roomId) ? self.props.incomingCall : null }
                     />
            );
        });
    },

    _getHeaderJsx: function() {
        return (

                { this.props.collapsed ? '' : this.props.label }

        );
    },

    render: function() {
        var connectDropTarget = this.props.connectDropTarget;
        var RoomDropTarget = sdk.getComponent('rooms.RoomDropTarget');

        var label = this.props.collapsed ? null : this.props.label;

        //console.log("render: " + JSON.stringify(this.state.sortedList));

        var target;
        if (this.state.sortedList.length == 0 && this.props.editable) {
            target = <RoomDropTarget label={ 'Drop here to ' + this.props.verb }/>;
        }

        if (this.state.sortedList.length > 0 || this.props.editable) {
            var subList;
            var classes = "mx_RoomSubList";

            if (!this.state.hidden) {
                subList =

                                { target }
                                { this.makeRoomTiles() }

;
            }
            else {
                subList =

;
            }

            return connectDropTarget(

                    { this._getHeaderJsx() }
                    { subList }

            );
        }
        else {
            var Loader = sdk.getComponent("elements.Spinner");
            return (

                    { this.props.alwaysShowHeader ? this._getHeaderJsx() : undefined }
                    { (this.props.showSpinner && !this.state.hidden) ? <Loader /> : undefined }

            );
        }
    }
});

// Export the wrapped version, inlining the 'collect' functions
// to more closely resemble the ES7
module.exports =
DropTarget('RoomTile', roomListTarget, function(connect) {
    return {
        connectDropTarget: connect.dropTarget(),
    }
})(RoomSubList);
<commit_msg>Update for new unread count format<commit_after>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var DropTarget = require('react-dnd').DropTarget;
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');
var UnreadStatus = require('matrix-react-sdk/lib/UnreadStatus');

// turn this on for drop & drag console debugging galore
var debug = false;

var roomListTarget = {
    canDrop: function() {
        return true;
    },

    drop: function(props, monitor, component) {
        if (debug) console.log("dropped on sublist")
    },

    hover: function(props, monitor, component) {
        var item = monitor.getItem();

        if (component.state.sortedList.length == 0 && props.editable) {
            if (debug) console.log("hovering on sublist " + props.label + ", isOver=" + monitor.isOver());

            if (item.targetList !== component) {
                 item.targetList.removeRoomTile(item.room);
                 item.targetList = component;
            }

            component.moveRoomTile(item.room, 0);
        }
    },
};

var RoomSubList = React.createClass({
    displayName: 'RoomSubList',

    debug: debug,

    propTypes: {
        list: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
        label: React.PropTypes.string.isRequired,
        tagName: React.PropTypes.string,
        editable: React.PropTypes.bool,
        order: React.PropTypes.string.isRequired,
        selectedRoom: React.PropTypes.string.isRequired,
        activityMap: React.PropTypes.object.isRequired,
        startAsHidden: React.PropTypes.bool,
        showSpinner: React.PropTypes.bool, // true to show a spinner if 0 elements when expanded

        // TODO: Fix the name of this. This is too easily confused with the
        // "hidden" state which is the expanded (or not) view of the list of rooms.
        // What this prop *really* does is control whether the room name is displayed
        // so it should be named as such.
        collapsed: React.PropTypes.bool.isRequired,
        onHeaderClick: React.PropTypes.func,
        alwaysShowHeader: React.PropTypes.bool,
        incomingCall: React.PropTypes.object
    },

    getInitialState: function() {
        return {
            hidden: this.props.startAsHidden || false,
            sortedList: [],
        };
    },

    getDefaultProps: function() {
        return {
            onHeaderClick: function() {} // NOP
        };
    },

    componentWillMount: function() {
        this.sortList(this.props.list, this.props.order);
    },

    componentWillReceiveProps: function(newProps) {
        // order the room list appropriately before we re-render
        //if (debug) console.log("received new props, list = " + newProps.list);
        this.sortList(newProps.list, newProps.order);
    },

    onClick: function(ev) {
        var isHidden = !this.state.hidden;
        this.setState({ hidden : isHidden });
        this.props.onHeaderClick(isHidden);
    },

    tsOfNewestEvent: function(room) {
        for (var i = room.timeline.length - 1; i >= 0; --i) {
            var ev = room.timeline[i];
            // logic copied from RoomList.js for when we do/don't highlight
            if (UnreadStatus.eventTriggersUnreadCount(ev)) {
                return ev.getTs();
            }
        }

        // we might only have events that don't trigger the unread indicator,
        // in which case use the oldest event even if normally it wouldn't count.
        // This is better than just assuming the last event was forever ago.
        if (room.timeline.length) {
            return room.timeline[0].getTs();
        } else {
            return Number.MAX_SAFE_INTEGER;
        }
    },

    // TODO: factor the comparators back out into a generic comparator
    // so that view_prev_room and view_next_room can do the right thing

    recentsComparator: function(roomA, roomB) {
        return this.tsOfNewestEvent(roomB) - this.tsOfNewestEvent(roomA);
    },

    manualComparator: function(roomA, roomB) {
        if (!roomA.tags[this.props.tagName] || !roomB.tags[this.props.tagName]) return 0;
        var a = roomA.tags[this.props.tagName].order;
        var b = roomB.tags[this.props.tagName].order;
        return a == b ? this.recentsComparator(roomA, roomB) : ( a > b  ? 1 : -1);
    },

    sortList: function(list, order) {
        if (list === undefined) list = this.state.sortedList;
        if (order === undefined) order = this.props.order;
        var comparator;
        list = list || [];
        if (order === "manual") comparator = this.manualComparator;
        if (order === "recent") comparator = this.recentsComparator;

        //if (debug) console.log("sorting list for sublist " + this.props.label + " with length " + list.length + ", this.props.list = " + this.props.list);
        this.setState({ sortedList: list.sort(comparator) });
    },

    moveRoomTile: function(room, atIndex) {
        if (debug) console.log("moveRoomTile: id " + room.roomId + ", atIndex " + atIndex);
        //console.log("moveRoomTile before: " + JSON.stringify(this.state.rooms));
        var found = this.findRoomTile(room);
        var rooms = this.state.sortedList;
        if (found.room) {
            if (debug) console.log("removing at index " + found.index + " and adding at index " + atIndex);
            rooms.splice(found.index, 1);
            rooms.splice(atIndex, 0, found.room);
        }
        else {
            if (debug) console.log("Adding at index " + atIndex);
            rooms.splice(atIndex, 0, room);
        }
        this.setState({ sortedList: rooms });
        // console.log("moveRoomTile after: " + JSON.stringify(this.state.rooms));
    },

    // XXX: this isn't invoked via a property method but indirectly via
    // the roomList property method.  Unsure how evil this is.
    removeRoomTile: function(room) {
        if (debug) console.log("remove room " + room.roomId);
        var found = this.findRoomTile(room);
        var rooms = this.state.sortedList;
        if (found.room) {
            rooms.splice(found.index, 1);
        }
        else {
            console.warn("Can't remove room " + room.roomId + " - can't find it");
        }
        this.setState({ sortedList: rooms });
    },

    findRoomTile: function(room) {
        var index = this.state.sortedList.indexOf(room);
        if (index >= 0) {
            // console.log("found: room: " + room.roomId + " with index " + index);
        }
        else {
            if (debug) console.log("didn't find room");
            room = null;
        }
        return ({
            room: room,
            index: index,
        });
    },

    calcManualOrderTagData: function(room) {
        var index = this.state.sortedList.indexOf(room);

        // we sort rooms by the lexicographic ordering of the 'order' metadata on their tags.
        // for convenience, we calculate this for now a floating point number between 0.0 and 1.0.

        var orderA = 0.0; // by default we're next to the beginning of the list
        if (index > 0) {
            var prevTag = this.state.sortedList[index - 1].tags[this.props.tagName];
            if (!prevTag) {
                console.error("Previous room in sublist is not tagged to be in this list. This should never happen.")
            }
            else if (prevTag.order === undefined) {
                console.error("Previous room in sublist has no ordering metadata. This should never happen.");
            }
            else {
                orderA = prevTag.order;
            }
        }

        var orderB = 1.0; // by default we're next to the end of the list too
        if (index < this.state.sortedList.length - 1) {
            var nextTag = this.state.sortedList[index + 1].tags[this.props.tagName];
            if (!nextTag) {
                console.error("Next room in sublist is not tagged to be in this list. This should never happen.")
            }
            else if (nextTag.order === undefined) {
                console.error("Next room in sublist has no ordering metadata. This should never happen.");
            }
            else {
                orderB = nextTag.order;
            }
        }

        var order = (orderA + orderB) / 2.0;
        if (order === orderA || order === orderB) {
            console.error("Cannot describe new list position.  This should be incredibly unlikely.");
            // TODO: renumber the list
        }

        return order;
    },

    makeRoomTiles: function() {
        var self = this;
        var RoomTile = sdk.getComponent("rooms.RoomTile");
        return this.state.sortedList.map(function(room) {
            var selected = room.roomId == self.props.selectedRoom;
            // XXX: is it evil to pass in self as a prop to RoomTile?
            return (
                <RoomTile
                    room={ room }
                    roomSubList={ self }
                    key={ room.roomId }
                    collapsed={ self.props.collapsed || false}
                    selected={ selected }
                    unread={ self.props.activityMap[room.roomId] === 1 }
                    highlight={ (room.unread_notifications && room.unread_notifications['notification_count'] > 0) || self.props.label === 'Invites' }
                    isInvite={ self.props.label === 'Invites' }
                    incomingCall={ self.props.incomingCall && (self.props.incomingCall.roomId === room.roomId) ? self.props.incomingCall : null }
                     />
            );
        });
    },

    _getHeaderJsx: function() {
        return (

                { this.props.collapsed ? '' : this.props.label }

        );
    },

    render: function() {
        var connectDropTarget = this.props.connectDropTarget;
        var RoomDropTarget = sdk.getComponent('rooms.RoomDropTarget');

        var label = this.props.collapsed ? null : this.props.label;

        //console.log("render: " + JSON.stringify(this.state.sortedList));

        var target;
        if (this.state.sortedList.length == 0 && this.props.editable) {
            target = <RoomDropTarget label={ 'Drop here to ' + this.props.verb }/>;
        }

        if (this.state.sortedList.length > 0 || this.props.editable) {
            var subList;
            var classes = "mx_RoomSubList";

            if (!this.state.hidden) {
                subList =

                                { target }
                                { this.makeRoomTiles() }

;
            }
            else {
                subList =

;
            }

            return connectDropTarget(

                    { this._getHeaderJsx() }
                    { subList }

            );
        }
        else {
            var Loader = sdk.getComponent("elements.Spinner");
            return (

                    { this.props.alwaysShowHeader ? this._getHeaderJsx() : undefined }
                    { (this.props.showSpinner && !this.state.hidden) ? <Loader /> : undefined }

            );
        }
    }
});

// Export the wrapped version, inlining the 'collect' functions
// to more closely resemble the ES7
module.exports =
DropTarget('RoomTile', roomListTarget, function(connect) {
    return {
        connectDropTarget: connect.dropTarget(),
    }
})(RoomSubList);
<|endoftext|>


<commit_before>var v3index = {};

(function(){

/* variables */
v3index = {
	typelist : [],
	current  : '',
	language : 'ja',
	extend : function(obj){ for(var n in obj){ this[n] = obj[n];}}
};

var _doc = document;
var self = v3index;
var typelist = self.typelist;

v3index.extend({
	/* common function */
	addEvent : function(element,type,func){
		if(!!element.addEventListener){ element.addEventListener(type,func,false);}
		else if(!!element.attachEvent){ element.attachEvent("on"+type,func);}
		else                          { element["on"+type] = func;}
	},

	/* onload function */
	onload_func : function(){
		if(!self.current){
			var el = _doc.getElementById("puztypes").firstChild;
			while(!!el){
				if(!!el.tagName && el.tagName.toLowerCase()==='li' &&
				   !!el.id      && el.id.match(/puzmenu_(.+)$/)){
					var typename = RegExp.$1;
					typelist.push(typename);
					self.addEvent(el,"click",self.click_tab);
					if(el.className=="puzmenusel"){ self.current = typename;}
				}
				el = el.nextSibling;
			}
			if(!self.current && typelist.length>0){ self.current = typelist[0];}

			var userlang = (navigator.browserLanguage || navigator.language || navigator.userLanguage);
			if(userlang.substr(0,2)!=='ja'){ self.language = 'en';}

			el = _doc.getElementById("urlinput_btn");
			if(!!el){ self.addEvent(el,"click",self.urlinput);}

			self.dbif.init();
		}
		self.disp();
	},

	reset_func : function(){
		typelist = [];
		self.current  = '';
		self.onload_func();
	},

	/* input-URL function */
	urlinput : function(e){
		var url = _doc.getElementById("urlinput_text").value;
		if(!!url){
			localStorage['pzprv3_urldata'] = url;
			window.open('./p.html', '');
		}
	},

	/* tab-click function */
	click_tab : function(e){
		var el = (e.target || e.srcElement);
		if(!!el){ self.current = el.id.substr(8); self.disp();}
	},

	/* display tabs and tables function */
	disp : function(){
		for(var i=0;i<typelist.length;i++){
			var el = _doc.getElementById("puzmenu_"+typelist[i]);
			var table = _doc.getElementById("table_"+typelist[i]);
			if(typelist[i]===self.current){
				el.className = "puzmenusel";
				try     { table.style.display = 'table';}
				catch(e){ table.style.display = 'block';} //IE raises error
			}
			else{
				el.className = "puzmenu";
				table.style.display = 'none';
			}
		}
	}
});

/* addEventListener */
self.addEvent(window, 'load', self.onload_func);

})();

/*********************/
/* Database function */
/*********************/
(function(){

v3index.dbif = {
	list   : [],
	LS     : false,
	extend : function(obj){ for(var n in obj){ this[n] = obj[n];}}
};

var _doc = document;
var _form;
var self = v3index.dbif;
var DBlist = self.list;
var isGecko = (navigator.userAgent.indexOf('Gecko')>-1 && navigator.userAgent.indexOf('KHTML') == -1);
var pheader = '';

v3index.dbif.extend({
	init : function(){
		// HTML5 - Web localStorage判定用(localStorage)
		try{ if(!!window.localStorage && (!isGecko || !!location.hostname)){ self.LS = true;}}
		catch(e){}

		if(self.LS){
			_form = _doc.database;

			v3index.addEvent(_form.sorts,    "change", self.display);
			v3index.addEvent(_form.datalist, "change", self.select);
			v3index.addEvent(_form.open,     "click",  self.open);

			pheader = 'pzprv3_storage:data:';
			self.importlist(self.display);
		}
	},
	importlist : function(callback){
		DBlist = [];
		for(var i=1;true;i++){
			var row = JSON.parse(localStorage[pheader+i]);
			if(!row || row.id==null){ break;}
			DBlist.push(row);
		}
		if(!!callback){ callback();}
	},
	display : function(){
		switch(_form.sorts.value){
			case 'idlist' : DBlist = DBlist.sort(function(a,b){ return (a.id-b.id);}); break;
			case 'newsave': DBlist = DBlist.sort(function(a,b){ return (b.time-a.time || a.id-b.id);}); break;
			case 'oldsave': DBlist = DBlist.sort(function(a,b){ return (a.time-b.time || a.id-b.id);}); break;
			case 'size'   : DBlist = DBlist.sort(function(a,b){ return (a.col-b.col || a.row-b.row || a.hard-b.hard || a.id-b.id);}); break;
		}

		_form.datalist.innerHTML = "";
		for(var i=0;i<DBlist.length;i++){
			var row = DBlist[i];
			if(!!row){
				var opt = _doc.createElement('option');
				opt.setAttribute('value', row.id);
				opt.innerHTML = self.getcaption(row);
				_form.datalist.appendChild(opt);
			}
		}
	},
	getcaption : function(row){
		var hardstr = [
			{ja:'−'       , en:'-'     },
			{ja:'らくらく', en:'Easy'  },
			{ja:'おてごろ', en:'Normal'},
			{ja:'たいへん', en:'Hard'  },
			{ja:'アゼン'  , en:'Expert'}
		];

		var datestr = (function(){
			var ni = function(num){ return (num<10?"0":"")+num;}, str = "", date = new Date();
			date.setTime(row.time*1000);
			str += (ni(date.getFullYear()%100) + "/" + ni(date.getMonth()+1) + "/" + ni(date.getDate())+" ");
			str += (ni(date.getHours()) + ":" + ni(date.getMinutes()));
			return str;
		})();

		var str = "";
		str += ((row.id<10?" ":"")+row.id+" : ");
		str += (PZLNAME[v3index.language][row.pid]+" ");
		str += (""+row.col+"×"+row.row+"  ");
		if(!!row.hard || row.hard=='0'){
			str += (hardstr[row.hard][v3index.language]+" ");
		}
		str += ("("+datestr+")");
		return str;
	},

	select : function(){
		var selected = self.getvalue();
		_form.comtext.value = (selected>=0 ? ""+DBlist[selected].comment : "");
	},
	open : function(){
		var selected = self.getvalue();
		if(selected>=0){
			var str = DBlist[selected].pdata;
			if(!!str){
				localStorage['pzprv3_filedata'] = str;
				window.open('./p.html', '');
			}
		}
	},
	getvalue : function(){
		var val = _form.datalist.value;
		if(val!=""){
			for(var i=0;i<DBlist.length;i++){
				if(DBlist[i].id==val){ return i;}
			}
		}
		return -1;
	}
});

})();
<commit_msg>v3index.js ・localStorageが使用できないときに一時保存を表示しないようにした(refs #14)<commit_after>var v3index = {};

(function(){

/* variables */
v3index = {
	typelist : [],
	current  : '',
	language : 'ja',
	extend : function(obj){ for(var n in obj){ this[n] = obj[n];}}
};

var _doc = document;
var self = v3index;
var typelist = self.typelist;

v3index.extend({
	/* common function */
	addEvent : function(element,type,func){
		if(!!element.addEventListener){ element.addEventListener(type,func,false);}
		else if(!!element.attachEvent){ element.attachEvent("on"+type,func);}
		else                          { element["on"+type] = func;}
	},

	/* onload function */
	onload_func : function(){
		if(!self.current){
			var el = _doc.getElementById("puztypes").firstChild;
			while(!!el){
				if(!!el.tagName && el.tagName.toLowerCase()==='li' &&
				   !!el.id      && el.id.match(/puzmenu_(.+)$/)){
					var typename = RegExp.$1;
					typelist.push(typename);
					self.addEvent(el,"click",self.click_tab);
					if(el.className=="puzmenusel"){ self.current = typename;}
				}
				el = el.nextSibling;
			}
			if(!self.current && typelist.length>0){ self.current = typelist[0];}

			var userlang = (navigator.browserLanguage || navigator.language || navigator.userLanguage);
			if(userlang.substr(0,2)!=='ja'){ self.language = 'en';}

			el = _doc.getElementById("urlinput_btn");
			if(!!el){ self.addEvent(el,"click",self.urlinput);}

			self.dbif.init();
		}
		self.disp();
	},

	reset_func : function(){
		typelist = [];
		self.current  = '';
		self.onload_func();
	},

	/* input-URL function */
	urlinput : function(e){
		var url = _doc.getElementById("urlinput_text").value;
		if(!!url){
			localStorage['pzprv3_urldata'] = url;
			window.open('./p.html', '');
		}
	},

	/* tab-click function */
	click_tab : function(e){
		var el = (e.target || e.srcElement);
		if(!!el){ self.current = el.id.substr(8); self.disp();}
	},

	/* display tabs and tables function */
	disp : function(){
		for(var i=0;i<typelist.length;i++){
			var el = _doc.getElementById("puzmenu_"+typelist[i]);
			var table = _doc.getElementById("table_"+typelist[i]);
			if(typelist[i]===self.current){
				el.className = "puzmenusel";
				try     { table.style.display = 'table';}
				catch(e){ table.style.display = 'block';} //IE raises error
			}
			else{
				el.className = "puzmenu";
				table.style.display = 'none';
			}
		}
	}
});

/* addEventListener */
self.addEvent(window, 'load', self.onload_func);

})();

/*********************/
/* Database function */
/*********************/
(function(){

v3index.dbif = {
	list   : [],
	LS     : false,
	extend : function(obj){ for(var n in obj){ this[n] = obj[n];}}
};

var _doc = document;
var _form;
var self = v3index.dbif;
var DBlist = self.list;
var isGecko = (navigator.userAgent.indexOf('Gecko')>-1 && navigator.userAgent.indexOf('KHTML') == -1);
var pheader = '';

v3index.dbif.extend({
	init : function(){
		// HTML5 - Web localStorage判定用(localStorage)
		try{ if(!!window.localStorage && (!isGecko || !!location.hostname)){ self.LS = true;}}
		catch(e){}

		_form = _doc.database;

		if(self.LS){
			v3index.addEvent(_form.sorts,    "change", self.display);
			v3index.addEvent(_form.datalist, "change", self.select);
			v3index.addEvent(_form.open,     "click",  self.open);

			pheader = 'pzprv3_storage:data:';
			self.importlist(self.display);
		}
		else{
			_form.style.display = 'none';
		}
	},
	importlist : function(callback){
		DBlist = [];
		for(var i=1;true;i++){
			var row = JSON.parse(localStorage[pheader+i]);
			if(!row || row.id==null){ break;}
			DBlist.push(row);
		}
		if(!!callback){ callback();}
	},
	display : function(){
		switch(_form.sorts.value){
			case 'idlist' : DBlist = DBlist.sort(function(a,b){ return (a.id-b.id);}); break;
			case 'newsave': DBlist = DBlist.sort(function(a,b){ return (b.time-a.time || a.id-b.id);}); break;
			case 'oldsave': DBlist = DBlist.sort(function(a,b){ return (a.time-b.time || a.id-b.id);}); break;
			case 'size'   : DBlist = DBlist.sort(function(a,b){ return (a.col-b.col || a.row-b.row || a.hard-b.hard || a.id-b.id);}); break;
		}

		_form.datalist.innerHTML = "";
		for(var i=0;i<DBlist.length;i++){
			var row = DBlist[i];
			if(!!row){
				var opt = _doc.createElement('option');
				opt.setAttribute('value', row.id);
				opt.innerHTML = self.getcaption(row);
				_form.datalist.appendChild(opt);
			}
		}
	},
	getcaption : function(row){
		var hardstr = [
			{ja:'−'       , en:'-'     },
			{ja:'らくらく', en:'Easy'  },
			{ja:'おてごろ', en:'Normal'},
			{ja:'たいへん', en:'Hard'  },
			{ja:'アゼン'  , en:'Expert'}
		];

		var datestr = (function(){
			var ni = function(num){ return (num<10?"0":"")+num;}, str = "", date = new Date();
			date.setTime(row.time*1000);
			str += (ni(date.getFullYear()%100) + "/" + ni(date.getMonth()+1) + "/" + ni(date.getDate())+" ");
			str += (ni(date.getHours()) + ":" + ni(date.getMinutes()));
			return str;
		})();

		var str = "";
		str += ((row.id<10?" ":"")+row.id+" : ");
		str += (PZLNAME[v3index.language][row.pid]+" ");
		str += (""+row.col+"×"+row.row+"  ");
		if(!!row.hard || row.hard=='0'){
			str += (hardstr[row.hard][v3index.language]+" ");
		}
		str += ("("+datestr+")");
		return str;
	},

	select : function(){
		var selected = self.getvalue();
		_form.comtext.value = (selected>=0 ? ""+DBlist[selected].comment : "");
	},
	open : function(){
		var selected = self.getvalue();
		if(selected>=0){
			var str = DBlist[selected].pdata;
			if(!!str){
				localStorage['pzprv3_filedata'] = str;
				window.open('./p.html', '');
			}
		}
	},
	getvalue : function(){
		var val = _form.datalist.value;
		if(val!=""){
			for(var i=0;i<DBlist.length;i++){
				if(DBlist[i].id==val){ return i;}
			}
		}
		return -1;
	}
});

})();
<|endoftext|>


<commit_before>Templates = function(type, cache, folder ){
	cache = cache == null ? true : false;

	var templates_directory = {} //nice and private container

	this.get = function(path){
		if(cache == false) return null;
		if(templates_directory[path]) return templates_directory[path];
  		return null;
	}

	this.update = function(path, template) { templates_directory[path] = template }

	this.INVALID_PATH =  -1;
	this.folder = folder
	this.type = type || '<'
}

Templates.prototype = {
	find : function(path){
		var template = this.get(path)

		if (template) return template;
	    if (template == this.INVALID_PATH) return null;

		var response = new Ajax.Request(path, {asynchronous: false, method: "get"});

		if ( response.transport.status == 404 ||
			(response.transport.status == 0 && response.transport.responseText == '') ) { // this means the template was not found
	        this.update(path, this.INVALID_PATH);
	        return null;
	    }
	    var template = new EjsCompiler(response.transport.responseText, this.type);
		template.path = path;
	    try {
			template.compile();
		} catch(e) {
			throw 'error processing template'
		}

    	this.update(path, template);

		return template;
	}
}

<commit_msg>cross browser, prototype-less Ajax templates added<commit_after>Templates = function(type, cache, folder ){
	cache = cache == null ? true : false;

	var templates_directory = {} //nice and private container

	this.get = function(path){
		if(cache == false) return null;
		if(templates_directory[path]) return templates_directory[path];
  		return null;
	}

	this.update = function(path, template) { templates_directory[path] = template }

	this.INVALID_PATH =  -1;
	this.folder = folder
	this.type = type || '<'
}

Templates.prototype = {
	find : function(path){
		var template = this.get(path)

		if (template) return template;
	    if (template == this.INVALID_PATH) return null;

		var text = Templates.request(path)
		if(text == null){
			this.update(path, this.INVALID_PATH);
	        return null;
		}

	    var template = new EjsCompiler(text, this.type);
		template.path = path;
	    try {
			template.compile();
		} catch(e) {
			throw 'error processing template'
		}

    	this.update(path, template);

		return template;
	}
}
if(typeof Prototype != 'undefined') {
	Templates.request = function(path){
		var response = new Ajax.Request(path, {asynchronous: false, method: "get"});
		if ( response.transport.status == 404 || response.transport.status == 2 ||
			(response.transport.status == 0 && response.transport.responseText == '') ) return null;
	    return response.transport.responseText
	}
}else
{
	Templates.request = function(path){
	   var factories = [function() { return new XMLHttpRequest(); },function() { return new ActiveXObject("Msxml2.XMLHTTP"); },function() { return new ActiveXObject("Microsoft.XMLHTTP"); }];
	   var request
	   for(var i = 0; i < factories.length; i++) {
	        try {
	            request = factories[i]();
	            if (request != null)  break;
	        }
	        catch(e) { continue;}
	   }
	   request.open("GET", path, false);

	   try{request.send(null);}
	   catch(e){return null;}

	   if ( request.status == 404 || request.status == 2 ||(request.status == 0 && request.responseText == '') ) return null;

	   return request.responseText
	}
}

<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var ReactDOM = require('react-dom');
var sdk = require('../../../index');
var Signup = require("../../../Signup");
var PasswordLogin = require("../../views/login/PasswordLogin");
var CasLogin = require("../../views/login/CasLogin");
var ServerConfig = require("../../views/login/ServerConfig");

/**
 * A wire component which glues together login UI components and Signup logic
 */
module.exports = React.createClass({displayName: 'Login',
    propTypes: {
        onLoggedIn: React.PropTypes.func.isRequired,

        customHsUrl: React.PropTypes.string,
        customIsUrl: React.PropTypes.string,
        defaultHsUrl: React.PropTypes.string,
        defaultIsUrl: React.PropTypes.string,
        // Secondary HS which we try to log into if the user is using
        // the default HS but login fails. Useful for migrating to a
        // different home server without confusing users.
        fallbackHsUrl: React.PropTypes.string,

        // login shouldn't know or care how registration is done.
        onRegisterClick: React.PropTypes.func.isRequired,

        // login shouldn't care how password recovery is done.
        onForgotPasswordClick: React.PropTypes.func,
        onLoginAsGuestClick: React.PropTypes.func,
        onCancelClick: React.PropTypes.func,
    },

    getInitialState: function() {
        return {
            busy: false,
            errorText: null,
            loginIncorrect: false,
            enteredHomeserverUrl: this.props.customHsUrl || this.props.defaultHsUrl,
            enteredIdentityServerUrl: this.props.customIsUrl || this.props.defaultIsUrl,

            // used for preserving username when changing homeserver
            username: "",
        };
    },

    componentWillMount: function() {
        this._initLoginLogic();
    },

    onPasswordLogin: function(username, password) {
        var self = this;
        self.setState({
            busy: true,
            errorText: null,
            loginIncorrect: false,
        });

        this._loginLogic.loginViaPassword(username, password).then(function(data) {
            self.props.onLoggedIn(data);
        }, function(error) {
            self._setStateFromError(error);
        }).finally(function() {
            self.setState({
                busy: false
            });
        });
    },

    onUsernameChanged: function(username) {
        this.setState({ username: username });
    },

    onHsUrlChanged: function(newHsUrl) {
        var self = this;
        this.setState({
            enteredHomeserverUrl: newHsUrl
        }, function() {
            self._initLoginLogic(newHsUrl);
        });
    },

    onIsUrlChanged: function(newIsUrl) {
        var self = this;
        this.setState({
            enteredIdentityServerUrl: newIsUrl
        }, function() {
            self._initLoginLogic(null, newIsUrl);
        });
    },

    _initLoginLogic: function(hsUrl, isUrl) {
        var self = this;
        hsUrl = hsUrl || this.state.enteredHomeserverUrl;
        isUrl = isUrl || this.state.enteredIdentityServerUrl;

        var fallbackHsUrl = hsUrl == this.props.defaultHsUrl ? this.props.fallbackHsUrl : null;

        var loginLogic = new Signup.Login(hsUrl, isUrl, fallbackHsUrl);
        this._loginLogic = loginLogic;

        loginLogic.getFlows().then(function(flows) {
            // old behaviour was to always use the first flow without presenting
            // options. This works in most cases (we don't have a UI for multiple
            // logins so let's skip that for now).
            loginLogic.chooseFlow(0);
        }, function(err) {
            self._setStateFromError(err);
        }).finally(function() {
            self.setState({
                busy: false
            });
        });

        this.setState({
            enteredHomeserverUrl: hsUrl,
            enteredIdentityServerUrl: isUrl,
            busy: true,
            errorText: null, // reset err messages
            loginIncorrect: false,
        });
    },

    _getCurrentFlowStep: function() {
        return this._loginLogic ? this._loginLogic.getCurrentFlowStep() : null
    },

    _setStateFromError: function(err) {
        this.setState({
            errorText: this._errorTextFromError(err),
            // https://matrix.org/jira/browse/SYN-744
            loginIncorrect: err.httpStatus == 401 || err.httpStatus == 403
        });
    },

    _errorTextFromError(err) {
        if (err.friendlyText) {
            return err.friendlyText;
        }

        let errCode = err.errcode;
        if (!errCode && err.httpStatus) {
            errCode = "HTTP " + err.httpStatus;
        }

        let errorText = "Error: Problem communicating with the given homeserver " +
                (errCode ? "(" + errCode + ")" : "")

        if (err.cors === 'rejected') {
            if (window.location.protocol === 'https:' &&
                (this.state.enteredHomeserverUrl.startsWith("http:") ||
                 !this.state.enteredHomeserverUrl.startsWith("http")))
            {
                errorText =
                    Can't connect to homeserver via HTTP when using a vector served by HTTPS.
                    Either use HTTPS or enable unsafe scripts
                ;
            }
            else {
                errorText =
                    Can't connect to homeserver - please check your connectivity and ensure
                    your homeserver's SSL certificate is trusted.
                ;
            }
        }

        return errorText;
    },

    componentForStep: function(step) {
        switch (step) {
            case 'm.login.password':
                return (
                    <PasswordLogin
                        onSubmit={this.onPasswordLogin}
                        initialUsername={this.state.username}
                        onUsernameChanged={this.onUsernameChanged}
                        onForgotPasswordClick={this.props.onForgotPasswordClick}
                        loginIncorrect={this.state.loginIncorrect}
                    />
                );
            case 'm.login.cas':
                return (
                    <CasLogin />
                );
            default:
                if (!step) {
                    return;
                }
                return (

                    Sorry, this homeserver is using a login which is not
                    recognised ({step})

                );
        }
    },

    render: function() {
        var Loader = sdk.getComponent("elements.Spinner");
        var LoginHeader = sdk.getComponent("login.LoginHeader");
        var LoginFooter = sdk.getComponent("login.LoginFooter");
        var loader = this.state.busy ?
<Loader />
 : null;

        var loginAsGuestJsx;
        if (this.props.onLoginAsGuestClick) {
            loginAsGuestJsx =

                    Login as guest

        }

        var returnToAppJsx;
        if (this.props.onCancelClick) {
            returnToAppJsx =

                    Return to app

        }

        return (

                    <LoginHeader />

Sign in
                            { loader }

                        { this.componentForStep(this._getCurrentFlowStep()) }
                        <ServerConfig ref="serverConfig"
                            withToggleButton={true}
                            customHsUrl={this.props.customHsUrl}
                            customIsUrl={this.props.customIsUrl}
                            defaultHsUrl={this.props.defaultHsUrl}
                            defaultIsUrl={this.props.defaultIsUrl}
                            onHsUrlChanged={this.onHsUrlChanged}
                            onIsUrlChanged={this.onIsUrlChanged}
                            delayTimeMs={1000}/>

                                { this.state.errorText }

                            Create a new account

                        { loginAsGuestJsx }
                        { returnToAppJsx }
                        <LoginFooter />

        );
    }
});
<commit_msg>Make sure error message never lies<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var ReactDOM = require('react-dom');
var sdk = require('../../../index');
var Signup = require("../../../Signup");
var PasswordLogin = require("../../views/login/PasswordLogin");
var CasLogin = require("../../views/login/CasLogin");
var ServerConfig = require("../../views/login/ServerConfig");

/**
 * A wire component which glues together login UI components and Signup logic
 */
module.exports = React.createClass({displayName: 'Login',
    propTypes: {
        onLoggedIn: React.PropTypes.func.isRequired,

        customHsUrl: React.PropTypes.string,
        customIsUrl: React.PropTypes.string,
        defaultHsUrl: React.PropTypes.string,
        defaultIsUrl: React.PropTypes.string,
        // Secondary HS which we try to log into if the user is using
        // the default HS but login fails. Useful for migrating to a
        // different home server without confusing users.
        fallbackHsUrl: React.PropTypes.string,

        // login shouldn't know or care how registration is done.
        onRegisterClick: React.PropTypes.func.isRequired,

        // login shouldn't care how password recovery is done.
        onForgotPasswordClick: React.PropTypes.func,
        onLoginAsGuestClick: React.PropTypes.func,
        onCancelClick: React.PropTypes.func,
    },

    getInitialState: function() {
        return {
            busy: false,
            errorText: null,
            loginIncorrect: false,
            enteredHomeserverUrl: this.props.customHsUrl || this.props.defaultHsUrl,
            enteredIdentityServerUrl: this.props.customIsUrl || this.props.defaultIsUrl,

            // used for preserving username when changing homeserver
            username: "",
        };
    },

    componentWillMount: function() {
        this._initLoginLogic();
    },

    onPasswordLogin: function(username, password) {
        var self = this;
        self.setState({
            busy: true,
            errorText: null,
            loginIncorrect: false,
        });

        this._loginLogic.loginViaPassword(username, password).then(function(data) {
            self.props.onLoggedIn(data);
        }, function(error) {
            self._setStateFromError(error, true);
        }).finally(function() {
            self.setState({
                busy: false
            });
        });
    },

    onUsernameChanged: function(username) {
        this.setState({ username: username });
    },

    onHsUrlChanged: function(newHsUrl) {
        var self = this;
        this.setState({
            enteredHomeserverUrl: newHsUrl
        }, function() {
            self._initLoginLogic(newHsUrl);
        });
    },

    onIsUrlChanged: function(newIsUrl) {
        var self = this;
        this.setState({
            enteredIdentityServerUrl: newIsUrl
        }, function() {
            self._initLoginLogic(null, newIsUrl);
        });
    },

    _initLoginLogic: function(hsUrl, isUrl) {
        var self = this;
        hsUrl = hsUrl || this.state.enteredHomeserverUrl;
        isUrl = isUrl || this.state.enteredIdentityServerUrl;

        var fallbackHsUrl = hsUrl == this.props.defaultHsUrl ? this.props.fallbackHsUrl : null;

        var loginLogic = new Signup.Login(hsUrl, isUrl, fallbackHsUrl);
        this._loginLogic = loginLogic;

        loginLogic.getFlows().then(function(flows) {
            // old behaviour was to always use the first flow without presenting
            // options. This works in most cases (we don't have a UI for multiple
            // logins so let's skip that for now).
            loginLogic.chooseFlow(0);
        }, function(err) {
            self._setStateFromError(err, false);
        }).finally(function() {
            self.setState({
                busy: false
            });
        });

        this.setState({
            enteredHomeserverUrl: hsUrl,
            enteredIdentityServerUrl: isUrl,
            busy: true,
            errorText: null, // reset err messages
            loginIncorrect: false,
        });
    },

    _getCurrentFlowStep: function() {
        return this._loginLogic ? this._loginLogic.getCurrentFlowStep() : null
    },

    _setStateFromError: function(err, isLoginAttempt) {
        this.setState({
            errorText: this._errorTextFromError(err),
            // https://matrix.org/jira/browse/SYN-744
            loginIncorrect: isLoginAttempt && (err.httpStatus == 401 || err.httpStatus == 403)
        });
    },

    _errorTextFromError(err) {
        if (err.friendlyText) {
            return err.friendlyText;
        }

        let errCode = err.errcode;
        if (!errCode && err.httpStatus) {
            errCode = "HTTP " + err.httpStatus;
        }

        let errorText = "Error: Problem communicating with the given homeserver " +
                (errCode ? "(" + errCode + ")" : "")

        if (err.cors === 'rejected') {
            if (window.location.protocol === 'https:' &&
                (this.state.enteredHomeserverUrl.startsWith("http:") ||
                 !this.state.enteredHomeserverUrl.startsWith("http")))
            {
                errorText =
                    Can't connect to homeserver via HTTP when using a vector served by HTTPS.
                    Either use HTTPS or enable unsafe scripts
                ;
            }
            else {
                errorText =
                    Can't connect to homeserver - please check your connectivity and ensure
                    your homeserver's SSL certificate is trusted.
                ;
            }
        }

        return errorText;
    },

    componentForStep: function(step) {
        switch (step) {
            case 'm.login.password':
                return (
                    <PasswordLogin
                        onSubmit={this.onPasswordLogin}
                        initialUsername={this.state.username}
                        onUsernameChanged={this.onUsernameChanged}
                        onForgotPasswordClick={this.props.onForgotPasswordClick}
                        loginIncorrect={this.state.loginIncorrect}
                    />
                );
            case 'm.login.cas':
                return (
                    <CasLogin />
                );
            default:
                if (!step) {
                    return;
                }
                return (

                    Sorry, this homeserver is using a login which is not
                    recognised ({step})

                );
        }
    },

    render: function() {
        var Loader = sdk.getComponent("elements.Spinner");
        var LoginHeader = sdk.getComponent("login.LoginHeader");
        var LoginFooter = sdk.getComponent("login.LoginFooter");
        var loader = this.state.busy ?
<Loader />
 : null;

        var loginAsGuestJsx;
        if (this.props.onLoginAsGuestClick) {
            loginAsGuestJsx =

                    Login as guest

        }

        var returnToAppJsx;
        if (this.props.onCancelClick) {
            returnToAppJsx =

                    Return to app

        }

        return (

                    <LoginHeader />

Sign in
                            { loader }

                        { this.componentForStep(this._getCurrentFlowStep()) }
                        <ServerConfig ref="serverConfig"
                            withToggleButton={true}
                            customHsUrl={this.props.customHsUrl}
                            customIsUrl={this.props.customIsUrl}
                            defaultHsUrl={this.props.defaultHsUrl}
                            defaultIsUrl={this.props.defaultIsUrl}
                            onHsUrlChanged={this.onHsUrlChanged}
                            onIsUrlChanged={this.onIsUrlChanged}
                            delayTimeMs={1000}/>

                                { this.state.errorText }

                            Create a new account

                        { loginAsGuestJsx }
                        { returnToAppJsx }
                        <LoginFooter />

        );
    }
});
<|endoftext|>


<commit_before>process.traceDeprecation = true;
const fs = require("fs");
const path = require("path");
const webpack = require("webpack");
const webpack_helpers = require("patternslib/webpack/webpack-helpers");

// plugins
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const DuplicatePackageCheckerPlugin = require("duplicate-package-checker-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");

module.exports = async (env) => {
    const mode = env.NODE_ENV;

    const config = {
        mode: mode,
        entry: {
            "bundle": path.resolve(__dirname, "src/patterns.js"),
            "bundle-polyfills": path.resolve(__dirname, "src/polyfills.js"),
        },
        externals: [
            {
                window: "window",
            },
        ],
        output: {
            filename: "[name].js",
            chunkFilename: "chunks/[name].[contenthash].js",
            //path: path.resolve(__dirname, "dist/"),
            path: path.resolve(__dirname, "../plone.staticresources/src/plone/staticresources/static/bundles/"),
            // publicPath set in bundle entry points via __webpack_public_path__
            // See: https://webpack.js.org/guides/public-path/
            // publicPath: "/dist/",
        },
        optimization: {
            minimize: false,
            minimizer: [
                new TerserPlugin({
                    include: /(\.min\.js$)/,
                    extractComments: false,
                    terserOptions: {
                        output: {
                            comments: false,
                        },
                    },
                }),
            ],
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules\/(?!(patternslib)\/)(?!(pat-.*)\/).*/,
                    loader: "babel-loader",
                },
                {
                    test: /\.*(?:html|xml)$/i,
                    use: "raw-loader",
                },
                {
                    test: require.resolve("jquery"),
                    use: [
                        {
                            loader: "expose-loader",
                            query: "$",
                        },
                        {
                            loader: "expose-loader",
                            query: "jQuery",
                        },
                    ],
                },
                {
                    test: /\.(?:sass|scss|css)$/i,
                    use: [
                        {
                            loader: "style-loader",
                            options: {
                                insert: webpack_helpers.top_head_insert,
                            },
                        },
                        "css-loader",
                        "sass-loader",
                    ],
                },
                {
                    test: /\.(png|jpe?g|gif|svg)$/i,
                    use: "file-loader",
                },
                {
                    test: /\.svg$/,
                    loader: "svg-inline-loader",
                },
            ],
        },
        plugins: [
            new CopyPlugin({
                patterns: [
                    { from: path.resolve(__dirname, "src/polyfills-loader.js"), }, // prettier-ignore
                ],
            }),
            new CleanWebpackPlugin(),
            new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery",
                jquery: "jquery",
                Backbone: "backbone",
                _: "underscore",
            }),
            new DuplicatePackageCheckerPlugin({
                verbose: true,
                emitError: true,
            }),
        ],
        resolve: {
            alias: {},
        },
    };
    if (mode === "development") {
        // Set public path to override __webpack_public_path__
        // for webpack-dev-server
        config.output.publicPath = "/dist/";
        config.devServer = {
            inline: true,
            contentBase: "./docs/_site/",
            port: "8000",
            host: "0.0.0.0",
            watchOptions: {
                ignored: ["node_modules/**", "mockup/**", "docs/**"],
            },
        };

        // Use checked-out versions of dependencies
        try {
            const dev_includes = await fs.promises.readdir("devsrc/");
            for (const it of dev_includes) {
                if (it in [".gitkeep"]) {
                    continue;
                }
                config.resolve.alias[it] = path.resolve(
                    __dirname,
                    `devsrc/${it}`
                );
            }
        } catch (error) {
            // ignore.
        }
    }
    if (mode === "production") {
        config.entry["bundle.min"] = config.entry["bundle"];
        config.entry["bundle-polyfills.min"] = config.entry["bundle-polyfills"];
        config.output.chunkFilename = "chunks/[name].[contenthash].min.js";
    }
    return config;
};
<commit_msg>Fixup: Plone integration: Add yarn command to directly build to static resources. Static resources must be checked out next to mockup.<commit_after><|endoftext|>


<commit_before>'use strict';

const merge = require('webpack-merge');
const base = require('./webpack.config.base');

module.exports = merge(base, {
  entry: './src/main.js',
  output: {
    filename: './src/[name]_bundle.js'
  },
  node: {
    __filename: true,
    __dirname: true
  },
  target: 'electron-main',
  externals: {
    remote: true // for electron-connect
  }
});
<commit_msg>Remove unnecessary webpack config<commit_after>'use strict';

const merge = require('webpack-merge');
const base = require('./webpack.config.base');

module.exports = merge(base, {
  entry: './src/main.js',
  output: {
    filename: './src/[name]_bundle.js'
  },
  node: {
    __filename: true,
    __dirname: true
  },
  target: 'electron-main'
});
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = {
  devtool: 'source-map',
  entry: './frontend/src/entry.js',
  output: {
    path: path.resolve(__dirname, 'frontend/dist'),
    filename: 'bundle.js',
    publicPath: '/', // Development server
  },
  module: {
    loaders: [
      {
        test: /\.less$/,
        exclude: /node_modules/,
        loaders: ['style-loader', 'css-loader', 'less-loader'],
      },
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [path.resolve(__dirname, 'frontend/src')],
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react'],
        },
      },
      {
        test: /\.css$/,
        loader: 'style!css?sourceMap',
      },
      { test: /\.jpg$/, loader: 'url-loader?limit=10000&minetype=image/jpg' },
      {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff',
      }, {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff',
      }, {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/octet-stream',
      }, {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file',
      }, {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=image/svg+xml',
      },
    ],
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
        API_URL: JSON.stringify(process.env.API_URL) || JSON.stringify('http://localhost:3000')
      },
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false },
      comments: false,
      sourceMap: false,
      mangle: true,
      minimize: true,
    }),
    new webpack.ProvidePlugin({
      _: 'lodash',
      React: 'react',
      ReactDOM: 'react-dom',
      jQuery: 'jquery',
      $: 'jquery',
      Promise: 'exports?global.Promise!es6-promise',
      fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch',
    }),
    new LodashModuleReplacementPlugin,
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.AggressiveMergingPlugin(),
  ],
  resolve: {
    extensions: ['', '.js', '.json', '.jsx'],
  },
};
<commit_msg>adds GA UID to webpack config<commit_after>var path = require('path');
var webpack = require('webpack');
var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = {
  devtool: 'source-map',
  entry: './frontend/src/entry.js',
  output: {
    path: path.resolve(__dirname, 'frontend/dist'),
    filename: 'bundle.js',
    publicPath: '/', // Development server
  },
  module: {
    loaders: [
      {
        test: /\.less$/,
        exclude: /node_modules/,
        loaders: ['style-loader', 'css-loader', 'less-loader'],
      },
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [path.resolve(__dirname, 'frontend/src')],
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react'],
        },
      },
      {
        test: /\.css$/,
        loader: 'style!css?sourceMap',
      },
      { test: /\.jpg$/, loader: 'url-loader?limit=10000&minetype=image/jpg' },
      {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff',
      }, {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff',
      }, {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/octet-stream',
      }, {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file',
      }, {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=image/svg+xml',
      },
    ],
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
        API_URL: JSON.stringify(process.env.API_URL) || JSON.stringify('http://localhost:3000'),
        GA_UID: JSON.stringify(process.env.GA_UID) || JSON.stringify('""')
      },
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false },
      comments: false,
      sourceMap: false,
      mangle: true,
      minimize: true,
    }),
    new webpack.ProvidePlugin({
      _: 'lodash',
      React: 'react',
      ReactDOM: 'react-dom',
      jQuery: 'jquery',
      $: 'jquery',
      Promise: 'exports?global.Promise!es6-promise',
      fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch',
    }),
    new LodashModuleReplacementPlugin,
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.AggressiveMergingPlugin(),
  ],
  resolve: {
    extensions: ['', '.js', '.json', '.jsx'],
  },
};
<|endoftext|>