<commit_before>var tables= [];
var tablesdatatype = function (rowslength) {
    this.tableRows = [];
    this.rowLength = rowslength;
    this.columnLength =0;
    this.totalDH = 0;
    this.validTable = false;
    this.heading = "";
}

var tableRows = function() {
    this.DH = [];
    this.DT = [];
    this.CombinedText = "";
    this.lengthDH = 0;
    this.lengthDT = 0;
    this.lengthChild = 0;
    this.validRow = false;
}

function compare(a,b) {
  if (a.last_nom < b.last_nom)
     return -1;
  if (a.last_nom > b.last_nom)
    return 1;
  return 0;
}

function getValidTableIfPossible(ctable) {
    var vTable = false;
    var cLength = -1;
    var cLengthArray = {};
    for (var j=0;j<ctable.tableRows.length;j++) {
        var cRow = ctable.tableRows[j];
        if( cRow.CombinedText != "") {
            if(cLengthArray[cRow.lengthChild] !== undefined) {
                cLengthArray[cRow.lengthChild]++;
            } else {
                cLengthArray[cRow.lengthChild] = 1;
            }
        }
    }
    var sortable = [];
    for (var child in cLengthArray) {
        sortable.push([child, cLengthArray[child]])
        //console.log(child+" child "+cLengthArray[child]);
    }
    sortable.sort(function(a, b) {return -1*(a[1] - b[1])})
    cLength = sortable[0][0];
    //console.log("Clength: "+cLength);
    for (var j=0;j<ctable.tableRows.length;j++) {
        var cRow = ctable.tableRows[j];
        if(cRow.lengthChild  != cLength ||cRow.CombinedText == "") {
            cRow.validRow = false;
            ctable.totalDH = ctable.totalDH - cRow.lengthDH;
            ctable.rowLength = ctable.rowLength - 1;
        }
    }
    ctable.validTable = true;
    return cLength;

}

function verifyPrintGoodTables(ctable) {
    var vTable = true;
    var cLength = -1;
    for (var j=0;j<ctable.tableRows.length;j++) {
        var cRow = ctable.tableRows[j];
        if(cLength == -1) {
            cLength = cRow.lengthChild;
        } else if ( cLength != cRow.lengthChild) {
            vTable = false;
        }
        if(cRow.lengthDH + cRow.lengthDT == cRow.lengthChild) {
            cRow.validRow = true;
        }
    }
    if(vTable) {
        //console.log("table is valid: "+cLength);
        ctable.validTable = vTable;
        return cLength;
    } else {
        return getValidTableIfPossible(ctable);
    }
}

function cleanString(myString) {
    return myString.replace(/[\r\n]/g,"").replace(/\"/g,"");
}

function getJSONType1(table) {
    //console.log("JSONizing with type 1,table.tableRows.length :"+table.tableRows.length);
    var array = {};
    var jsoncollection= {};
    var firstrow = -1;
    for(var i=0; i < table.tableRows.length; i++) {
        if (table.tableRows[i].validRow) {
            if(firstrow == -1 ) {
                if(table.tableRows[i].lengthDH > 0){
                    firstrow = i;
                    continue;
                } else {
                    return undefined;
                }
            }
            for( var j=0; j < table.columnLength; j++){
            //    console.log(cleanString(table.tableRows[0].DH[j])+" : "+cleanString(table.tableRows[i].DT[j]));
                array[cleanString(table.tableRows[firstrow].DH[j])] = cleanString(table.tableRows[i].DT[j]);
            }
            jsoncollection[i]=array;
            array = {};
       }
    }
    return(jsoncollection);
    //return(("{"+jsoncollection.toString()+"}"));
}

function getJSONType4(table) {
    //console.log("JSONizing with type 1,table.tableRows.length :"+table.tableRows.length);
    var array = {};
    var jsoncollection= {};
    var firstrow = -1;
    for(var i=0; i < table.tableRows.length; i++) {
        if (table.tableRows[i].validRow) {
            if(firstrow == -1 ) {
                    firstrow = i;
                    continue;
            }
            for( var j=0; j < table.columnLength; j++){
            //    console.log(cleanString(table.tableRows[0].DH[j])+" : "+cleanString(table.tableRows[i].DT[j]));
                array[cleanString(table.tableRows[firstrow].DT[j])] = cleanString(table.tableRows[i].DT[j]);
            }
            jsoncollection[i]=array;
            array = {};
       }
    }
    return(jsoncollection);
    //return(("{"+jsoncollection.toString()+"}"));
}

function getJSONType2(table) {
    //console.log("JSONizing with type 2");
    var array = {};
    for(var i=0; i < table.tableRows.length; i++) {
        if (table.tableRows[i].validRow) {
 //           console.log(cleanString(table.tableRows[i].DH[0])+" : "+cleanString(table.tableRows[i].DT[0]));
            array[cleanString(table.tableRows[i].DH[0])] = cleanString(table.tableRows[i].DT[0]);
        }
    }
    return(array);
}

function getJSONType3(table) {
    //console.log("JSONizing with type 3");
    var array = {};
    for(var i=0; i < table.tableRows.length; i++) {
        if (table.tableRows[i].validRow) {
            //console.log(cleanString(table.tableRows[i].DT[0])+" : "+cleanString(table.tableRows[i].DT[1]));
                array[cleanString(table.tableRows[i].DT[0])] = cleanString(table.tableRows[i].DT[1]);
        }
    }
/*    array = array.reduce(function(m,i){
        var s = i.split(':');
        m[s.shift()] = s.join(':');
        return m;
    }, {});*/
    return (array);
}

function getJSON(table) {
    //console.log("totalDH: "+table.totalDH+"table.columnLength: "+ table.columnLength+ "table.rowLength: "+table.rowLength);
    if(table.rowLength > 2){
        if(table.totalDH == table.columnLength ) {
            //console.log("Jsoning the table as type 1");
            return getJSONType1(table);
        } else if (table.totalDH == table.rowLength) {
            //console.log("Jsoning the table as type 2");
            return getJSONType2(table);
        } else if ( table.totalDH == 0 && table.columnLength==2) {
            //console.log("Jsoning the table as type 3");
            return getJSONType3(table);
        } else if ( table.totalDH == 0 && table.columnLength > 2) {
            //console.log("Jsoning the table as type 3");
            return getJSONType4(table);
        }
    } else {
        return undefined;
    }
}

function jsonizeValidTables() {
    //console.log("jsoning the tables");
    var finaljsonobj = {};
    for (var i = 0;i < tables.length; i++) {
        if(tables[i].validTable) {
            var json = getJSON(tables[i]);
            if(json !== undefined && json != "{}") {
               finaljsonobj[tables[i].heading] = json;
            } else {
    //            console.log("This type of table yet not supported :"+"totalDH: "+tables[i].totalDH+"table.columnLength: "+ tables[i].columnLength+ "table.rowLength: "+tables[i].rowLength);
            }
        }
    }
/*    finaljsonobj = finaljsonobj.reduce(function(m,i){
        var s = i.split(':');
        m[s.shift()] = s.join(':');
        return m;
    }, {});*/
    return(JSON.stringify(finaljsonobj, undefined, 2));

}

exports.jsonifyTable = function(errors,window) {
    var $ = window.$;
    var tablenum = 0;
    //console.log("Number of table: "+$("table").length);
    $("table").each(function() {
            tablenum++;
            //console.log("New Table");
            var currenttable = new tablesdatatype($(this).find("tr").length);
            tables[tables.length] = currenttable;
            //console.log($(this).find("tr").length);
//            console.log("heading"+$(this).prev(":header").text());
            currenttable.heading =  $(this).prev(":header").text();
            var parent__ = $(this).parent();
            var max = 5;
            if(currenttable.heading  == "" && parent__ !== undefined && max >0 ) {
                currenttable.heading = parent__.prev(":header").text();
                parent__ = parent__.parent();
                max--;
//                console.log(parent__);
            }
            if(currenttable.heading  == "") {
                currenttable.heading = tablenum;
            }
            $(this).find("tr").each(function(){
//                console.log("New table row");
                var currentTableRows = new tableRows();
                currentTableRows.lengthDH = $(this).find("th").length;
                currentTableRows.lengthDT = $(this).find("td").length;
                currentTableRows.lengthChild = $(this).children().length;
//                console.log("TH NODES: "+$(this).find("th").length);
  //              console.log("TD NODES: "+$(this).find("td").length);
    //            console.log("Children: "+$(this).children().length);
                    //console.log($(this).text());
                currentTableRows.CombinedText = "";
                $(this).find("th").each(function(){
                    currentTableRows.DH[currentTableRows.DH.length] = $(this).text();
                    currentTableRows.CombinedText = currentTableRows.CombinedText + $(this).text();
//                    console.log("TH: "+$(this).text());
                    currenttable.totalDH++;
                });
                $(this).find("td").each(function(){
                    currentTableRows.DT[currentTableRows.DT.length] = $(this).text();
                    currentTableRows.CombinedText = currentTableRows.CombinedText + $(this).text();
  //                  console.log("TD: "+ $(this).text());

                });
                currenttable.tableRows[currenttable.tableRows.length]= currentTableRows;
            });
            currenttable.columnLength =  verifyPrintGoodTables(currenttable);
//        console.log(" -", $(this).children());
    });
    console.log(jsonizeValidTables());
}
<commit_msg>moving from find to children(non depth sol)<commit_after>var tables= [];
var tablesdatatype = function (rowslength) {
    this.tableRows = [];
    this.rowLength = rowslength;
    this.columnLength =0;
    this.totalDH = 0;
    this.validTable = false;
    this.heading = "";
}

var tableRows = function() {
    this.DH = [];
    this.DT = [];
    this.CombinedText = "";
    this.lengthDH = 0;
    this.lengthDT = 0;
    this.lengthChild = 0;
    this.validRow = false;
}

function compare(a,b) {
  if (a.last_nom < b.last_nom)
     return -1;
  if (a.last_nom > b.last_nom)
    return 1;
  return 0;
}

function getValidTableIfPossible(ctable) {
    var vTable = false;
    var cLength = -1;
    var cLengthArray = {};
    for (var j=0;j<ctable.tableRows.length;j++) {
        var cRow = ctable.tableRows[j];
        if( cRow.CombinedText != "") {
            if(cLengthArray[cRow.lengthChild] !== undefined) {
                cLengthArray[cRow.lengthChild]++;
            } else {
                cLengthArray[cRow.lengthChild] = 1;
            }
        }
    }
    var sortable = [];
    for (var child in cLengthArray) {
        sortable.push([child, cLengthArray[child]])
        //console.log(child+" child "+cLengthArray[child]);
    }
    sortable.sort(function(a, b) {return -1*(a[1] - b[1])})
    if(sortable[0] && sortable[0][0]) {
        cLength = sortable[0][0];
        console.log("Clength: "+cLength+"  " +cLengthArray[cLength]);
        for (var j=0;j<ctable.tableRows.length;j++) {
            var cRow = ctable.tableRows[j];
            if(cRow.lengthChild  != cLength || cRow.CombinedText == "") {
                cRow.validRow = false;
                ctable.totalDH = ctable.totalDH - cRow.lengthDH;
                ctable.rowLength = ctable.rowLength - 1;
                console.log("invalidating the row");
            }
        }
        console.log("Clength: row length "+ctable.rowLength+"  " +ctable.totalDH );
        ctable.validTable = true;
    } else {
        ctable.validTable = false;

    }
    return cLength;

}

function verifyPrintGoodTables(ctable) {
    var vTable = true;
    var cLength = -1;
    for (var j=0;j<ctable.tableRows.length;j++) {
        var cRow = ctable.tableRows[j];
        if(cLength == -1) {
            cLength = cRow.lengthChild;
        } else if ( cLength != cRow.lengthChild) {
            vTable = false;
        }
        if(cRow.lengthDH + cRow.lengthDT == cRow.lengthChild) {
            cRow.validRow = true;
        }
    }
    if(vTable) {
        //console.log("table is valid: "+cLength);
        ctable.validTable = vTable;
        return cLength;
    } else {
        return getValidTableIfPossible(ctable);
    }
}

function cleanString(myString) {
    if(myString) {
        return myString.replace(/[\r\n]/g,"").replace(/\"/g,"").replace(/[^a-zA-Z0-9]/g,' ');;
    } else {
        console.log("undefined thing for cleaning");
        return "";
    }
}

function getJSONType1(table) {
    console.log("JSONizing with type 1,table.tableRows.length :"+table.tableRows.length);
    var array = {};
    var jsoncollection= {};
    var firstrow = -1;
    for(var i=0; i < table.tableRows.length; i++) {
        if (table.tableRows[i].validRow) {
            if(firstrow == -1 ) {
                if(table.tableRows[i].lengthDH > 0){
                    firstrow = i;
                    continue;
                } else {
                    return undefined;
                }
            }
            for( var j=0; j < table.columnLength; j++){
            //    console.log(cleanString(table.tableRows[0].DH[j])+" : "+cleanString(table.tableRows[i].DT[j]));
                array[cleanString(table.tableRows[firstrow].DH[j])] = cleanString(table.tableRows[i].DT[j]);
            }
            jsoncollection[i]=array;
            array = {};
       }
    }
    return(jsoncollection);
    //return(("{"+jsoncollection.toString()+"}"));
}

function getJSONType4(table) {
    console.log("JSONizing with type 1,table.tableRows.length :"+table.tableRows.length);
    var array = {};
    var jsoncollection= {};
    var firstrow = -1;
    for(var i=0; i < table.tableRows.length; i++) {
        if (table.tableRows[i].validRow) {
            if(firstrow == -1 ) {
                    firstrow = i;
                    continue;
            }
            for( var j=0; j < table.columnLength; j++){
            //    console.log(cleanString(table.tableRows[0].DH[j])+" : "+cleanString(table.tableRows[i].DT[j]));
                array[cleanString(table.tableRows[firstrow].DT[j])] = cleanString(table.tableRows[i].DT[j]);
            }
            jsoncollection[i]=array;
            array = {};
       }
    }
    return(jsoncollection);
    //return(("{"+jsoncollection.toString()+"}"));
}

function getJSONType2(table) {
    console.log("JSONizing with type 2");
    var array = {};
    for(var i=0; i < table.tableRows.length; i++) {
        if (table.tableRows[i].validRow) {
 //           console.log(cleanString(table.tableRows[i].DH[0])+" : "+cleanString(table.tableRows[i].DT[0]));
            array[cleanString(table.tableRows[i].DH[0])] = cleanString(table.tableRows[i].DT[0]);
        }
    }
    return(array);
}

function getJSONType3(table) {
    console.log("JSONizing with type 3");
    var array = {};
    for(var i=0; i < table.tableRows.length; i++) {
        if (table.tableRows[i].validRow) {
      //      console.log("lengths DT "+table.tableRows[i].lengthDT+" length DH"+table.tableRows[i].lengthDH);
                if(table.tableRows[i].lengthDT == 2) {
                    array[cleanString(table.tableRows[i].DT[0])] = cleanString(table.tableRows[i].DT[1]);
                } else if (table.tableRows[i].lengthDT == 1 && table.tableRows[i].lengthDH == 1 ) {
    //                console.log(table.tableRows[i].DH[0] +" DT length : "+table.tableRows[i].DT[0]);
                    array[cleanString(table.tableRows[i].DH[0])] = cleanString(table.tableRows[i].DT[0]);
                } else if(table.tableRows[i].lengthDH == 2) {
                    array[cleanString(table.tableRows[i].DH[0])] = cleanString(table.tableRows[i].DH[1]);
                }
        }
    }
/*    array = array.reduce(function(m,i){
        var s = i.split(':');
        m[s.shift()] = s.join(':');
        return m;
    }, {});*/
    return (array);
}

function getJSON(table) {
    console.log("totalDH: "+table.totalDH+"table.columnLength: "+ table.columnLength+ "table.rowLength: "+table.rowLength);
    if(table.rowLength > 2){
        if(table.totalDH == table.columnLength ) {
            //console.log("Jsoning the table as type 1");
            return getJSONType1(table);
        } else if (table.totalDH == table.rowLength) {
            //console.log("Jsoning the table as type 2");
            return getJSONType2(table);
        } else if ( table.totalDH == 0 && table.columnLength==2) {
            //console.log("Jsoning the table as type 3");
            return getJSONType3(table);
        } else if ( table.totalDH == 0 && table.columnLength > 2) {
            //console.log("Jsoning the table as type 3");
            return getJSONType4(table);
        } else if ( table.columnLength==2) {
            //console.log("Jsoning the table as type 3");
            return getJSONType3(table);
        }
    } else {
        return undefined;
    }
}

function jsonizeValidTables() {
    //console.log("jsoning the tables");
    var finaljsonobj = {};
    for (var i = 0;i < tables.length; i++) {
        if(tables[i].validTable) {
            var json = getJSON(tables[i]);
            if(json !== undefined && json != "{}") {
               finaljsonobj[tables[i].heading] = json;
            } else {
    //            console.log("This type of table yet not supported :"+"totalDH: "+tables[i].totalDH+"table.columnLength: "+ tables[i].columnLength+ "table.rowLength: "+tables[i].rowLength);
            }
        }
    }
/*    finaljsonobj = finaljsonobj.reduce(function(m,i){
        var s = i.split(':');
        m[s.shift()] = s.join(':');
        return m;
    }, {});*/
    return(JSON.stringify(finaljsonobj, undefined, 2));

}

exports.jsonifyTable = function(errors,window) {
    var $ = window.$;
    var tablenum = 0;
    //console.log("Number of table: "+$("table").length);
    $("table").each(function() {
            tablenum++;
            //console.log("New Table");
            var currenttable = new tablesdatatype($(this).find("tr").length);
            tables[tables.length] = currenttable;
            //console.log($(this).find("tr").length);
//            console.log("heading"+$(this).prev(":header").text());
            currenttable.heading =  $(this).prev(":header").text();
            var parent__ = $(this).parent();
            var max = 5;
            if(currenttable.heading  == "" && parent__ !== undefined && max >0 ) {
                currenttable.heading = parent__.prev(":header").text();
                parent__ = parent__.parent();
                max--;
//                console.log(parent__);
            }
            if(currenttable.heading  == "") {
                currenttable.heading = tablenum;
            }
            $(this).children("tr").each(function(){
                console.log("New table row");
                var currentTableRows = new tableRows();
//                currentTableRows.lengthDH = $(this).find("th").length;
  //              currentTableRows.lengthDT = $(this).find("td").length;
                currentTableRows.lengthChild = $(this).children().length;
//                console.log("TH NODES: "+$(this).find("th").length);
  //              console.log("TD NODES: "+$(this).find("td").length);
    //            console.log("Children: "+$(this).children().length);
                    //console.log($(this).text());
                currentTableRows.CombinedText = "";
                $(this).children().each(function() {
                    console.log($(this).prop('tagName'));
                    if($(this).prop('tagName') == "TH") {
                        currentTableRows.DH[currentTableRows.DH.length] = $(this).text();
                        currentTableRows.CombinedText = currentTableRows.CombinedText + $(this).text();
                        console.log("TH: "+$(this).text());
                        currenttable.totalDH++;
                        currentTableRows.lengthDH++;
                    } else if ($(this).prop('tagName') == "TD") {
                        currentTableRows.DT[currentTableRows.DT.length] = $(this).text();
                        currentTableRows.CombinedText = currentTableRows.CombinedText + $(this).text();
                        console.log("TD: "+ $(this).text());
                        currentTableRows.lengthDT++;

                    }
                });
                /*$(this).find("th").each(function(){
                    currentTableRows.DH[currentTableRows.DH.length] = $(this).text();
                    currentTableRows.CombinedText = currentTableRows.CombinedText + $(this).text();
//                    console.log("TH: "+$(this).text());
                    currenttable.totalDH++;
                });
                $(this).find("td").each(function(){
                    currentTableRows.DT[currentTableRows.DT.length] = $(this).text();
                    currentTableRows.CombinedText = currentTableRows.CombinedText + $(this).text();
  //                  console.log("TD: "+ $(this).text());

                });*/
                currenttable.tableRows[currenttable.tableRows.length]= currentTableRows;
            });
            currenttable.columnLength =  verifyPrintGoodTables(currenttable);
//        console.log(" -", $(this).children());
    });
    console.log(jsonizeValidTables());
}
<|endoftext|>


<commit_before>import AuthenticatedRoute from 'ghost-admin/routes/authenticated';
import {action} from '@ember/object';
import {bind} from '@ember/runloop';
import {inject as service} from '@ember/service';

export default class SettingsDesignCustomizeRoute extends AuthenticatedRoute {
    @service feature;
    @service modals;
    @service settings;

    beforeModel() {
        super.beforeModel(...arguments);

        if (!this.session.user.isAdmin) {
            return this.transitionTo('site');
        }

        if (!this.feature.customThemeSettings) {
            return this.transitionTo('settings');
        }
    }

    activate() {
        this.customizeModal = this.modals.open('modals/design/customize', {
            saveTask: this.controllerFor('settings.design.customize').saveTask
        }, {
            className: 'fullscreen-modal-full-overlay fullscreen-modal-branding-modal',
            beforeClose: bind(this, this.beforeModalClose)
        });
    }

    @action
    async willTransition(transition) {
        if (this.settings.get('hasDirtyAttributes')) {
            transition.abort();

            const shouldLeave = await this.confirmUnsavedChanges();

            if (shouldLeave) {
                return transition.retry();
            }
        } else {
            return true;
        }
    }

    deactivate() {
        this.customizeModal?.close();
        this.customizeModal = null;
        this.confirmModal = null;
    }

    async beforeModalClose() {
        const shouldLeave = await this.confirmUnsavedChanges();

        if (shouldLeave === true) {
            this.transitionTo('settings.design');
        } else {
            // prevent modal from closing
            return false;
        }
    }

    confirmUnsavedChanges() {
        if (!this.settings.get('hasDirtyAttributes')) {
            return Promise.resolve(true);
        }

        if (!this.confirmModal) {
            this.confirmModal = this.modals.open('modals/confirm-unsaved-changes', {}, {
                className: 'fullscreen-modal-action fullscreen-modal-wide'
            }).then((discardChanges) => {
                if (discardChanges === true) {
                    this.settings.rollbackAttributes();
                }
                return discardChanges;
            }).finally(() => {
                this.confirmModal = null;
            });
        }

        return this.confirmModal;
    }
}
<commit_msg>Fixed unexpected redirect when navigating away from customize modal<commit_after>import AuthenticatedRoute from 'ghost-admin/routes/authenticated';
import {action} from '@ember/object';
import {bind} from '@ember/runloop';
import {inject as service} from '@ember/service';

export default class SettingsDesignCustomizeRoute extends AuthenticatedRoute {
    @service feature;
    @service modals;
    @service settings;

    customizeModal = null;
    confirmModal = null;
    hasConfirmed = false;

    beforeModel() {
        super.beforeModel(...arguments);

        if (!this.session.user.isAdmin) {
            return this.transitionTo('site');
        }

        if (!this.feature.customThemeSettings) {
            return this.transitionTo('settings');
        }
    }

    activate() {
        this.customizeModal = this.modals.open('modals/design/customize', {
            saveTask: this.controllerFor('settings.design.customize').saveTask
        }, {
            className: 'fullscreen-modal-full-overlay fullscreen-modal-branding-modal',
            beforeClose: bind(this, this.beforeModalClose)
        });
    }

    @action
    async willTransition(transition) {
        if (this.settings.get('hasDirtyAttributes')) {
            transition.abort();

            const shouldLeave = await this.confirmUnsavedChanges();
            this.hasConfirmed = true;

            if (shouldLeave) {
                return transition.retry();
            }
        } else {
            this.hasConfirmed = true;
            return true;
        }
    }

    deactivate() {
        this.customizeModal?.close();
        this.customizeModal = null;
        this.confirmModal = null;
        this.hasConfirmed = false;
    }

    async beforeModalClose() {
        if (this.hasConfirmed) {
            return;
        }

        const shouldLeave = await this.confirmUnsavedChanges();

        if (shouldLeave === true) {
            this.transitionTo('settings.design');
        } else {
            // prevent modal from closing
            return false;
        }
    }

    confirmUnsavedChanges() {
        if (!this.settings.get('hasDirtyAttributes')) {
            return Promise.resolve(true);
        }

        if (!this.confirmModal) {
            this.confirmModal = this.modals.open('modals/confirm-unsaved-changes', {}, {
                className: 'fullscreen-modal-action fullscreen-modal-wide'
            }).then((discardChanges) => {
                if (discardChanges === true) {
                    this.settings.rollbackAttributes();
                }
                return discardChanges;
            }).finally(() => {
                this.confirmModal = null;
            });
        }

        return this.confirmModal;
    }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Route, Switch } from 'react-router-dom'
import PropTypes from 'prop-types'
import Loadable from '@7rulnik/react-loadable'
import Loading from './components/Loading/Loading'
import AuthActionCreator from './actions/auth'
import ForgotPasswordForm from './components/ForgotPasswordForm/ForgotPasswordForm'
import Header from './components/Header/Header'
import Home from './components/Home/Home'
import About from './components/About/About'
import LoginForm from './components/LoginForm/LoginForm'
import restricted from './components/Restricted/Restricted'
import SignupForm from './components/SignupForm/SignupForm'
import Version from './components/Version/Version'
import LandingA from './components/LandingA/LandingA'
import LandingC from './components/LandingC/LandingC'
import ProjectDetail from './components/Project/ProjectDetail'
import Footer from './components/LandingF/LandingF'
import LandingB from './components/LandingB/LandingB'
import LandingE from './components/LandingE/LandingE'
import LandingD from './components/LandingD/LandingD'

// set up components for lazy loading
const ProfileRestrictedLoadable = restricted(Loadable({
  loader: () => import('./components/Profile/Profile'),
  loading: Loading
}))

const CreateProjectRestrictedLoadable = restricted(Loadable({
  loader: () => import('./components/CreateProjectForm/CreateProjectForm'),
  loading: Loading
}))

const ApplicationsRestrictedLoadable = restricted(Loadable({
  loader: () => import('./components/Applications/ApplicationsList'),
  loading: Loading
}))

class App extends Component {
  componentDidMount () {
    this.props.appLoad()
  }

  renderAppLoaded () {
    return (

        <Version />
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route path='/about' component={About}/>
          <Route path='/create-project' component={CreateProjectRestrictedLoadable}/>
          <Route path='/forgot-password' component={ForgotPasswordForm}/>
          <Route path='/login' component={LoginForm}/>
          <Route path='/profile' component={ProfileRestrictedLoadable}/>
          <Route path='/signup' component={SignupForm}/>
          <Route path='/landing-a' component={LandingA} />
          <Route path='/landing-c' component={LandingC} />
          <Route path='/landing-f' component={Footer} />
          <Route path='/landing-b' component={LandingB} />
          <Route path='/landing-f' component={Footer} />
          <Route path='/landing-e' component={LandingE} />
          <Route path='/landing-d' component={LandingD} />
          <Route path='/show-applications' component={ApplicationsRestrictedLoadable} />
          <Route path='/projects/:id' component={ProjectDetail} />
        </Switch>

    )
  }

  renderAppNotLoaded () {
    return (

    )
  }

  render () {
    return this.props.appLoaded
      ? this.renderAppLoaded()
      : this.renderAppNotLoaded()
  }
}

function mapStateToProps (state) {
  return {
    appLoaded: state.common.appLoaded
  }
}

const mapDispatchToProps = {
  appLoad: AuthActionCreator.appLoad
}

App.propTypes = {
  appLoad: PropTypes.func,
  appLoaded: PropTypes.bool
}

export default connect(mapStateToProps, mapDispatchToProps)(App)
<commit_msg>fixed error<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Route, Switch } from 'react-router-dom'
import PropTypes from 'prop-types'
import Loadable from '@7rulnik/react-loadable'
import Loading from './components/Loading/Loading'
import AuthActionCreator from './actions/auth'
import ForgotPasswordForm from './components/ForgotPasswordForm/ForgotPasswordForm'
import Header from './components/Header/Header'
import Home from './components/Home/Home'
import About from './components/About/About'
import LoginForm from './components/LoginForm/LoginForm'
import restricted from './components/Restricted/Restricted'
import SignupForm from './components/SignupForm/SignupForm'
import Version from './components/Version/Version'
import LandingA from './components/LandingA/LandingA'
import LandingC from './components/LandingC/LandingC'
import ProjectDetail from './components/Project/ProjectDetail'
import Footer from './components/LandingF/LandingF'
import LandingB from './components/LandingB/LandingB'
import LandingE from './components/LandingE/LandingE'
import LandingD from './components/LandingD/LandingD'
import LandingF from './components/LandingF/LandingF'

// set up components for lazy loading
const ProfileRestrictedLoadable = restricted(Loadable({
  loader: () => import('./components/Profile/Profile'),
  loading: Loading
}))

const CreateProjectRestrictedLoadable = restricted(Loadable({
  loader: () => import('./components/CreateProjectForm/CreateProjectForm'),
  loading: Loading
}))

const ApplicationsRestrictedLoadable = restricted(Loadable({
  loader: () => import('./components/Applications/ApplicationsList'),
  loading: Loading
}))

class App extends Component {
  componentDidMount () {
    this.props.appLoad()
  }

  renderAppLoaded () {
    return (

        <Version />
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route path='/about' component={About}/>
          <Route path='/create-project' component={CreateProjectRestrictedLoadable}/>
          <Route path='/forgot-password' component={ForgotPasswordForm}/>
          <Route path='/login' component={LoginForm}/>
          <Route path='/profile' component={ProfileRestrictedLoadable}/>
          <Route path='/signup' component={SignupForm}/>
          <Route path='/landing-a' component={LandingA} />
          <Route path='/landing-c' component={LandingC} />
          <Route path='/landing-f' component={Footer} />
          <Route path='/landing-b' component={LandingB} />
          <Route path='/landing-f' component={Footer} />
          <Route path='/landing-e' component={LandingE} />
          <Route path='/landing-d' component={LandingD} />
          <Route path='/show-applications' component={ApplicationsRestrictedLoadable} />
          <Route path='/projects/:id' component={ProjectDetail} />
        </Switch>

    )
  }

  renderAppNotLoaded () {
    return (

    )
  }

  render () {
    return this.props.appLoaded
      ? this.renderAppLoaded()
      : this.renderAppNotLoaded()
  }
}

function mapStateToProps (state) {
  return {
    appLoaded: state.common.appLoaded
  }
}

const mapDispatchToProps = {
  appLoad: AuthActionCreator.appLoad
}

App.propTypes = {
  appLoad: PropTypes.func,
  appLoaded: PropTypes.bool
}

export default connect(mapStateToProps, mapDispatchToProps)(App)
<|endoftext|>


<commit_before>module.exports = {
  siteMetadata: {
    title: '@resir014',
    description: 'Web developer based in Jakarta, Indonesia.',
    siteUrl: `https://resir014.xyz`,
    author: {
      name: 'Resi Respati',
      url: 'https://twitter.com/resir014',
      email: 'resir014@gmail.com'
    }
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'pages',
        path: `${__dirname}/src/pages`
      }
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'data',
        path: `${__dirname}/src/data`
      }
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-responsive-iframe`,
            options: {
              wrapperStyle: `margin-bottom: 1rem`
            }
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-autolink-headers',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants'
        ]
      }
    },
    {
      resolve: 'gatsby-plugin-canonical-urls',
      options: {
        siteUrl: `https://resir014.xyz`
      }
    },
    {
      resolve: `gatsby-plugin-feed`,
      options: {
        query: `
          {
            site {
              siteMetadata {
                title
                description
                siteUrl
                site_url: siteUrl
              }
            }
          }
        `,
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) => {
              return allMarkdownRemark.edges.map(edge => {
                return Object.assign({}, edge.node.frontmatter, {
                  description: edge.node.excerpt,
                  url: site.siteMetadata.siteUrl + edge.node.fields.slug,
                  guid: site.siteMetadata.siteUrl + edge.node.fields.slug,
                  custom_elements: [{ 'content:encoded': edge.node.html }],
                });
              });
            },
            query: `
              {
                allMarkdownRemark(
                  limit: 10,
                  filter: {id: {regex: "/blog/"}},
                  sort: {fields: [fields___date], order: DESC}
                ) {
                  edges {
                    node {
                      excerpt
                      html
                      fields {
                        slug
                        date
                      }
                      frontmatter {
                        title
                      }
                    }
                  }
                }
              }
            `,
            output: '/blog.xml',
            feedTitle: 'All posts by @resir014'
          }
        ]
      }
    },
    {
      resolve: 'gatsby-plugin-nprogress',
      options: {
        color: '#fff',
      },
    },
    'gatsby-transformer-json',
    'gatsby-plugin-twitter',
    'gatsby-plugin-sass',
    'gatsby-plugin-typescript',
    'gatsby-plugin-glamor',
    'gatsby-plugin-react-helmet'
  ]
}
<commit_msg>don't show spinner on nprogress<commit_after>module.exports = {
  siteMetadata: {
    title: '@resir014',
    description: 'Web developer based in Jakarta, Indonesia.',
    siteUrl: `https://resir014.xyz`,
    author: {
      name: 'Resi Respati',
      url: 'https://twitter.com/resir014',
      email: 'resir014@gmail.com'
    }
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'pages',
        path: `${__dirname}/src/pages`
      }
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'data',
        path: `${__dirname}/src/data`
      }
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-responsive-iframe`,
            options: {
              wrapperStyle: `margin-bottom: 1rem`
            }
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-autolink-headers',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants'
        ]
      }
    },
    {
      resolve: 'gatsby-plugin-canonical-urls',
      options: {
        siteUrl: `https://resir014.xyz`
      }
    },
    {
      resolve: `gatsby-plugin-feed`,
      options: {
        query: `
          {
            site {
              siteMetadata {
                title
                description
                siteUrl
                site_url: siteUrl
              }
            }
          }
        `,
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) => {
              return allMarkdownRemark.edges.map(edge => {
                return Object.assign({}, edge.node.frontmatter, {
                  description: edge.node.excerpt,
                  url: site.siteMetadata.siteUrl + edge.node.fields.slug,
                  guid: site.siteMetadata.siteUrl + edge.node.fields.slug,
                  custom_elements: [{ 'content:encoded': edge.node.html }],
                });
              });
            },
            query: `
              {
                allMarkdownRemark(
                  limit: 10,
                  filter: {id: {regex: "/blog/"}},
                  sort: {fields: [fields___date], order: DESC}
                ) {
                  edges {
                    node {
                      excerpt
                      html
                      fields {
                        slug
                        date
                      }
                      frontmatter {
                        title
                      }
                    }
                  }
                }
              }
            `,
            output: '/blog.xml',
            feedTitle: 'All posts by @resir014'
          }
        ]
      }
    },
    {
      resolve: 'gatsby-plugin-nprogress',
      options: {
        color: '#fff',
        showSpinner: false
      },
    },
    'gatsby-transformer-json',
    'gatsby-plugin-twitter',
    'gatsby-plugin-sass',
    'gatsby-plugin-typescript',
    'gatsby-plugin-glamor',
    'gatsby-plugin-react-helmet'
  ]
}
<|endoftext|>


<commit_before>import _ from 'lodash'

import { LOCATION_CHANGE } from 'react-router-redux'
import {
  BEACONS,
  GUI,
  HEAD_FAILURE,
  HEAD_SUCCESS,
  LOAD_STREAM_SUCCESS,
  PROFILE,
  SET_LAYOUT_MODE,
} from '../constants/action_types'

let location = {}
const oldDate = new Date()
oldDate.setFullYear(oldDate.getFullYear() - 2)
// order matters for matching routes
const initialState = {
  activeNotificationsTabType: 'all',
  currentStream: '/following',
  isOffsetLayout: false,
  history: {},
  lastNotificationCheck: oldDate.toUTCString(),
  modes: [
    { label: 'root', mode: 'grid', regex: '^\/$' },
    { label: 'discover', mode: 'grid', regex: '\/discover|\/explore' },
    { label: 'following', mode: 'grid', regex: '\/following' },
    { label: 'invitations', mode: 'list', regex: '\/invitations' },
    { label: 'onboarding', mode: 'grid', regex: '\/onboarding' },
    { label: 'notifications', mode: 'list', regex: '\/notifications' },
    { label: 'search', mode: 'grid', regex: '\/search|\/find' },
    { label: 'settings', mode: 'list', regex: '\/settings' },
    { label: 'starred', mode: 'list', regex: '\/starred' },
    { label: 'staff', mode: 'list', regex: '\/staff' },
    { label: 'posts', mode: 'list', regex: '\/[\\w\\-]+\/post\/.+' },
    { label: 'users/following', mode: 'grid', regex: '\/[\\w\\-]+\/following' },
    { label: 'users/followers', mode: 'grid', regex: '\/[\\w\\-]+\/followers' },
    { label: 'users/loves', mode: 'grid', regex: '\/[\\w\\-]+\/loves' },
    { label: 'users', mode: 'list', regex: '\/[\\w\\-]+' },
  ],
  newNotificationContent: false,
}

export function findLayoutMode(modes) {
  for (const mode of modes) {
    const regex = new RegExp(mode.regex)
    if (regex.test(location.pathname)) {
      return mode
    }
  }
  return modes[modes.length - 1]
}

const STREAMS_WHITELIST = [
  /discover/,
  /following/,
  /starred/,
]

export function gui(state = initialState, action = { type: '' }) {
  const newState = { ...state }
  let mode = null
  let pathname = null
  switch (action.type) {
    case BEACONS.LAST_DISCOVER_VERSION:
      return { ...state, lastDiscoverBeaconVersion: action.payload.version }
    case BEACONS.LAST_FOLLOWING_VERSION:
      return { ...state, lastFollowingBeaconVersion: action.payload.version }
    case BEACONS.LAST_STARRED_VERSION:
      return { ...state, lastStarredBeaconVersion: action.payload.version }
    case HEAD_FAILURE:
      return { ...state, newNotificationContent: false }
    case HEAD_SUCCESS:
      if (action.payload.serverResponse.status === 204) {
        return { ...state, newNotificationContent: true }
      }
      return state
    case LOAD_STREAM_SUCCESS:
      if (action.meta && /\/notifications/.test(action.meta.resultKey)) {
        return {
          ...state,
          newNotificationContent: false,
          lastNotificationCheck: new Date().toUTCString(),
        }
      }
      return state
    case PROFILE.DELETE_SUCCESS:
      return { ...initialState }
    case SET_LAYOUT_MODE:
      mode = findLayoutMode(newState.modes)
      if (mode.mode === action.payload.mode) return state
      mode.mode = action.payload.mode
      return newState
    case LOCATION_CHANGE:
      location = action.payload
      pathname = location.pathname

      if (_.some(STREAMS_WHITELIST, re => re.test(pathname))) {
        return { ...state, currentStream: pathname }
      }

      return { ...state }
    case GUI.NOTIFICATIONS_TAB:
      return { ...state, activeNotificationsTabType: action.payload.activeTabType }
    case GUI.SET_SCROLL:
      newState.history[action.payload.key] = { ...action.payload }
      return newState
    case GUI.SET_IS_OFFSET_LAYOUT:
      return { ...state, isOffsetLayout: action.payload.isOffsetLayout }
    case GUI.BIND_DISCOVER_KEY:
      return { ...newState, discoverKeyType: action.payload.type }
    default:
      return state
  }
}

// this is used for testing in StreamComponent_test
export function setLocation(loc) {
  location = loc
}

<commit_msg>clear discoverKeyType on logout<commit_after>import _ from 'lodash'

import { LOCATION_CHANGE } from 'react-router-redux'
import {
  AUTHENTICATION,
  BEACONS,
  GUI,
  HEAD_FAILURE,
  HEAD_SUCCESS,
  LOAD_STREAM_SUCCESS,
  PROFILE,
  SET_LAYOUT_MODE,
} from '../constants/action_types'

let location = {}
const oldDate = new Date()
oldDate.setFullYear(oldDate.getFullYear() - 2)
// order matters for matching routes
const initialState = {
  activeNotificationsTabType: 'all',
  currentStream: '/following',
  isOffsetLayout: false,
  history: {},
  lastNotificationCheck: oldDate.toUTCString(),
  modes: [
    { label: 'root', mode: 'grid', regex: '^\/$' },
    { label: 'discover', mode: 'grid', regex: '\/discover|\/explore' },
    { label: 'following', mode: 'grid', regex: '\/following' },
    { label: 'invitations', mode: 'list', regex: '\/invitations' },
    { label: 'onboarding', mode: 'grid', regex: '\/onboarding' },
    { label: 'notifications', mode: 'list', regex: '\/notifications' },
    { label: 'search', mode: 'grid', regex: '\/search|\/find' },
    { label: 'settings', mode: 'list', regex: '\/settings' },
    { label: 'starred', mode: 'list', regex: '\/starred' },
    { label: 'staff', mode: 'list', regex: '\/staff' },
    { label: 'posts', mode: 'list', regex: '\/[\\w\\-]+\/post\/.+' },
    { label: 'users/following', mode: 'grid', regex: '\/[\\w\\-]+\/following' },
    { label: 'users/followers', mode: 'grid', regex: '\/[\\w\\-]+\/followers' },
    { label: 'users/loves', mode: 'grid', regex: '\/[\\w\\-]+\/loves' },
    { label: 'users', mode: 'list', regex: '\/[\\w\\-]+' },
  ],
  newNotificationContent: false,
}

export function findLayoutMode(modes) {
  for (const mode of modes) {
    const regex = new RegExp(mode.regex)
    if (regex.test(location.pathname)) {
      return mode
    }
  }
  return modes[modes.length - 1]
}

const STREAMS_WHITELIST = [
  /discover/,
  /following/,
  /starred/,
]

export function gui(state = initialState, action = { type: '' }) {
  const newState = { ...state }
  let mode = null
  let pathname = null
  switch (action.type) {
    case BEACONS.LAST_DISCOVER_VERSION:
      return { ...state, lastDiscoverBeaconVersion: action.payload.version }
    case BEACONS.LAST_FOLLOWING_VERSION:
      return { ...state, lastFollowingBeaconVersion: action.payload.version }
    case BEACONS.LAST_STARRED_VERSION:
      return { ...state, lastStarredBeaconVersion: action.payload.version }
    case HEAD_FAILURE:
      return { ...state, newNotificationContent: false }
    case HEAD_SUCCESS:
      if (action.payload.serverResponse.status === 204) {
        return { ...state, newNotificationContent: true }
      }
      return state
    case AUTHENTICATION.LOGOUT:
      return { ...state, discoverKeyType: null }
    case LOAD_STREAM_SUCCESS:
      if (action.meta && /\/notifications/.test(action.meta.resultKey)) {
        return {
          ...state,
          newNotificationContent: false,
          lastNotificationCheck: new Date().toUTCString(),
        }
      }
      return state
    case PROFILE.DELETE_SUCCESS:
      return { ...initialState }
    case SET_LAYOUT_MODE:
      mode = findLayoutMode(newState.modes)
      if (mode.mode === action.payload.mode) return state
      mode.mode = action.payload.mode
      return newState
    case LOCATION_CHANGE:
      location = action.payload
      pathname = location.pathname

      if (_.some(STREAMS_WHITELIST, re => re.test(pathname))) {
        return { ...state, currentStream: pathname }
      }

      return { ...state }
    case GUI.NOTIFICATIONS_TAB:
      return { ...state, activeNotificationsTabType: action.payload.activeTabType }
    case GUI.SET_SCROLL:
      newState.history[action.payload.key] = { ...action.payload }
      return newState
    case GUI.SET_IS_OFFSET_LAYOUT:
      return { ...state, isOffsetLayout: action.payload.isOffsetLayout }
    case GUI.BIND_DISCOVER_KEY:
      return { ...newState, discoverKeyType: action.payload.type }
    default:
      return state
  }
}

// this is used for testing in StreamComponent_test
export function setLocation(loc) {
  location = loc
}

<|endoftext|>


<commit_before>'use strict';

var chalk = require('chalk');
var YAML = require('yamljs');

// task implementation
module.exports = function (grunt) {

	grunt.registerMultiTask('frontmatter', 'Extract YAML frontmatter from multiple files into one JSON', function () {

		var options = this.options({
			minify: false,
			width: 100,
			metadata: {},
		});

		var count = 0;

		this.files.forEach(function (f) {
			var validFiles = removeInvalidFiles(f);

			count += writeCompiledFile(f.dest, concatOutput(validFiles, options));
		});

		grunt.log.ok(count + ' files created.');

		function compileFrontmatter(body, options, filepath) {

			var lines = body.split('\n');
			var end = 0;
			if (lines[0] === '---') {
				end = end + 1;
			}
			while (lines[end] !== '---' && lines[end] !== lines[-1]) {
				end = end + 1;
			}

			var yaml = lines.slice(1, end).join('\n');
			var data = YAML.parse(yaml);

			var basename = filepath.split('/').slice(-1)[0].split('.')[0];
			var preview = lines.slice(end+1).join(' ').slice(0, options.width);

			data.basename = basename;
			data.preview = preview;

			return data;
		}

		function concatOutput(files, options) {
			var result;

			result = {};
			files.forEach(function(filepath) {
				var body = grunt.file.read(filepath);
				var data = compileFrontmatter(body, options, filepath);
				result[data.basename] = data;
			});

			if (options.minify) {
				result = JSON.stringify(result);
			} else {
				result = JSON.stringify(result, undefined, 2);
			}

			return result;
		}

		function removeInvalidFiles(files) {
			return files.src.filter(function(filepath) {
				if (!grunt.file.exists(filepath)) {
					grunt.log.warn('Source file "' + filepath + '" not found.');
					return false;
				} else {
					return true;
				}
			});
		}

		function writeCompiledFile(path, output) {
			if (writeFile(path, output)) {
				grunt.verbose.writeln('File ' + chalk.cyan(path) + ' created.');
				return 1;
			} else {
				return 0;
			}
		}

		function writeFile(path, output) {
			if (output.length < 1) {
				grunt.log.warn('Destination "' + path + '" not written because compiled files were empty.');
				return false;
			} else {
				grunt.file.write(path, output);
				return true;
			}
		}

	});

};<commit_msg>accept case when no front matter available<commit_after>'use strict';

var chalk = require('chalk');
var YAML = require('yamljs');

// task implementation
module.exports = function (grunt) {

	grunt.registerMultiTask('frontmatter', 'Extract YAML frontmatter from multiple files into one JSON', function () {

		var options = this.options({
			minify: false,
			width: 100,
			metadata: {},
		});

		var count = 0;

		this.files.forEach(function (f) {
			var validFiles = removeInvalidFiles(f);

			count += writeCompiledFile(f.dest, concatOutput(validFiles, options));
		});

		grunt.log.ok(count + ' files created.');

		function compileFrontmatter(body, options, filepath) {

			var lines = body.split('\n');
			var basename = filepath.split('/').slice(-1)[0].split('.')[0];

			var end = 0;
			if (lines[0] === '---') {
				end = 1;
				while (lines[end] !== '---' && lines[end] !== lines[-1]) {
					end++;
				}

				var preview = lines.slice(end+1).join(' ').slice(0, options.width);
				var yaml = lines.slice(1, end).join('\n');
				var data = YAML.parse(yaml);

				data.basename = basename;
				data.preview = preview;

				return data;
			} else {
				return {basename: basename, preview: body.slice(0, options.width)};
			}
		}

		function concatOutput(files, options) {
			var result;

			result = {};
			files.forEach(function(filepath) {
				var body = grunt.file.read(filepath);
				var data = compileFrontmatter(body, options, filepath);
				result[data.basename] = data;
			});

			if (options.minify) {
				result = JSON.stringify(result);
			} else {
				result = JSON.stringify(result, undefined, 2);
			}

			return result;
		}

		function removeInvalidFiles(files) {
			return files.src.filter(function(filepath) {
				if (!grunt.file.exists(filepath)) {
					grunt.log.warn('Source file "' + filepath + '" not found.');
					return false;
				} else {
					return true;
				}
			});
		}

		function writeCompiledFile(path, output) {
			if (writeFile(path, output)) {
				grunt.verbose.writeln('File ' + chalk.cyan(path) + ' created.');
				return 1;
			} else {
				return 0;
			}
		}

		function writeFile(path, output) {
			if (output.length < 1) {
				grunt.log.warn('Destination "' + path + '" not written because compiled files were empty.');
				return false;
			} else {
				grunt.file.write(path, output);
				return true;
			}
		}

	});

};<|endoftext|>


<commit_before>/**
 * Copyright (c) UNA, Inc - https://una.io
 * MIT License - https://opensource.org/licenses/MIT
 *
 * @defgroup    UnaCore UNA Core
 * @{
 */
function bx_editor_init(oEditor, oParams){
    hljs.configure({
        languages: ['javascript', 'php', 'html', 'css']
    });

    bEmptyToolbar = oParams.toolbar == false ? true : false;

    if (oParams.query_params == undefined)
        oParams.query_params = {};

    oParams.toolbar = {
        container: bEmptyToolbar ? [] : oParams.toolbar,
            handlers: {
            'embed': function(value) {
                var range = oEditor.getSelection();
                bx_prompt(_t('_sys_txt_quill_tooltip_embed_popup_header'), '', function(oPopup){
                    sLink = $(oPopup).find("input[type = 'text']").val()
                    $.getJSON(oParams.root_url + 'embed.php?', {a: 'get_link', l: sLink}, function(aData){
                        if (range) {
                            oEditor.clipboard.dangerouslyPasteHTML(range.index, "

", 'api');
                            oEditor.insertEmbed(range.index+2, 'embed-link', {source: sLink, inlinecode : aData.code}, 'api');
                        }
                        else{
                            oEditor.insertEmbed(0, 'embed-link', {source: sLink, inlinecode : aData.code}, 'api');
                        }

                        if ($(oParams.selector).next().next().find('.bx-embed-link a[href="' + aData.link + '"]').length > 0)
                            bx_embed_link($(oParams.selector).next().next().find('.bx-embed-link a[href="' + aData.link + '"]')[0]);
                        else
                            bx_embed_link();
                    });
                });
            },
            'link': function(value) {
                if (value) {
                    bx_prompt(_t('_sys_txt_quill_tooltip_link_popup_header'), '', function(oPopup){
                        oEditor.format('link', $(oPopup).find("input[type = 'text']").val());
                    });
                } else {
                    oEditor.format('link', false);
                }
            }
        }
    }
    $(oParams.selector).after("
" + $(oParams.selector).val() + "
" );
    $(oParams.selector).hide();

    $(oParams.selector).attr('object_editor', oParams.name);

    if (typeof bQuillRegistred === 'undefined' ) {

        var Embed = Quill.import('blots/embed');

        class MenthionLink extends Embed {
            static create(value) {
                let node = super.create(value);
                if (value.id && value.value){
                    node.setAttribute('href', value.id);
                    node.innerHTML = value.denotationChar + value.value;
                    node.setAttribute('title', value.value);
                    node.setAttribute('dchar', value.denotationChar);
                }
                return node;
            }

            format(name, value) {
                if (name === 'href' || name === 'title' || name === 'dchar') {
                    if (value) {
                        this.domNode.setAttribute(name, value);
                        if (name === 'dchar'){
                            this.domNode.innerHTML = value + this.domNode.getAttribute('title');
                        }
                    } else {
                        this.domNode.removeAttribute(name, value);
                    }
                }
                else {
                    super.format(name, value);
                }
            };

            static formats(node) {
                let format = {};
                if (node.hasAttribute('href')) {
                    format.href = node.getAttribute('href');
                }
                if (node.hasAttribute('title')) {
                    format.title = node.getAttribute('title');
                }
                if (node.hasAttribute('dchar')) {
                    format.dchar = node.getAttribute('dchar');
                }
                return format;
            }

        }
        MenthionLink.blotName = 'menthion-link';
        MenthionLink.className = 'bx-menthion-link';
        MenthionLink.tagName = 'a';
        Quill.register({
            'formats/menthion-link': MenthionLink
        });

        class EmbedCode extends Embed {
            static create(value) {
                let node = super.create(value);
                if (value.source && value.inlinecode){
                    node.setAttribute('source', value.source);
                    node.innerHTML = value.inlinecode;
                    return node;
                }
                return node;
            };

            format(name, value) {
                if (name === 'source') {
                    if (value) {
                        this.domNode.setAttribute(name, value);
                    } else {
                        this.domNode.removeAttribute(name, value);
                    }
                }
                else {
                    super.format(name, value);
                }
            };

            static formats(node) {
                let format = {};
                if (node.hasAttribute('source')) {
                  format.source = node.getAttribute('source');
                }
                return format;
            }
        }
        EmbedCode.className = 'bx-embed-link';
        EmbedCode.blotName = 'embed-link';
        EmbedCode.tagName = 'div';
        Quill.register({
            'formats/embed-link': EmbedCode
        });

        bQuillRegistred = true;

        var icons = Quill.import('ui/icons');
        icons['embed'] = '<svg class="fr-svg" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path class="ql-fill" d="M20.73889,15.45929a3.4768,3.4768,0,0,0-5.45965-.28662L9.5661,12.50861a3.49811,3.49811,0,0,0-.00873-1.01331l5.72174-2.66809a3.55783,3.55783,0,1,0-.84527-1.81262L8.70966,9.6839a3.50851,3.50851,0,1,0,.0111,4.63727l5.7132,2.66412a3.49763,3.49763,0,1,0,6.30493-1.526ZM18.00745,5.01056A1.49993,1.49993,0,1,1,16.39551,6.3894,1.49994,1.49994,0,0,1,18.00745,5.01056ZM5.99237,13.49536a1.49989,1.49989,0,1,1,1.61194-1.37878A1.49982,1.49982,0,0,1,5.99237,13.49536Zm11.78211,5.494a1.49993,1.49993,0,1,1,1.61193-1.37885A1.49987,1.49987,0,0,1,17.77448,18.98932Z"></path></svg>';
    }

    var oConfig = {
         theme: oParams.skin,
         modules: {
            syntax: true,
            imageResize: {},
            toolbar: oParams.toolbar,
            mention: {
                allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
                mentionDenotationChars: ["@", "#"],
                showDenotationChar: true,
                blotName: 'menthion-link',
                mentionContainerClass: 'bx-popup bx-popup-trans bx-popup-border bx-popup-color-bg',
                mentionListClass: 'ql-mention-list bx-menu-ver',
                listItemClass: 'bx-menu-item bx-def-color-bg-hl-hover',
                source: function (searchTerm, renderList, mentionChar) {
                  $.getJSON(oParams.root_url + 'searchExtended.php?action=get_mention', $.extend({}, {symbol: mentionChar, term: searchTerm}, oParams.query_params), function(data){
                      renderList(data, searchTerm);
                  });
                },
                renderItem: function(item, searchTerm){
                    item.id = item.url;
                    item.value = item.label;
                    return item.symbol + item.value;
                },
                onSelect: function(item, insertItem){
                    insertItem(item, false)
                }
            },
        }
    };

    oConfig.modules.imageUploader = {
        upload: file => {
            return new Promise((resolve, reject) => {
                if (typeof glOnInsertImageInEditor !== 'undefined' && glOnInsertImageInEditor instanceof Array && glOnInsertImageInEditor.length > 0) {
                    for (var i = 0; i < glOnInsertImageInEditor.length; i++) {
                        if (typeof glOnInsertImageInEditor[i] === "function") {
                            glOnInsertImageInEditor[i](file);
                        }
                    }
                    reject("External uploader");
                }
                else{
                    const formData = new FormData();
                    formData.append("file", file);
                    fetch(oParams.root_url + "storage.php?o=sys_images_editor&t=sys_images_editor&a=upload", {
                            method: "POST",
                            body: formData
                        }
                    )
                    .then(response => response.json())
                    .then(result => {
                        if ('undefined' != typeof(result.link))
                            resolve(result.link);
                        else
                            reject("Upload failed");
                    })
                    .catch(error => {
                        reject("Upload failed");
                    });
                }
            });
        }
    }

    oEditor = new Quill('#' + oParams.name, oConfig)
    $(oParams.selector).next().find('button.ql-bold').attr('title', _t('_sys_txt_quill_tooltip_bold'));
    $(oParams.selector).next().find('button.ql-italic').attr('title', _t('_sys_txt_quill_tooltip_italic'));
    $(oParams.selector).next().find('button.ql-underline').attr('title', _t('_sys_txt_quill_tooltip_underline'));
    $(oParams.selector).next().find('button.ql-clean').attr('title', _t('_sys_txt_quill_tooltip_clean'));
    $(oParams.selector).next().find('button.ql-list[value = "ordered"]').attr('title', _t('_sys_txt_quill_tooltip_list_ordered'));
    $(oParams.selector).next().find('button.ql-list[value = "bullet"]').attr('title', _t('_sys_txt_quill_tooltip_list_bullet'));
    $(oParams.selector).next().find('button.ql-indent[value = "-1"]').attr('title', _t('_sys_txt_quill_tooltip_indent_1'));
    $(oParams.selector).next().find('button.ql-indent[value = "+1"]').attr('title', _t('_sys_txt_quill_tooltip_indent_2'));
    $(oParams.selector).next().find('button.ql-blockquote').attr('title', _t('_sys_txt_quill_tooltip_blockquote'));
    $(oParams.selector).next().find('button.ql-direction').attr('title', _t('_sys_txt_quill_tooltip_direction'));
    $(oParams.selector).next().find('button.ql-script[value="sub"]').attr('title', _t('_sys_txt_quill_tooltip_script_sub'));
    $(oParams.selector).next().find('button.ql-script[value="super"]').attr('title', _t('_sys_txt_quill_tooltip_script_super'));
    $(oParams.selector).next().find('button.ql-link').attr('title', _t('_sys_txt_quill_tooltip_link'));
    $(oParams.selector).next().find('button.ql-image').attr('title', _t('_sys_txt_quill_tooltip_image'));
    $(oParams.selector).next().find('button.ql-code-block').attr('title', _t('_sys_txt_quill_tooltip_code_block'));
    $(oParams.selector).next().find('span.ql-color').attr('title', _t('_sys_txt_quill_tooltip_color'));
    $(oParams.selector).next().find('span.ql-background').attr('title', _t('_sys_txt_quill_tooltip_background'));
    $(oParams.selector).next().find('span.ql-align').attr('title', _t('_sys_txt_quill_tooltip_align'));
    $(oParams.selector).next().find('span.ql-header').attr('title', _t('_sys_txt_quill_tooltip_header'));

    if (bEmptyToolbar)
        $(oParams.selector).next().hide();

    oEditor.keyboard.addBinding({
        key: ' ',
        handler: function(range, context) {
            bx_editor_on_space_enter (oEditor, oParams.selector);
            return true;
        }
    });

    if (oParams.insert_as_plain_text){
        oEditor.clipboard.addMatcher (Node.ELEMENT_NODE, function (node, delta) {
            var plaintext = $ (node).text ();
            const Delta = Quill.import('delta')
            return new Delta().insert (plaintext);
        });
    }

    oEditor.keyboard.bindings[13].unshift({
        key: 13,
        handler: (range, context) => {
            bx_editor_on_space_enter (oEditor, oParams.selector)
            return true;
        }
    });

    oEditor.on('text-change', function(delta, oldDelta, source) {
        $(oParams.selector).val(oEditor.container.firstChild.innerHTML);
    });

    return oEditor
}

function bx_editor_insert_html (sEditorId, sImgId, sHtml)
{
    console.log(999);
    if ($('#' + sEditorId) &&  $('#' + sEditorId).attr('object_editor')){
        eval ('oEditor = ' + $('#' + sEditorId).attr('object_editor'));
        if (oEditor.getSelection())
            oEditor.clipboard.dangerouslyPasteHTML(oEditor.getSelection().index, sHtml, 'api');
        else
            oEditor.clipboard.dangerouslyPasteHTML(0, sHtml, 'api');
    }
}

function bx_editor_insert_img (sEditorId, sImgId, sImgUrl, sClasses) {

    if ('undefined' == typeof(sClasses))
        sClasses = '';

    bx_editor_insert_html(sEditorId, sImgId, '')
}

function bx_editor_on_space_enter (oEditor, sEditorId)
{
    if (typeof glBxEditorOnSpaceEnterTimer !== 'undefined')
        clearTimeout(glBxEditorOnSpaceEnterTimer);

    glBxEditorOnSpaceEnterTimer = setTimeout(function () {
        glBxEditorOnSpaceEnterTimer = undefined;
        if (typeof glOnSpaceEnterInEditor !== 'undefined' && glOnSpaceEnterInEditor instanceof Array) {
            for (var i = 0; i < glOnSpaceEnterInEditor.length; i++) {
                if (typeof glOnSpaceEnterInEditor[i] === "function") {;
                    glOnSpaceEnterInEditor[i](oEditor.container.firstChild.innerHTML, sEditorId);
                }
            }
        }
    }, 800);
}

function bx_editor_remove_img (aEditorIds, aMarkers)
{
    for (var i = 0; i < aEditorIds.length; i++) {
        var eEditor = $('#' + $('#' + aEditorIds[i]).attr('object_editor'));
        // delete images in html editor
        for (var k = 0; k < aMarkers.length; k++) {
            var jFiles = eEditor.find(aMarkers[k]);
            jFiles.each(function () {
                $(this).remove();
            });
        }
    }
}

/** @} */
<commit_msg>#3708 - Quill - insert as plain text<commit_after>/**
 * Copyright (c) UNA, Inc - https://una.io
 * MIT License - https://opensource.org/licenses/MIT
 *
 * @defgroup    UnaCore UNA Core
 * @{
 */
function bx_editor_init(oEditor, oParams){
    hljs.configure({
        languages: ['javascript', 'php', 'html', 'css']
    });

    bEmptyToolbar = oParams.toolbar == false ? true : false;

    if (oParams.query_params == undefined)
        oParams.query_params = {};

    oParams.toolbar = {
        container: bEmptyToolbar ? [] : oParams.toolbar,
            handlers: {
            'embed': function(value) {
                var range = oEditor.getSelection();
                bx_prompt(_t('_sys_txt_quill_tooltip_embed_popup_header'), '', function(oPopup){
                    sLink = $(oPopup).find("input[type = 'text']").val()
                    $.getJSON(oParams.root_url + 'embed.php?', {a: 'get_link', l: sLink}, function(aData){
                        if (range) {
                            oEditor.clipboard.dangerouslyPasteHTML(range.index, "

", 'api');
                            oEditor.insertEmbed(range.index+2, 'embed-link', {source: sLink, inlinecode : aData.code}, 'api');
                        }
                        else{
                            oEditor.insertEmbed(0, 'embed-link', {source: sLink, inlinecode : aData.code}, 'api');
                        }

                        if ($(oParams.selector).next().next().find('.bx-embed-link a[href="' + aData.link + '"]').length > 0)
                            bx_embed_link($(oParams.selector).next().next().find('.bx-embed-link a[href="' + aData.link + '"]')[0]);
                        else
                            bx_embed_link();
                    });
                });
            },
            'link': function(value) {
                if (value) {
                    bx_prompt(_t('_sys_txt_quill_tooltip_link_popup_header'), '', function(oPopup){
                        oEditor.format('link', $(oPopup).find("input[type = 'text']").val());
                    });
                } else {
                    oEditor.format('link', false);
                }
            }
        }
    }
    $(oParams.selector).after("
" + $(oParams.selector).val() + "
" );
    $(oParams.selector).hide();

    $(oParams.selector).attr('object_editor', oParams.name);

    if (typeof bQuillRegistred === 'undefined' ) {

        var Embed = Quill.import('blots/embed');

        class MenthionLink extends Embed {
            static create(value) {
                let node = super.create(value);
                if (value.id && value.value){
                    node.setAttribute('href', value.id);
                    node.innerHTML = value.denotationChar + value.value;
                    node.setAttribute('title', value.value);
                    node.setAttribute('dchar', value.denotationChar);
                }
                return node;
            }

            format(name, value) {
                if (name === 'href' || name === 'title' || name === 'dchar') {
                    if (value) {
                        this.domNode.setAttribute(name, value);
                        if (name === 'dchar'){
                            this.domNode.innerHTML = value + this.domNode.getAttribute('title');
                        }
                    } else {
                        this.domNode.removeAttribute(name, value);
                    }
                }
                else {
                    super.format(name, value);
                }
            };

            static formats(node) {
                let format = {};
                if (node.hasAttribute('href')) {
                    format.href = node.getAttribute('href');
                }
                if (node.hasAttribute('title')) {
                    format.title = node.getAttribute('title');
                }
                if (node.hasAttribute('dchar')) {
                    format.dchar = node.getAttribute('dchar');
                }
                return format;
            }

        }
        MenthionLink.blotName = 'menthion-link';
        MenthionLink.className = 'bx-menthion-link';
        MenthionLink.tagName = 'a';
        Quill.register({
            'formats/menthion-link': MenthionLink
        });

        class EmbedCode extends Embed {
            static create(value) {
                let node = super.create(value);
                if (value.source && value.inlinecode){
                    node.setAttribute('source', value.source);
                    node.innerHTML = value.inlinecode;
                    return node;
                }
                return node;
            };

            format(name, value) {
                if (name === 'source') {
                    if (value) {
                        this.domNode.setAttribute(name, value);
                    } else {
                        this.domNode.removeAttribute(name, value);
                    }
                }
                else {
                    super.format(name, value);
                }
            };

            static formats(node) {
                let format = {};
                if (node.hasAttribute('source')) {
                  format.source = node.getAttribute('source');
                }
                return format;
            }
        }
        EmbedCode.className = 'bx-embed-link';
        EmbedCode.blotName = 'embed-link';
        EmbedCode.tagName = 'div';
        Quill.register({
            'formats/embed-link': EmbedCode
        });

        bQuillRegistred = true;

        var icons = Quill.import('ui/icons');
        icons['embed'] = '<svg class="fr-svg" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path class="ql-fill" d="M20.73889,15.45929a3.4768,3.4768,0,0,0-5.45965-.28662L9.5661,12.50861a3.49811,3.49811,0,0,0-.00873-1.01331l5.72174-2.66809a3.55783,3.55783,0,1,0-.84527-1.81262L8.70966,9.6839a3.50851,3.50851,0,1,0,.0111,4.63727l5.7132,2.66412a3.49763,3.49763,0,1,0,6.30493-1.526ZM18.00745,5.01056A1.49993,1.49993,0,1,1,16.39551,6.3894,1.49994,1.49994,0,0,1,18.00745,5.01056ZM5.99237,13.49536a1.49989,1.49989,0,1,1,1.61194-1.37878A1.49982,1.49982,0,0,1,5.99237,13.49536Zm11.78211,5.494a1.49993,1.49993,0,1,1,1.61193-1.37885A1.49987,1.49987,0,0,1,17.77448,18.98932Z"></path></svg>';
    }

    var oConfig = {
         theme: oParams.skin,
         modules: {
            syntax: true,
            imageResize: {},
            toolbar: oParams.toolbar,
            mention: {
                allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
                mentionDenotationChars: ["@", "#"],
                showDenotationChar: true,
                blotName: 'menthion-link',
                mentionContainerClass: 'bx-popup bx-popup-trans bx-popup-border bx-popup-color-bg',
                mentionListClass: 'ql-mention-list bx-menu-ver',
                listItemClass: 'bx-menu-item bx-def-color-bg-hl-hover',
                source: function (searchTerm, renderList, mentionChar) {
                  $.getJSON(oParams.root_url + 'searchExtended.php?action=get_mention', $.extend({}, {symbol: mentionChar, term: searchTerm}, oParams.query_params), function(data){
                      renderList(data, searchTerm);
                  });
                },
                renderItem: function(item, searchTerm){
                    item.id = item.url;
                    item.value = item.label;
                    return item.symbol + item.value;
                },
                onSelect: function(item, insertItem){
                    insertItem(item, false)
                }
            },
        }
    };

    oConfig.modules.imageUploader = {
        upload: file => {
            return new Promise((resolve, reject) => {
                if (typeof glOnInsertImageInEditor !== 'undefined' && glOnInsertImageInEditor instanceof Array && glOnInsertImageInEditor.length > 0) {
                    for (var i = 0; i < glOnInsertImageInEditor.length; i++) {
                        if (typeof glOnInsertImageInEditor[i] === "function") {
                            glOnInsertImageInEditor[i](file);
                        }
                    }
                    reject("External uploader");
                }
                else{
                    const formData = new FormData();
                    formData.append("file", file);
                    fetch(oParams.root_url + "storage.php?o=sys_images_editor&t=sys_images_editor&a=upload", {
                            method: "POST",
                            body: formData
                        }
                    )
                    .then(response => response.json())
                    .then(result => {
                        if ('undefined' != typeof(result.link))
                            resolve(result.link);
                        else
                            reject("Upload failed");
                    })
                    .catch(error => {
                        reject("Upload failed");
                    });
                }
            });
        }
    }

    oEditor = new Quill('#' + oParams.name, oConfig)
    $(oParams.selector).next().find('button.ql-bold').attr('title', _t('_sys_txt_quill_tooltip_bold'));
    $(oParams.selector).next().find('button.ql-italic').attr('title', _t('_sys_txt_quill_tooltip_italic'));
    $(oParams.selector).next().find('button.ql-underline').attr('title', _t('_sys_txt_quill_tooltip_underline'));
    $(oParams.selector).next().find('button.ql-clean').attr('title', _t('_sys_txt_quill_tooltip_clean'));
    $(oParams.selector).next().find('button.ql-list[value = "ordered"]').attr('title', _t('_sys_txt_quill_tooltip_list_ordered'));
    $(oParams.selector).next().find('button.ql-list[value = "bullet"]').attr('title', _t('_sys_txt_quill_tooltip_list_bullet'));
    $(oParams.selector).next().find('button.ql-indent[value = "-1"]').attr('title', _t('_sys_txt_quill_tooltip_indent_1'));
    $(oParams.selector).next().find('button.ql-indent[value = "+1"]').attr('title', _t('_sys_txt_quill_tooltip_indent_2'));
    $(oParams.selector).next().find('button.ql-blockquote').attr('title', _t('_sys_txt_quill_tooltip_blockquote'));
    $(oParams.selector).next().find('button.ql-direction').attr('title', _t('_sys_txt_quill_tooltip_direction'));
    $(oParams.selector).next().find('button.ql-script[value="sub"]').attr('title', _t('_sys_txt_quill_tooltip_script_sub'));
    $(oParams.selector).next().find('button.ql-script[value="super"]').attr('title', _t('_sys_txt_quill_tooltip_script_super'));
    $(oParams.selector).next().find('button.ql-link').attr('title', _t('_sys_txt_quill_tooltip_link'));
    $(oParams.selector).next().find('button.ql-image').attr('title', _t('_sys_txt_quill_tooltip_image'));
    $(oParams.selector).next().find('button.ql-code-block').attr('title', _t('_sys_txt_quill_tooltip_code_block'));
    $(oParams.selector).next().find('span.ql-color').attr('title', _t('_sys_txt_quill_tooltip_color'));
    $(oParams.selector).next().find('span.ql-background').attr('title', _t('_sys_txt_quill_tooltip_background'));
    $(oParams.selector).next().find('span.ql-align').attr('title', _t('_sys_txt_quill_tooltip_align'));
    $(oParams.selector).next().find('span.ql-header').attr('title', _t('_sys_txt_quill_tooltip_header'));

    if (bEmptyToolbar)
        $(oParams.selector).next().hide();

    oEditor.keyboard.addBinding({
        key: ' ',
        handler: function(range, context) {
            bx_editor_on_space_enter (oEditor, oParams.selector);
            return true;
        }
    });

    if (oParams.insert_as_plain_text){
        oEditor.clipboard.addMatcher (Node.ELEMENT_NODE, function (node, delta) {
            var plaintext = $ (node).text ();
            const Delta = Quill.import('delta')
            return new Delta().insert (plaintext);
        });
    }

    oEditor.keyboard.bindings[13].unshift({
        key: 13,
        handler: (range, context) => {
            bx_editor_on_space_enter (oEditor, oParams.selector)
            return true;
        }
    });

    oEditor.on('text-change', function(delta, oldDelta, source) {
        $(oParams.selector).val(oEditor.container.firstChild.innerHTML);
    });

    return oEditor
}

function bx_editor_insert_html (sEditorId, sImgId, sHtml)
{
    if ($('#' + sEditorId) &&  $('#' + sEditorId).attr('object_editor')){
        eval ('oEditor = ' + $('#' + sEditorId).attr('object_editor'));
        if (oEditor.getSelection())
            oEditor.clipboard.dangerouslyPasteHTML(oEditor.getSelection().index, sHtml, 'api');
        else
            oEditor.clipboard.dangerouslyPasteHTML(0, sHtml, 'api');
    }
}

function bx_editor_insert_img (sEditorId, sImgId, sImgUrl, sClasses) {

    if ('undefined' == typeof(sClasses))
        sClasses = '';

    bx_editor_insert_html(sEditorId, sImgId, '')
}

function bx_editor_on_space_enter (oEditor, sEditorId)
{
    if (typeof glBxEditorOnSpaceEnterTimer !== 'undefined')
        clearTimeout(glBxEditorOnSpaceEnterTimer);

    glBxEditorOnSpaceEnterTimer = setTimeout(function () {
        glBxEditorOnSpaceEnterTimer = undefined;
        if (typeof glOnSpaceEnterInEditor !== 'undefined' && glOnSpaceEnterInEditor instanceof Array) {
            for (var i = 0; i < glOnSpaceEnterInEditor.length; i++) {
                if (typeof glOnSpaceEnterInEditor[i] === "function") {;
                    glOnSpaceEnterInEditor[i](oEditor.container.firstChild.innerHTML, sEditorId);
                }
            }
        }
    }, 800);
}

function bx_editor_remove_img (aEditorIds, aMarkers)
{
    for (var i = 0; i < aEditorIds.length; i++) {
        var eEditor = $('#' + $('#' + aEditorIds[i]).attr('object_editor'));
        // delete images in html editor
        for (var k = 0; k < aMarkers.length; k++) {
            var jFiles = eEditor.find(aMarkers[k]);
            jFiles.each(function () {
                $(this).remove();
            });
        }
    }
}

/** @} */
<|endoftext|>


<commit_before>Tasks = new Mongo.Collection("tasks");
Meteor.subscribe('tasks');

Template.taskList.helpers({
  tasks: function() {
    var query = Session.get('task_query') || '';
    return searchTasks(query);
  }
});

Template.search.events({
  "keyup #search": _.throttle(function(event) {
    var text = $(event.target).val().trim();
    Session.set('task_query', text);
  }, 200)
});

Template.stats.helpers({
  ntasks: function() {
    return Session.get('n_tasks');
  },
  nprojects: function() {
    return Session.get('n_projects');
  },
  weekdue: function() {
    return Session.get('tasks_weekdue');
  },
  overdue: function() {
    return Session.get('tasks_overdue');
  }
});

Template.sortAndFilter.events({
  'change #sort-radiogroup input': function(event) {
    var sort = $('#sort-radiogroup input[name=sort]:checked').val();
    console.log('clicky', sort);
    Session.set('task_sort', sort.replace('sort-', ''));
    $('#sort-dropdown').mouseout();
  },
  'change #filter-show-checked': function(event) {
    var show = $('#filter-show-checked').is(":checked");
    Session.set('task_show_complete', show);
    console.log(show);
  }
});

Template.actionButton.onRendered(function() {
  this.$('.modal-trigger').leanModal({
    in_duration: 200,
    out_duration: 200,
    ready: function() {
      $('input[name="title"]').delay(205).focus();
    }
  });
});

Template.actionButton.events({
  "click #add-task-btn": function(event) {
    $('#add-task-btn').closeFAB();
  }
});

Template.addTaskFrequencyModal.onRendered(function() {
  this.$('select').material_select();
});

Template.taskPopout.events({
  "escaped-click .task-complete": function(event) {
    event.stopPropagation();

    Tasks.update(this._id, {
      '$set': {
        'completed': !this.completed
      }
    });
    this.completed = !this.completed;
  },
  "escaped-click .task-delete": function(event) {
    event.stopPropagation();

    Tasks.remove(this._id);
  },
  "escaped-click .task-guilt": function(event) {
    event.stopPropagation();

    Tasks.update(this._id, { $inc : { "guilt" : 1 } });
  },
  "escaped-click .task-edit": function(event) {
    event.stopPropagation();
    event.preventDefault();

    var containerid = this._id + '_content';

    var container = $('#' + containerid);

    if (container.hasClass('with-editor')) {

      // get contents of editor, then destroy it
      var textarea = container.parent().find('textarea');
      var content = $.trim(textarea.val());
      textarea.remove();
      container.find('iframe').remove();

      // update the task popout contents and resize
      container.html(Markdown(content));
      container.removeClass('with-editor');
      container.css({ height: 'auto' });

      Tasks.update(this._id, { '$set': { 'content': content }});
      this.content = content;

    } else {
      var opts = {
        basePath: '/epic',
        theme: {
          base: '/base.css',
          editor: '/editor.css'
        },
        preloadText: this.content,
        autogrow: true,
        focusOnLoad: true,
        button: false
      }
      Epic.create(containerid, opts);
      container.find('iframe').css({ height: 'auto' });
      $('#epicarea' + containerid).hide();
      container.addClass('with-editor');
    }

    return false;
  }
});

Template.taskPopout.helpers({
  hasProject: function() {
    return !!this.project && this.project.length > 0;
  },
  overdue: function() {
    return !!this.due_at && !this.completed &&
           (+(new Date(this.due_at)) <= +(new Date()));
  },
  overdueBy: function() {
    var due_at = moment(new Date(this.due_at));
    var now = moment(new Date());
    var daysover = now.diff(due_at, 'days') + 1;
    return daysover + ' days overdue';
  }
});

Template.taskPopout.onRendered(function() {
  // initialise collapsible
  $('.collapsible').collapsible()
  // initialise tooltips
  $('.tooltipped').tooltip({
    delay: 0
  });

  // hackety-hack - don't collapse the task if user clicks
  // on the buttons
  var buttons = this.$('.task-btns > a');

  buttons.on('click.collapse', function(e) {
    e.stopPropagation();
    $(e.target).trigger('escaped-click');
  });

  buttons.mouseover(function() {
    $(this).removeClass('text-lighten-3');
  });

  buttons.mouseout(function() {
    $(this).addClass('text-lighten-3');
  });

  this.$('.task-content p').addClass('flow-text');

});

Template.body.events({
  "submit #add-form": function(event) {
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    var title = event.target.title.value;
    var project = event.target.project.value;
    var content = event.target.content.value;
    var duedate = event.target.duedate.value;
    var frequency = event.target.frequency.value;

    if (duedate.length = 0) {
      duedate = undefined;
    }

    // Insert a task into the collection
    Tasks.insert({
      title: title,
      project: project,
      content: content,
      guilt: 0,
      completed: false,
      due_at: duedate,
      frequency: frequency,
      created_at: new Date() // current time
    });

    // Clear form
    event.target.reset();
    $('#add-task-modal').closeModal();
  },
  "focus #add-task-frequency": function(event) {
    $('#add-task-frequency-modal').openModal();
  },
  "click #add-task-frequency-modal-choose": function(event) {
    console.log(event);
    // Prevent default browser form submit
    event.preventDefault();

    // Get values
    var form = $('#add-task-frequency-form')[0];
    var number = form.number.value;
    var timeperiod = form.timeperiod.value;

    $('#add-task-frequency').val(number + " times a " + timeperiod);

    $('#add-task-frequency-form').reset();
  },
  "click #add-task-frequency-modal-clear": function(event) {
    $('#add-task-frequency').value = "";
  }
});

Template.body.onRendered(function() {
  // default search settings
  Session.set('task_query', '');
  Session.set('task_sort', 'created-desc');
  Session.set('task_show_complete', false);

  $('.datepicker').pickadate({
    selectMonths: true,
    selectYears: 10,
    min: new Date()
  });
});

Template.addTaskModal.onRendered(function() {
  AutoCompletion.init("#add-task-project");
});

Template.addTaskModal.events = {
  'keyup #add-task-project': function () {
    AutoCompletion.autocomplete({
      element: '#add-task-project',
      collection: Tasks,
      field: 'project',
      limit: 10
    }, _.uniq);
  }
}
<commit_msg>Fix materialize collapsibles after version update<commit_after>Tasks = new Mongo.Collection("tasks");
Meteor.subscribe('tasks');

Template.taskList.helpers({
  tasks: function() {
    var query = Session.get('task_query') || '';
    return searchTasks(query);
  }
});

Template.search.events({
  "keyup #search": _.throttle(function(event) {
    var text = $(event.target).val().trim();
    Session.set('task_query', text);
  }, 200)
});

Template.stats.helpers({
  ntasks: function() {
    return Session.get('n_tasks');
  },
  nprojects: function() {
    return Session.get('n_projects');
  },
  weekdue: function() {
    return Session.get('tasks_weekdue');
  },
  overdue: function() {
    return Session.get('tasks_overdue');
  }
});

Template.sortAndFilter.events({
  'change #sort-radiogroup input': function(event) {
    var sort = $('#sort-radiogroup input[name=sort]:checked').val();
    console.log('clicky', sort);
    Session.set('task_sort', sort.replace('sort-', ''));
    $('#sort-dropdown').mouseout();
  },
  'change #filter-show-checked': function(event) {
    var show = $('#filter-show-checked').is(":checked");
    Session.set('task_show_complete', show);
    console.log(show);
  }
});

Template.actionButton.onRendered(function() {
  this.$('.modal-trigger').leanModal({
    in_duration: 200,
    out_duration: 200,
    ready: function() {
      $('input[name="title"]').delay(205).focus();
    }
  });
});

Template.actionButton.events({
  "click #add-task-btn": function(event) {
    $('#add-task-btn').closeFAB();
  }
});

Template.addTaskFrequencyModal.onRendered(function() {
  this.$('select').material_select();
});

Template.taskPopout.events({
  "escaped-click .task-complete": function(event) {
    event.stopPropagation();

    Tasks.update(this._id, {
      '$set': {
        'completed': !this.completed
      }
    });
    this.completed = !this.completed;
  },
  "escaped-click .task-delete": function(event) {
    event.stopPropagation();

    Tasks.remove(this._id);
  },
  "escaped-click .task-guilt": function(event) {
    event.stopPropagation();

    Tasks.update(this._id, { $inc : { "guilt" : 1 } });
  },
  "escaped-click .task-edit": function(event) {
    event.stopPropagation();
    event.preventDefault();

    var containerid = this._id + '_content';

    var container = $('#' + containerid);

    if (container.hasClass('with-editor')) {

      // get contents of editor, then destroy it
      var textarea = container.parent().find('textarea');
      var content = $.trim(textarea.val());
      textarea.remove();
      container.find('iframe').remove();

      // update the task popout contents and resize
      container.html(Markdown(content));
      container.removeClass('with-editor');
      container.css({ height: 'auto' });

      Tasks.update(this._id, { '$set': { 'content': content }});
      this.content = content;

    } else {
      var opts = {
        basePath: '/epic',
        theme: {
          base: '/base.css',
          editor: '/editor.css'
        },
        preloadText: this.content,
        autogrow: true,
        focusOnLoad: true,
        button: false
      }
      Epic.create(containerid, opts);
      container.find('iframe').css({ height: 'auto' });
      $('#epicarea' + containerid).hide();
      container.addClass('with-editor');
    }

    return false;
  }
});

Template.taskPopout.helpers({
  hasProject: function() {
    return !!this.project && this.project.length > 0;
  },
  overdue: function() {
    return !!this.due_at && !this.completed &&
           (+(new Date(this.due_at)) <= +(new Date()));
  },
  overdueBy: function() {
    var due_at = moment(new Date(this.due_at));
    var now = moment(new Date());
    var daysover = now.diff(due_at, 'days') + 1;
    return daysover + ' days overdue';
  }
});

Template.taskPopout.onRendered(function() {

  // initialise tooltips
  $('.tooltipped').tooltip({
    delay: 0
  });

  // hackety-hack - don't collapse the task if user clicks
  // on the buttons
  var buttons = this.$('.task-btns > a');

  buttons.on('click.collapse', function(e) {
    e.stopPropagation();
    $(e.target).trigger('escaped-click');
  });

  buttons.mouseover(function() {
    $(this).removeClass('text-lighten-3');
  });

  buttons.mouseout(function() {
    $(this).addClass('text-lighten-3');
  });

  this.$('.task-content p').addClass('flow-text');

});

Template.body.events({
  "submit #add-form": function(event) {
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    var title = event.target.title.value;
    var project = event.target.project.value;
    var content = event.target.content.value;
    var duedate = event.target.duedate.value;
    var frequency = event.target.frequency.value;

    if (duedate.length = 0) {
      duedate = undefined;
    }

    // Insert a task into the collection
    Tasks.insert({
      title: title,
      project: project,
      content: content,
      guilt: 0,
      completed: false,
      due_at: duedate,
      frequency: frequency,
      created_at: new Date() // current time
    });

    // Clear form
    event.target.reset();
    $('#add-task-modal').closeModal();
  },
  "focus #add-task-frequency": function(event) {
    $('#add-task-frequency-modal').openModal();
  },
  "click #add-task-frequency-modal-choose": function(event) {
    console.log(event);
    // Prevent default browser form submit
    event.preventDefault();

    // Get values
    var form = $('#add-task-frequency-form')[0];
    var number = form.number.value;
    var timeperiod = form.timeperiod.value;

    $('#add-task-frequency').val(number + " times a " + timeperiod);

    $('#add-task-frequency-form').reset();
  },
  "click #add-task-frequency-modal-clear": function(event) {
    $('#add-task-frequency').value = "";
  }
});

Template.body.onRendered(function() {
  // default search settings
  Session.set('task_query', '');
  Session.set('task_sort', 'created-desc');
  Session.set('task_show_complete', false);

  $('.datepicker').pickadate({
    selectMonths: true,
    selectYears: 10,
    min: new Date()
  });

  // initialise collapsible
  $('.collapsible').collapsible({
    accordion: false
  })

});

Template.addTaskModal.onRendered(function() {
  AutoCompletion.init("#add-task-project");
});

Template.addTaskModal.events = {
  'keyup #add-task-project': function () {
    AutoCompletion.autocomplete({
      element: '#add-task-project',
      collection: Tasks,
      field: 'project',
      limit: 10
    }, _.uniq);
  }
}
<|endoftext|>


<commit_before>
(function( $ ) {
	jsPsych.xab = (function(){

		var plugin = {}

		plugin.create = function(params)
		{
			//xab_stims = shuffle(xab_stims);
			xab_stims = params["stimuli"];
			trials = new Array(xab_stims.length);
			for(var i = 0; i < trials.length; i++)
			{
				trials[i] = {};
				trials[i]["type"] = "xab";
				trials[i]["a_path"] = xab_stims[i][0];
				trials[i]["b_path"] = xab_stims[i][1];
				trials[i]["timing"] = params["timing"];
				trials[i]["data"] = params["data"][i] || params["data"] || undefined;
				trials[i]["left_key"] = params["left_key"] || 81; // defaults to 'q'
				trials[i]["right_key"] = params["right_key"] || 80; // defaults to 'p'
			}
			return trials;
		}

		plugin.trial = function($this, block, trial, part)
		{
			switch(part){
				case 1:
					p1_time = (new Date()).getTime();
					$this.append($('<img>', {
						"src": trial.a_path,
						"class": 'xab'
					}));
					setTimeout(function(){plugin.trial($this, block, trial, part + 1)}, trial.timing[0]);
					break;
				case 2:
					p2_time = (new Date()).getTime();
					$('.xab').remove();
					setTimeout(function(){plugin.trial($this, block, trial, part + 1)}, trial.timing[1]);
					break;
				case 3:
					p3_time = (new Date()).getTime();
					startTime = (new Date()).getTime();
					var images = [trial.a_path, trial.b_path];
					var target_left = (Math.floor(Math.random()*2)==0); // binary true/false choice
					if(!target_left){
						images = [trial.b_path, trial.a_path];
					}

					// show the images
					$this.append($('<img>', {
						"src": images[0],
						"class": 'xab'
					}));
					$this.append($('<img>', {
						"src": images[1],
						"class": 'xab'
					}));

					var resp_func = function(e) {
						var flag = false;
						var correct = false;
						if(e.which== trial.left_key) // 'p' key
						{
							flag = true;
							if(!target_left) { correct = true; }
						} else if(e.which== trial.right_key) // 'q' key
						{
							flag = true;
							if(target_left){ correct = true; }
						}
						if(flag)
						{
							endTime = (new Date()).getTime();
							rt = (endTime-startTime);
							stim1_time = (p2_time-p1_time);
							isi_time = (p3_time-p2_time);
							var trial_data = {"rt": rt, "correct": correct, "a_path": trial.a_path, "b_path": trial.b_path, "key_press": e.which, "key_press": e.which, "stim1_time": stim1_time, "isi_time":isi_time}
							block.data[block.trial_idx] = $.extend({},trial_data,trial.data);
							$(document).unbind('keyup',resp_func);
							$('.xab').remove();
							setTimeout(function(){block.next();}, trial.timing[2]);
						}
					}
					$(document).keyup(resp_func);
					//TODO: CHECK IF IMAGE SHOULD DISAPPEAR
					//based on timings
					break;
			}
		}

		return plugin;
	})();
})(jQuery);<commit_msg>added prompt option to XAB<commit_after>
(function( $ ) {
	jsPsych.xab = (function(){

		var plugin = {}

		plugin.create = function(params)
		{
			//xab_stims = shuffle(xab_stims);
			xab_stims = params["stimuli"];
			trials = new Array(xab_stims.length);
			for(var i = 0; i < trials.length; i++)
			{
				trials[i] = {};
				trials[i]["type"] = "xab";
				trials[i]["a_path"] = xab_stims[i][0];
				trials[i]["b_path"] = xab_stims[i][1];
				trials[i]["timing"] = params["timing"];
				trials[i]["left_key"] = params["left_key"] || 81; // defaults to 'q'
				trials[i]["right_key"] = params["right_key"] || 80; // defaults to 'p'
				if(params["prompt"]) {
					trials[i]["prompt"] = params["prompt"];
				}
				if(params["data"]){
					trials[i]["data"] = params["data"][i];
				}
			}
			return trials;
		}

		plugin.trial = function($this, block, trial, part)
		{
			switch(part){
				case 1:
					p1_time = (new Date()).getTime();
					$this.append($('<img>', {
						"src": trial.a_path,
						"class": 'xab'
					}));
					setTimeout(function(){plugin.trial($this, block, trial, part + 1)}, trial.timing[0]);
					break;
				case 2:
					p2_time = (new Date()).getTime();
					$('.xab').remove();
					setTimeout(function(){plugin.trial($this, block, trial, part + 1)}, trial.timing[1]);
					break;
				case 3:
					p3_time = (new Date()).getTime();
					startTime = (new Date()).getTime();
					var images = [trial.a_path, trial.b_path];
					var target_left = (Math.floor(Math.random()*2)==0); // binary true/false choice
					if(!target_left){
						images = [trial.b_path, trial.a_path];
					}

					// show the images
					$this.append($('<img>', {
						"src": images[0],
						"class": 'xab'
					}));
					$this.append($('<img>', {
						"src": images[1],
						"class": 'xab'
					}));

					if(trial.prompt)
					{
						$this.append(trial.prompt);
					}

					var resp_func = function(e) {
						var flag = false;
						var correct = false;
						if(e.which== trial.left_key) // 'p' key
						{
							flag = true;
							if(!target_left) { correct = true; }
						} else if(e.which== trial.right_key) // 'q' key
						{
							flag = true;
							if(target_left){ correct = true; }
						}
						if(flag)
						{
							endTime = (new Date()).getTime();
							rt = (endTime-startTime);
							stim1_time = (p2_time-p1_time);
							isi_time = (p3_time-p2_time);
							var trial_data = {"rt": rt, "correct": correct, "a_path": trial.a_path, "b_path": trial.b_path, "key_press": e.which, "key_press": e.which, "stim1_time": stim1_time, "isi_time":isi_time}
							block.data[block.trial_idx] = $.extend({},trial_data,trial.data);
							$(document).unbind('keyup',resp_func);
							$('.xab').remove();
							setTimeout(function(){block.next();}, trial.timing[2]);
						}
					}
					$(document).keyup(resp_func);
					//TODO: CHECK IF IMAGE SHOULD DISAPPEAR
					//based on timings
					break;
			}
		}

		return plugin;
	})();
})(jQuery);<|endoftext|>