<commit_before>"use strict";

var changing = bestGlobals.changing;

myOwn.messages=changing(myOwn.messages, {
    loading: "loading",
    Filter : "Filter",
    Delete : "Delete",
});

myOwn.es=changing(myOwn.es, {
    loading: "cargando",
    Filter : "Filtrar",
    Delete : "Eliminar",
});

var escapeRegExp = bestGlobals.escapeRegExp;

myOwn.firstDisplayCount = 20;
myOwn.displayCountBreaks = [100,250,1000];
myOwn.displayCountBreaks = [50,100,500];
myOwn.comparator={
    '=':function(valueToCheck,condition){return valueToCheck == condition;},
    '~':function(valueToCheck,condition){return RegExp(escapeRegExp(condition),'i').test(valueToCheck);},
    '/R/i':function(valueToCheck,condition){return RegExp(condition,'i').test(valueToCheck);},
    '\u2205':function(valueToCheck,condition){return valueToCheck == null;},//\u2205 = conjunto vacío
    '>':function(valueToCheck,condition){return (valueToCheck>condition)},
    '>=':function(valueToCheck,condition){return (valueToCheck>=condition)},
    '<':function(valueToCheck,condition){return (valueToCheck<condition)},
    '<=':function(valueToCheck,condition){return (valueToCheck<=condition)},
    'not-an-operator':function(valueToCheck,condition){ return 'Operator does not exist'}
}
myOwn.tableGrid = function tableGrid(layout, tableName){
    var my = this;
    var inputColspan = 1;
    var modes = {
        saveByField: true
    };
    layout.textContent = my.messages.loading+'...';
    var grid={};
    var createRowElements;
    var createRowFilter;
    var footInfoElement;
    var structureRequest = my.ajax.table.structure({
        table:tableName,
    }).then(function(tableDef){
        grid.def=tableDef;
        grid.view={
            sortColumns:tableDef.sortColumns||[]
        }
        var buttonInsert;
        var buttonCreateFilter;
        var buttonDestroyFilter;
        var getSaveModeImgSrc=function(){ return modes.saveByField?'img/tables-update-by-field.png':'img/tables-update-by-row.png';};
        var buttonSaveModeImg=html.img({src:getSaveModeImgSrc()}).create();
        var buttonSaveMode;
        if(tableDef.allow.update){
            buttonSaveMode=html.button({class:'table-button'}, [buttonSaveModeImg]).create();
            buttonSaveMode.addEventListener('click',function(){
                modes.saveByField = !modes.saveByField;
                buttonSaveModeImg.src=getSaveModeImgSrc();
            });
        }
        if(tableDef.allow.insert){
            buttonInsert=html.button({class:'table-button'}, [html.img({src:'img/insert.png'})]).create();
            buttonInsert.addEventListener('click', function(){
                grid.createRowElements(0);
            });
        }
        if(tableDef.allow.filter){
            buttonCreateFilter=html.button({class:'table-button', 'when-filter':'no'}, [html.img({src:'img/filter.png'})]).create();
            buttonCreateFilter.addEventListener('click', function(){
                grid.createRowFilter(0);
            });
            buttonDestroyFilter=html.button({class:'table-button', 'when-filter':'yes'}, [html.img({src:'img/destroy-filter.png'})]).create();
            buttonDestroyFilter.addEventListener('click', function(){
                grid.destroyRowFilter(0);
            });
        }
        var columnsHeadElements = tableDef.fields.map(function(fieldDef){
            var tr=html.th({colspan:inputColspan},fieldDef.title).create();
            tr.addEventListener('click',function(){
                var currentOrder=grid.view.sortColumns.length && grid.view.sortColumns[0].column==fieldDef.name?grid.view.sortColumns[0].order:null;
                grid.view.sortColumns=grid.view.sortColumns.filter(function(sortColumn){
                    return sortColumn.column != fieldDef.name;
                })
                grid.view.sortColumns.unshift({column:fieldDef.name, order:currentOrder?-currentOrder:1})
                grid.displayBody(tr.info)
            });
            return tr;
        });
        footInfoElement = html.td({colspan:columnsHeadElements.length*inputColspan, "is-processing":"1"}).create();
        [
            {name:'displayFrom', value:'0'},
            {name:'elipsis', value:' ... '},
            {name:'displayTo', value:'?'},
            {name:'rowCount', value:''}
        ].forEach(function(info){
            footInfoElement[info.name] = html.span(info.value).create();
            footInfoElement.appendChild(footInfoElement[info.name]);
        });
        grid.element = html.table({"class":"my-grid", "my-table": tableName},[
            html.caption(tableDef.title),
            html.thead([
                html.tr([html.th([buttonInsert,/*buttonSaveMode,*/buttonCreateFilter,buttonDestroyFilter])].concat(columnsHeadElements))
            ]),
            html.tbody(),
            html.tfoot([
                html.tr([html.th(),footInfoElement])
            ])
        ]).create();
        layout.innerHTML='';
        layout.appendChild(grid.element);
    });
    var displayGrid = function displayGrid(rows){
        var tbody = grid.element.tBodies[0];
        var updateRowData = function updateRowData(tr, updatedRow){
            var forInsert = false; // not define how to detect
            tr.info.row = updatedRow;
            tr.info.status = 'retrieved';
            tr.info.primaryKeyValues = grid.def.primaryKey.map(function(fieldName){
                return tr.info.row[fieldName];
            });
            grid.def.fields.forEach(function(fieldDef){
                var td = tr.info.rowControls[fieldDef.name];
                td.contentEditable=grid.def.allow.update && (forInsert?fieldDef.allow.insert:fieldDef.allow.update);
                td.setTypedValue(tr.info.row[fieldDef.name]);
            });
        }
        var saveRow = function(tr, opts){
            var changeIoStatus = function changeIoStatus(newStatus, title){
                fieldNames.forEach(function(name){
                    var td=tr.info.rowControls[name];
                    td.setAttribute('io-status', newStatus);
                    if(title){
                        //td.title=err.message;
                    }
                });
            }
            var fieldNames=Object.keys(tr.info.rowPendingForUpdate);
            changeIoStatus('updating');
            my.ajax.table['save-record']({
                table:tableName,
                primaryKeyValues:tr.info.primaryKeyValues,
                newRow:tr.info.rowPendingForUpdate,
                status:tr.info.status
            },opts).then(function(updatedRow){
                my.adaptData(grid.def,[updatedRow]);
                updateRowData(tr, updatedRow);
                tr.info.rowPendingForUpdate = {};
                changeIoStatus('temporal-ok');
                setTimeout(function(){
                    changeIoStatus('ok');
                },3000);
            }).catch(function(err){
                changeIoStatus('error',err.message);
            });
        }
        grid.createRowElements = function createRowElements(iRow, row){
            var forInsert = iRow>=0;
            var tr = tbody.insertRow(iRow);
            tr.info = {
                rowControls:{},
                row: {},
                rowPendingForUpdate:{},
                primaryKeyValues:false,
                status: 'new'
            };
            var thActions=html.th().create();
            tr.appendChild(thActions);
            var actionNamesList = ['insert','delete'].concat(grid.def.actionNamesList);
            actionNamesList.forEach(function(actionName){
                var actionDef = my.tableAction[actionName];
                if(grid.def.allow[actionName]){
                    var buttonAction=html.button({class:'table-button'}, [
                        html.img({src:actionDef.img})
                    ]).create();
                    thActions.appendChild(buttonAction);
                    buttonAction.addEventListener('click', function(){
                        actionDef.actionRow(my,grid,tr);
                    });
                }
            });
            grid.def.fields.forEach(function(fieldDef){
                var td = html.td({colspan:inputColspan}).create();
                TypedControls.adaptElement(td, fieldDef);
                tr.info.rowControls[fieldDef.name] = td;
                td.contentEditable=grid.def.allow.update && (forInsert?fieldDef.allow.insert:fieldDef.allow.update);
                td.addEventListener('update',function(){
                    var value = this.getTypedValue();
                    if(value!==tr.info.row[fieldDef.name]){
                        this.setAttribute('io-status', 'pending');
                        tr.info.rowPendingForUpdate[fieldDef.name] = value;
                        if(modes.saveByField){
                            saveRow(tr,{visiblyLogErrors:false});
                        }
                    }
                });
                tr.appendChild(td);
            });
            tr.addEventListener('focusout', function(event){
                if(event.target.parentNode != (event.relatedTarget||{}).parentNode ){
                    if(Object.keys(tr.info.rowPendingForUpdate).length){
                        saveRow(tr);
                    }
                }
            });
            return tr;
        }
        grid.destroyRowFilter = function destroyRowFilter(){
            var tr=grid.hasFilterRow;
            grid.element.setAttribute('has-filter',0);
            grid.element.tHead.removeChild(tr);
            delete grid.hasFilterRow;
        }
        grid.element.setAttribute('has-filter',0);
        grid.createRowFilter = function createRowFilter(){
            // var tr=html.tr().create();
            if(grid.hasFilterRow){
                return true;
            }
            var buttonFilter=html.button(myOwn.messages.Filter+"!").create();
            var tr=html.tr({'class':'filter-line'}, [html.th([buttonFilter])]).create();
            grid.hasFilterRow=tr;
            grid.element.setAttribute('has-filter',1);
            grid.element.tHead.appendChild(tr);
            // tr.appendChild(html.td().create());
            tr.info = {
                rowControls:{},
                row: {},
                rowSymbols: {},
                isFilterPending:false,
            };
            buttonFilter.addEventListener('click',function(){
                grid.displayBody(tr.info);
            });
            grid.def.fields.forEach(function(fieldDef){
                var fieldName=fieldDef.name;
                tr.info.rowSymbols[fieldName]=fieldDef.typeName==='text'?'~':'=';
                var symbolFilter=html.button({"class":'auto-filter', tabindex:-1},tr.info.rowSymbols[fieldName]).create();
                var elementFilter=html.span({"class":"filter-span"}).create();
                elementFilter.contentEditable=true;
                tr.info.rowControls[fieldName]=elementFilter;
                elementFilter.addEventListener('update',function(){
                    tr.info.row[fieldDef.name]=this.getTypedValue();
                });
                TypedControls.adaptElement(elementFilter,fieldDef);
                tr.appendChild(html.td({"class":"autoFilter"},[symbolFilter,elementFilter]).create());
            });
        }
        grid.displayBody=function displayBody(filterData){
            if(filterData){
                var rowsToDisplay= rows.filter(function(row,i){
                    var partialOk=true;
                    for(var column in row){
                        if(filterData.row[column]!=null){
                            var isSatisfied=my.comparator[filterData.rowSymbols[column]](row[column],filterData.row[column])
                            if(!isSatisfied){
                                partialOk=false;
                            }
                        }
                    }
                    return partialOk;
                })
            }else{
                var rowsToDisplay=rows;
            }
            if(grid.view.sortColumns.length>0){
                rowsToDisplay.sort(function(row1,row2){
                    var column;
                    var i=0;
                    do{
                        column=grid.view.sortColumns[i].column;
                        var a=bestGlobals.forOrder(row1[column]);
                        var b=bestGlobals.forOrder(row2[column]);
                        if(a>b){
                            return 1*grid.view.sortColumns[i].order;
                        }else if(a<b){
                            return -1*grid.view.sortColumns[i].order;
                        }
                        i++;
                    }while(i<grid.view.sortColumns.length);
                    return 0;
                });
            }
            var displayRows = function displayRows(fromRowNumber, toRowNumber, adding){
                if(!adding){
                    tbody.innerHTML='';
                }
                for(var iRow=fromRowNumber; iRow<toRowNumber; iRow++){
                    (function(row){
                        var tr=grid.createRowElements(-1);
                        updateRowData(tr, row);
                    })(rowsToDisplay[iRow]);
                }
                footInfoElement.displayFrom.textContent=rowsToDisplay.length?1:0;
                footInfoElement.displayTo.textContent=iRow;
                footInfoElement.rowCount.innerHTML='';
                if(iRow<rowsToDisplay.length){
                    var addButtonRest = function addButtonRest(toNextRowNumber){
                        var buttonRest=html.button("+..."+toNextRowNumber).create();
                        footInfoElement.rowCount.appendChild(html.span('  ').create());
                        footInfoElement.rowCount.appendChild(buttonRest);
                        buttonRest.addEventListener('click',function(){
                            displayRows(iRow, toNextRowNumber, true);
                        });
                    }
                    my.displayCountBreaks.forEach(function(size, iSize){
                        var cut=(iRow+size) - (iRow+size) % size;
                        if(cut*5<=rowsToDisplay.length*3 && (iSize==my.displayCountBreaks.length-1 || cut*5<=my.displayCountBreaks[iSize+1]*3)){
                            addButtonRest(cut);
                        }
                    });
                    addButtonRest(rowsToDisplay.length);
                }
            }
            displayRows(0, Math.min(my.firstDisplayCount,rowsToDisplay.length));
        }
        grid.displayBody();
    }
    my.ajax.table.data({
        table:tableName
    }).then(function(rows){
        return structureRequest.then(function(){
            my.adaptData(grid.def,rows);
            displayGrid(rows);
            return grid;
        });
    }).catch(function(err){
        my.log(err);
    })
}

myOwn.tableAction={
    "insert":{
        img: 'img/insert.png',
        actionRow: function(my, grid, tr){
            return grid.createRowElements(
                ('sectionRowIndex' in tr?
                    tr.sectionRowIndex:
                    tr.rowIndex-grid.element.tHead.rows.length
                )+1
            )
        }
    },
    "delete":{
        img: 'img/delete.png',
        actionRow: function(my, grid, tr){
            return my.showQuestion(my.messages.Delete+' '+JSON.stringify(tr.info.primaryKeyValues)+' ?').then(function(result){
                if(result){
                    return (tr.info.primaryKeyValues===false?
                        Promise.resolve():
                        my.ajax.table['delete-record']({
                            table:grid.def.name,
                            primaryKeyValues:tr.info.primaryKeyValues
                        })
                    ).then(function(){
                        my.fade(tr);
                    });
                }
            });
        }
    }
}<commit_msg>Nulos siempre abajo al ordenar.<commit_after>"use strict";

var changing = bestGlobals.changing;

myOwn.messages=changing(myOwn.messages, {
    loading: "loading",
    Filter : "Filter",
    Delete : "Delete",
});

myOwn.es=changing(myOwn.es, {
    loading: "cargando",
    Filter : "Filtrar",
    Delete : "Eliminar",
});

var escapeRegExp = bestGlobals.escapeRegExp;

myOwn.firstDisplayCount = 20;
myOwn.displayCountBreaks = [100,250,1000];
myOwn.displayCountBreaks = [50,100,500];
myOwn.comparator={
    '=':function(valueToCheck,condition){return valueToCheck == condition;},
    '~':function(valueToCheck,condition){return RegExp(escapeRegExp(condition),'i').test(valueToCheck);},
    '/R/i':function(valueToCheck,condition){return RegExp(condition,'i').test(valueToCheck);},
    '\u2205':function(valueToCheck,condition){return valueToCheck == null;},//\u2205 = conjunto vacío
    '>':function(valueToCheck,condition){return (valueToCheck>condition)},
    '>=':function(valueToCheck,condition){return (valueToCheck>=condition)},
    '<':function(valueToCheck,condition){return (valueToCheck<condition)},
    '<=':function(valueToCheck,condition){return (valueToCheck<=condition)},
    'not-an-operator':function(valueToCheck,condition){ return 'Operator does not exist'}
}
myOwn.tableGrid = function tableGrid(layout, tableName){
    var my = this;
    var inputColspan = 1;
    var modes = {
        saveByField: true
    };
    layout.textContent = my.messages.loading+'...';
    var grid={};
    var createRowElements;
    var createRowFilter;
    var footInfoElement;
    var structureRequest = my.ajax.table.structure({
        table:tableName,
    }).then(function(tableDef){
        grid.def=tableDef;
        grid.view={
            sortColumns:tableDef.sortColumns||[]
        }
        var buttonInsert;
        var buttonCreateFilter;
        var buttonDestroyFilter;
        var getSaveModeImgSrc=function(){ return modes.saveByField?'img/tables-update-by-field.png':'img/tables-update-by-row.png';};
        var buttonSaveModeImg=html.img({src:getSaveModeImgSrc()}).create();
        var buttonSaveMode;
        if(tableDef.allow.update){
            buttonSaveMode=html.button({class:'table-button'}, [buttonSaveModeImg]).create();
            buttonSaveMode.addEventListener('click',function(){
                modes.saveByField = !modes.saveByField;
                buttonSaveModeImg.src=getSaveModeImgSrc();
            });
        }
        if(tableDef.allow.insert){
            buttonInsert=html.button({class:'table-button'}, [html.img({src:'img/insert.png'})]).create();
            buttonInsert.addEventListener('click', function(){
                grid.createRowElements(0);
            });
        }
        if(tableDef.allow.filter){
            buttonCreateFilter=html.button({class:'table-button', 'when-filter':'no'}, [html.img({src:'img/filter.png'})]).create();
            buttonCreateFilter.addEventListener('click', function(){
                grid.createRowFilter(0);
            });
            buttonDestroyFilter=html.button({class:'table-button', 'when-filter':'yes'}, [html.img({src:'img/destroy-filter.png'})]).create();
            buttonDestroyFilter.addEventListener('click', function(){
                grid.destroyRowFilter(0);
            });
        }
        var columnsHeadElements = tableDef.fields.map(function(fieldDef){
            var tr=html.th({colspan:inputColspan},fieldDef.title).create();
            tr.addEventListener('click',function(){
                var currentOrder=grid.view.sortColumns.length && grid.view.sortColumns[0].column==fieldDef.name?grid.view.sortColumns[0].order:null;
                grid.view.sortColumns=grid.view.sortColumns.filter(function(sortColumn){
                    return sortColumn.column != fieldDef.name;
                })
                grid.view.sortColumns.unshift({column:fieldDef.name, order:currentOrder?-currentOrder:1})
                grid.displayBody(tr.info)
            });
            return tr;
        });
        footInfoElement = html.td({colspan:columnsHeadElements.length*inputColspan, "is-processing":"1"}).create();
        [
            {name:'displayFrom', value:'0'},
            {name:'elipsis', value:' ... '},
            {name:'displayTo', value:'?'},
            {name:'rowCount', value:''}
        ].forEach(function(info){
            footInfoElement[info.name] = html.span(info.value).create();
            footInfoElement.appendChild(footInfoElement[info.name]);
        });
        grid.element = html.table({"class":"my-grid", "my-table": tableName},[
            html.caption(tableDef.title),
            html.thead([
                html.tr([html.th([buttonInsert,/*buttonSaveMode,*/buttonCreateFilter,buttonDestroyFilter])].concat(columnsHeadElements))
            ]),
            html.tbody(),
            html.tfoot([
                html.tr([html.th(),footInfoElement])
            ])
        ]).create();
        layout.innerHTML='';
        layout.appendChild(grid.element);
    });
    var displayGrid = function displayGrid(rows){
        var tbody = grid.element.tBodies[0];
        var updateRowData = function updateRowData(tr, updatedRow){
            var forInsert = false; // not define how to detect
            tr.info.row = updatedRow;
            tr.info.status = 'retrieved';
            tr.info.primaryKeyValues = grid.def.primaryKey.map(function(fieldName){
                return tr.info.row[fieldName];
            });
            grid.def.fields.forEach(function(fieldDef){
                var td = tr.info.rowControls[fieldDef.name];
                td.contentEditable=grid.def.allow.update && (forInsert?fieldDef.allow.insert:fieldDef.allow.update);
                td.setTypedValue(tr.info.row[fieldDef.name]);
            });
        }
        var saveRow = function(tr, opts){
            var changeIoStatus = function changeIoStatus(newStatus, title){
                fieldNames.forEach(function(name){
                    var td=tr.info.rowControls[name];
                    td.setAttribute('io-status', newStatus);
                    if(title){
                        //td.title=err.message;
                    }
                });
            }
            var fieldNames=Object.keys(tr.info.rowPendingForUpdate);
            changeIoStatus('updating');
            my.ajax.table['save-record']({
                table:tableName,
                primaryKeyValues:tr.info.primaryKeyValues,
                newRow:tr.info.rowPendingForUpdate,
                status:tr.info.status
            },opts).then(function(updatedRow){
                my.adaptData(grid.def,[updatedRow]);
                updateRowData(tr, updatedRow);
                tr.info.rowPendingForUpdate = {};
                changeIoStatus('temporal-ok');
                setTimeout(function(){
                    changeIoStatus('ok');
                },3000);
            }).catch(function(err){
                changeIoStatus('error',err.message);
            });
        }
        grid.createRowElements = function createRowElements(iRow, row){
            var forInsert = iRow>=0;
            var tr = tbody.insertRow(iRow);
            tr.info = {
                rowControls:{},
                row: {},
                rowPendingForUpdate:{},
                primaryKeyValues:false,
                status: 'new'
            };
            var thActions=html.th().create();
            tr.appendChild(thActions);
            var actionNamesList = ['insert','delete'].concat(grid.def.actionNamesList);
            actionNamesList.forEach(function(actionName){
                var actionDef = my.tableAction[actionName];
                if(grid.def.allow[actionName]){
                    var buttonAction=html.button({class:'table-button'}, [
                        html.img({src:actionDef.img})
                    ]).create();
                    thActions.appendChild(buttonAction);
                    buttonAction.addEventListener('click', function(){
                        actionDef.actionRow(my,grid,tr);
                    });
                }
            });
            grid.def.fields.forEach(function(fieldDef){
                var td = html.td({colspan:inputColspan}).create();
                TypedControls.adaptElement(td, fieldDef);
                tr.info.rowControls[fieldDef.name] = td;
                td.contentEditable=grid.def.allow.update && (forInsert?fieldDef.allow.insert:fieldDef.allow.update);
                td.addEventListener('update',function(){
                    var value = this.getTypedValue();
                    if(value!==tr.info.row[fieldDef.name]){
                        this.setAttribute('io-status', 'pending');
                        tr.info.rowPendingForUpdate[fieldDef.name] = value;
                        if(modes.saveByField){
                            saveRow(tr,{visiblyLogErrors:false});
                        }
                    }
                });
                tr.appendChild(td);
            });
            tr.addEventListener('focusout', function(event){
                if(event.target.parentNode != (event.relatedTarget||{}).parentNode ){
                    if(Object.keys(tr.info.rowPendingForUpdate).length){
                        saveRow(tr);
                    }
                }
            });
            return tr;
        }
        grid.destroyRowFilter = function destroyRowFilter(){
            var tr=grid.hasFilterRow;
            grid.element.setAttribute('has-filter',0);
            grid.element.tHead.removeChild(tr);
            delete grid.hasFilterRow;
        }
        grid.element.setAttribute('has-filter',0);
        grid.createRowFilter = function createRowFilter(){
            // var tr=html.tr().create();
            if(grid.hasFilterRow){
                return true;
            }
            var buttonFilter=html.button(myOwn.messages.Filter+"!").create();
            var tr=html.tr({'class':'filter-line'}, [html.th([buttonFilter])]).create();
            grid.hasFilterRow=tr;
            grid.element.setAttribute('has-filter',1);
            grid.element.tHead.appendChild(tr);
            // tr.appendChild(html.td().create());
            tr.info = {
                rowControls:{},
                row: {},
                rowSymbols: {},
                isFilterPending:false,
            };
            buttonFilter.addEventListener('click',function(){
                grid.displayBody(tr.info);
            });
            grid.def.fields.forEach(function(fieldDef){
                var fieldName=fieldDef.name;
                tr.info.rowSymbols[fieldName]=fieldDef.typeName==='text'?'~':'=';
                var symbolFilter=html.button({"class":'auto-filter', tabindex:-1},tr.info.rowSymbols[fieldName]).create();
                var elementFilter=html.span({"class":"filter-span"}).create();
                elementFilter.contentEditable=true;
                tr.info.rowControls[fieldName]=elementFilter;
                elementFilter.addEventListener('update',function(){
                    tr.info.row[fieldDef.name]=this.getTypedValue();
                });
                TypedControls.adaptElement(elementFilter,fieldDef);
                tr.appendChild(html.td({"class":"autoFilter"},[symbolFilter,elementFilter]).create());
            });
        }
        grid.displayBody=function displayBody(filterData){
            if(filterData){
                var rowsToDisplay= rows.filter(function(row,i){
                    var partialOk=true;
                    for(var column in row){
                        if(filterData.row[column]!=null){
                            var isSatisfied=my.comparator[filterData.rowSymbols[column]](row[column],filterData.row[column])
                            if(!isSatisfied){
                                partialOk=false;
                            }
                        }
                    }
                    return partialOk;
                })
            }else{
                var rowsToDisplay=rows;
            }
            if(grid.view.sortColumns.length>0){
                rowsToDisplay.sort(function(row1,row2){
                    var column;
                    var i=0;
                    do{
                        column=grid.view.sortColumns[i].column;
                        if(row1[column]==null){
                            return 1;
                        }
                        if(row2[column]==null){
                            return -1;
                        }
                        var a=bestGlobals.forOrder(row1[column]);
                        var b=bestGlobals.forOrder(row2[column]);
                        if(a>b){
                            return 1*grid.view.sortColumns[i].order;
                        }else if(a<b){
                            return -1*grid.view.sortColumns[i].order;
                        }
                        i++;
                    }while(i<grid.view.sortColumns.length);
                    return 0;
                });
            }
            var displayRows = function displayRows(fromRowNumber, toRowNumber, adding){
                if(!adding){
                    tbody.innerHTML='';
                }
                for(var iRow=fromRowNumber; iRow<toRowNumber; iRow++){
                    (function(row){
                        var tr=grid.createRowElements(-1);
                        updateRowData(tr, row);
                    })(rowsToDisplay[iRow]);
                }
                footInfoElement.displayFrom.textContent=rowsToDisplay.length?1:0;
                footInfoElement.displayTo.textContent=iRow;
                footInfoElement.rowCount.innerHTML='';
                if(iRow<rowsToDisplay.length){
                    var addButtonRest = function addButtonRest(toNextRowNumber){
                        var buttonRest=html.button("+..."+toNextRowNumber).create();
                        footInfoElement.rowCount.appendChild(html.span('  ').create());
                        footInfoElement.rowCount.appendChild(buttonRest);
                        buttonRest.addEventListener('click',function(){
                            displayRows(iRow, toNextRowNumber, true);
                        });
                    }
                    my.displayCountBreaks.forEach(function(size, iSize){
                        var cut=(iRow+size) - (iRow+size) % size;
                        if(cut*5<=rowsToDisplay.length*3 && (iSize==my.displayCountBreaks.length-1 || cut*5<=my.displayCountBreaks[iSize+1]*3)){
                            addButtonRest(cut);
                        }
                    });
                    addButtonRest(rowsToDisplay.length);
                }
            }
            displayRows(0, Math.min(my.firstDisplayCount,rowsToDisplay.length));
        }
        grid.displayBody();
    }
    my.ajax.table.data({
        table:tableName
    }).then(function(rows){
        return structureRequest.then(function(){
            my.adaptData(grid.def,rows);
            displayGrid(rows);
            return grid;
        });
    }).catch(function(err){
        my.log(err);
    })
}

myOwn.tableAction={
    "insert":{
        img: 'img/insert.png',
        actionRow: function(my, grid, tr){
            return grid.createRowElements(
                ('sectionRowIndex' in tr?
                    tr.sectionRowIndex:
                    tr.rowIndex-grid.element.tHead.rows.length
                )+1
            )
        }
    },
    "delete":{
        img: 'img/delete.png',
        actionRow: function(my, grid, tr){
            return my.showQuestion(my.messages.Delete+' '+JSON.stringify(tr.info.primaryKeyValues)+' ?').then(function(result){
                if(result){
                    return (tr.info.primaryKeyValues===false?
                        Promise.resolve():
                        my.ajax.table['delete-record']({
                            table:grid.def.name,
                            primaryKeyValues:tr.info.primaryKeyValues
                        })
                    ).then(function(){
                        my.fade(tr);
                    });
                }
            });
        }
    }
}<|endoftext|>


<commit_before>/*
  nomon.js
  Easily show/hide portions of text in long paragraphs.

  Requires: jQuery 1.6.x
*/

(function($){
  $.fn.nomon = function nomon(opts) {
    var parent = this,
        opts = opts || {},
        words = this.text().split(' ');
    words.splice(opts.words || 20, 1, '');
    words.push('');
    words.push('Read More')

    this.html(words.join(' '));

    this.find('a[data-action="toggleHiddenText"]').one('click', function(e){
      e.preventDefault();
      parent.find('span[data-action-receiver="toggleHiddenText"]').show();
      $(this).hide();
    });
  }
})(jQuery);<commit_msg>Updated description.<commit_after>/*
  nomon.js
  Simple show more helper.

  Requires: jQuery 1.6.x
*/

(function($){
  $.fn.nomon = function nomon(opts) {
    var parent = this,
        opts = opts || {},
        words = this.text().split(' ');
    words.splice(opts.words || 20, 1, '');
    words.push('');
    words.push('Read More')

    this.html(words.join(' '));

    this.find('a[data-action="toggleHiddenText"]').one('click', function(e){
      e.preventDefault();
      parent.find('span[data-action-receiver="toggleHiddenText"]').show();
      $(this).hide();
    });
  }
})(jQuery);<|endoftext|>


<commit_before>(function() {
		$("nav div#button").on('click', function(){
			$('div#belezkaInput').css("display","block");
			$('div#belezka').css("display","none");
			$('div#fotBox').css("display","block");
		});

		$("div#wrapper div#belezka div#bele_Main div#button_re").on('click', function(){
			var content = $(this).first("div#belezkaInput div#content").val();
			var colorClass =$(this).first("div#belezkaInput div#content").prop('class');
		/*	$(this).closest('div#belezka').remove();*/
			$('div#belezkaInput').css("display","block");
			$('div#belezka').css("display","none");
			$('div#fotBox').css("display","block");
			$('div#belezkaInput').addClass(colorClass);
			$('div#belezkaInput textarea').text(content);
		});

		$('div#fotBox div#purple').click(function() {
			$('div#belezkaInput div#content').attr( "class", "purple" );
		});
		$('div#fotBox div#yellow').click(function() {
			$('div#belezkaInput div#content').attr( "class", "yellow" );
		});
		$('div#fotBox div#blue').click(function() {
			$('div#belezkaInput div#content').attr( "class", "blue" );
		});
		$('div#fotBox div#green').click(function() {
			$('div#belezkaInput div#content').attr( "class", "green" );
		});
		$('div#fotBox div#orange').click(function() {
			$('div#belezkaInput div#content').attr( "class", "orange" );
		});

		$('div#wrapper div#bele_Main div#button').click(function() {
		$(this).closest('div#belezka').animate(1500).css("height","auto");
		});

		$('div#bele_Main div#button_right-end').click(function() {
		$(this).closest('div#belezka').css("height","65px");
		});

		$('div#wrapper div#belezka div#bele_Main div#button_right').click(function() {
			confirm("STE SIGRNA DA zelite");
	/*	$(this).closest('div#belezka').slideUp(400);*/
		$(this).closest('div#belezka').remove();
		var count1 = $( "div#belezka" ).size() -2 ;
		$('nav div#button span#count').text(count1);
		});

			$('div#fotBox div#buttons div#preklici').click(function(){
			$('div#belezkaInput').css("display","none");
			$('div#belezka').css("display","block");
			$('div#fotBox').css("display","none");
		});

		$('div#fotBox div#buttons div#shrani').click(function(){
			$('div#belezka').css("display","block");
			var content = $("div#belezkaInput textarea").val();
			var colorClass =$("div#belezkaInput div#content").prop('class');
				/*var belezka = $("div#wrapper").first("div#belezka");*/
					var belezka = $("div#belezka.default").clone(true);

				console.log(belezka);

			/*	$(belezka).css("display","block");*/

			$('div#fotBox').css("display","none");
			$('div#belezkaInput').css("display","none");
			/*$('div#belezka').css("display","block");*/

			/*$("div#wrapper").prepend(belezka);*/

			/*belezka.addClass(colorClass).text(content);*/
			belezka.removeClass("default").appendTo("div#wrapper");
			$('div#wrapper div#belezka').last('div#belezka').addClass(colorClass);
			$('div#wrapper div#belezka div#content').last().text(content);
						/*.nth(1).first("div#content")
						.addClass('red');*/
						/*.text(content);*/
			/*$('div#belezka').first().addClass(colorClass);*/
			/*$("div#wrapper").after('sdsdsds');*/
				var count1 = $( "div#belezka" ).size() -2 ;
				/*alert( "Size: " + count1);*/
				/*var text12 = '+ Ustvari belezko ...' . count1;*/
			$('nav div#button span#count').text(count1);
			});
})();
<commit_msg>Delete notes.js<commit_after><|endoftext|>


<commit_before>// ==UserScript==
// @name        Hyperiums forum highlighting
// @namespace   http://github.com/Nasga/hyperiums-greasemonkey/
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
// @include     http://hyp2.hyperiums.com/servlet/Forums*
// @version     39
// @grant       none
// ==/UserScript==

/* global $:false */

"use strict";

var storageAvailable = false;

if (typeof(Storage) !== "undefined") {
    storageAvailable = true;
}
var forumJSon = getForumStorage();

function storeForumPostDate(forumThreadId, forumPostDate) {
    var dummy;
    if (!forumJSon[forumThreadId]) {
        forumJSon[forumThreadId] = forumPostDate;
        return true;
    }
    var storedForumPostDate = new Date(forumJSon[forumThreadId]);
    if (forumPostDate > storedForumPostDate) {
        forumJSon[forumThreadId] = forumPostDate;
    }
    return true;
}

function hypDateToDate(hypDate) {
    return new Date(
        hypDate.substr(0, 4),
        parseInt(hypDate.substr(5, 2)) - 1,
        hypDate.substr(8, 2),
        hypDate.substr(11, 2),
        hypDate.substr(14, 2),
        hypDate.substr(17, 2),
        0
    )
}

function needHighlight(threadId, forumPostDate) {
    if (forumJSon[threadId]) {
        storedForumDate = new Date(forumJSon[threadId]);
    } else {
        storedForumDate = new Date(1970, 0, 1);
    }
    if (forumPostDate > storedForumDate) {
        return true;
    }
    return false;
}

function getForumStorage() {
    if (!storageAvailable) {
        return "";
    }
    var forumStorage = localStorage.forumStorage;
    if (forumStorage) {
        return JSON.parse(forumStorage);
    }
    else {
        return {};
    }
}

function setForumStorage(forumStorageIn) {
    localStorage.forumStorage = JSON.stringify(forumStorageIn);
    return true;
}

function getUrlVars(urlIn) {
    var vars = {};
    var parts = urlIn.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}

if (window.location.search.indexOf("action=fenter") > -1) {
    if (storageAvailable) {
        var link = "";
        var threadId = "";
        var forumThreadLastPost;

        $('body ul.solidblockmenu2').append('
Mark all Read
');
        $('#markAllRead').click(function () {
                $('body center form tr:not(#forumArray)')
                    .each(function (idx, elt) {
                        if ($(elt).find('#noStyle').length < 1) {
                            link = $(elt).find('td:not(.hc) a:first').prop("href");
                            threadId = getUrlVars(link)["threadid"];
                            forumThreadLastPost = hypDateToDate($(elt).find('td.hc:eq(2)').text());
                            if (forumJSon[threadId]) {
                                storedForumDate = new Date(forumJSon[threadId]);
                            } else {
                                storedForumDate = new Date(1970, 0, 1);
                            }
                            if (forumThreadLastPost > storedForumDate) {
                                forumJSon[threadId] = forumThreadLastPost.toUTCString();
                                $(elt).find('td:not(.hc) a:first').css("font-style", "normal");
                            }
                        }
                    }
                )
                setForumStorage(forumJSon);
            }
        );

        $('body center form tr:not(#forumArray)')
            .each(function (idx, elt) {
                link = $(elt).find('td:not(.hc) a:first').prop("href");
                threadId = getUrlVars(link)["threadid"];
                forumThreadLastPost = hypDateToDate($(elt).find('td.hc:eq(2)').text());
                if (needHighlight(threadId, forumThreadLastPost)) {
                    $(elt).find('td:not(.hc) a:first').css("font-style", "italic");
                }
            }
        );

    }
}

if (window.location.search.indexOf("action=fdispmsg") > -1) {
    if (storageAvailable) {
        var forumPostDate;
        var forumThreadId;
        var storedForumDate;
        forumThreadId = getUrlVars(window.location.href)["threadid"];

        if (forumJSon[forumThreadId]) {
            storedForumDate = new Date(forumJSon[forumThreadId]);
        } else {
            storedForumDate = new Date(1970, 0, 1);
        }
        $('body table.sender td.player')
            .each(function (idx, elt) {
                forumPostDate = hypDateToDate($(elt).text().substr(0, 19));
//            alert(forumPostDate);
                if (forumPostDate > storedForumDate) {
                    forumJSon[forumThreadId] = forumPostDate.toUTCString();
                }
            }
        );
        setForumStorage(forumJSon);
    }
}

if (window.location.search.indexOf("action=lastmsg") > -1) {
    if (storageAvailable) {
        var forumPostDate;
        var forumThreadId;
        var storedForumDate;
        var link = "";

        $('body center table.hc:not(.body)')
            .each(function (idx, elt) {
                if ($(elt).width() > 460) {
                    link = $(elt).find('tr.msgForum td.hc a').attr("href");
//                if (link != 'undefined') {
                    forumThreadId = getUrlVars(link)["threadid"];
                    if (forumJSon[forumThreadId]) {
                        storedForumDate = new Date(forumJSon[forumThreadId]);
                    } else {
                        storedForumDate = new Date(1970, 0, 1);
                    }
                    forumPostDate = hypDateToDate($(elt).find('table.sender td.player').text().substr(0, 19));
                    if (forumPostDate > storedForumDate) {
                        forumJSon[forumThreadId] = forumPostDate.toUTCString();
                    }
                }
            }
        );
        setForumStorage(forumJSon);
    }
}
<commit_msg>Also perform highlighting (italic) after new forum post<commit_after>// ==UserScript==
// @name        Hyperiums forum highlighting
// @namespace   http://github.com/Nasga/hyperiums-greasemonkey/
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
// @include     http://hyp2.hyperiums.com/servlet/Forums*
// @version     40
// @grant       none
// ==/UserScript==

/* global $:false */

"use strict";

var storageAvailable = false;

if (typeof(Storage) !== "undefined") {
    storageAvailable = true;
}
var forumJSon = getForumStorage();

function storeForumPostDate(forumThreadId, forumPostDate) {
    var dummy;
    if (!forumJSon[forumThreadId]) {
        forumJSon[forumThreadId] = forumPostDate;
        return true;
    }
    var storedForumPostDate = new Date(forumJSon[forumThreadId]);
    if (forumPostDate > storedForumPostDate) {
        forumJSon[forumThreadId] = forumPostDate;
    }
    return true;
}

function hypDateToDate(hypDate) {
    return new Date(
        hypDate.substr(0, 4),
        parseInt(hypDate.substr(5, 2)) - 1,
        hypDate.substr(8, 2),
        hypDate.substr(11, 2),
        hypDate.substr(14, 2),
        hypDate.substr(17, 2),
        0
    )
}

function needHighlight(threadId, forumPostDate) {
    if (forumJSon[threadId]) {
        storedForumDate = new Date(forumJSon[threadId]);
    } else {
        storedForumDate = new Date(1970, 0, 1);
    }
    if (forumPostDate > storedForumDate) {
        return true;
    }
    return false;
}

function getForumStorage() {
    if (!storageAvailable) {
        return "";
    }
    var forumStorage = localStorage.forumStorage;
    if (forumStorage) {
        return JSON.parse(forumStorage);
    }
    else {
        return {};
    }
}

function setForumStorage(forumStorageIn) {
    localStorage.forumStorage = JSON.stringify(forumStorageIn);
    return true;
}

function getUrlVars(urlIn) {
    var vars = {};
    var parts = urlIn.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}

if ((window.location.search.indexOf("action=fenter") > -1) ||
    ($('body center center span.info:not(.bigtext)').length > 0)) {
    if (storageAvailable) {
        var link = "";
        var threadId = "";
        var forumThreadLastPost;

        // Create Read All button
        $('body ul.solidblockmenu2').append('
Mark all Read
');
        // on click Read All button, store last posts dates per threadid to forumJSon
        $('#markAllRead').click(function () {
                $('body center form tr:not(#forumArray)')
                    .each(function (idx, elt) {
                        if ($(elt).find('#noStyle').length < 1) {
                            link = $(elt).find('td:not(.hc) a:first').prop("href");
                            threadId = getUrlVars(link)["threadid"];
                            forumThreadLastPost = hypDateToDate($(elt).find('td.hc:eq(2)').text());
                            if (forumJSon[threadId]) {
                                storedForumDate = new Date(forumJSon[threadId]);
                            } else {
                                storedForumDate = new Date(1970, 0, 1);
                            }
                            if (forumThreadLastPost > storedForumDate) {
                                forumJSon[threadId] = forumThreadLastPost.toUTCString();
                                $(elt).find('td:not(.hc) a:first').css("font-style", "normal");
                            }
                        }
                    }
                )
                setForumStorage(forumJSon);
            }
        );

        $('body center form tr:not(#forumArray)')
            .each(function (idx, elt) {
                link = $(elt).find('td:not(.hc) a:first').prop("href");
                threadId = getUrlVars(link)["threadid"];
                forumThreadLastPost = hypDateToDate($(elt).find('td.hc:eq(2)').text());
                if (needHighlight(threadId, forumThreadLastPost)) {
                    $(elt).find('td:not(.hc) a:first').css("font-style", "italic");
                }
            }
        );

    }
}

if (window.location.search.indexOf("action=fdispmsg") > -1) {
    if (storageAvailable) {
        var forumPostDate;
        var forumThreadId;
        var storedForumDate;
        forumThreadId = getUrlVars(window.location.href)["threadid"];

        if (forumJSon[forumThreadId]) {
            storedForumDate = new Date(forumJSon[forumThreadId]);
        } else {
            storedForumDate = new Date(1970, 0, 1);
        }
        $('body table.sender td.player')
            .each(function (idx, elt) {
                forumPostDate = hypDateToDate($(elt).text().substr(0, 19));
//            alert(forumPostDate);
                if (forumPostDate > storedForumDate) {
                    forumJSon[forumThreadId] = forumPostDate.toUTCString();
                }
            }
        );
        setForumStorage(forumJSon);
    }
}

if (window.location.search.indexOf("action=lastmsg") > -1) {
    if (storageAvailable) {
        var forumPostDate;
        var forumThreadId;
        var storedForumDate;
        var link = "";

        $('body center table.hc:not(.body)')
            .each(function (idx, elt) {
                if ($(elt).width() > 460) {
                    link = $(elt).find('tr.msgForum td.hc a').attr("href");
//                if (link != 'undefined') {
                    forumThreadId = getUrlVars(link)["threadid"];
                    if (forumJSon[forumThreadId]) {
                        storedForumDate = new Date(forumJSon[forumThreadId]);
                    } else {
                        storedForumDate = new Date(1970, 0, 1);
                    }
                    forumPostDate = hypDateToDate($(elt).find('table.sender td.player').text().substr(0, 19));
                    if (forumPostDate > storedForumDate) {
                        forumJSon[forumThreadId] = forumPostDate.toUTCString();
                    }
                }
            }
        );
        setForumStorage(forumJSon);
    }
}
<|endoftext|>


<commit_before>var XMLSerializer = require("xmldom").XMLSerializer,
	DOMParser = require("xmldom").DOMParser;

var filename = process.argv[2];
var doc = new DOMParser().parseFromString(string);
console.log(filename);<commit_msg>deleted parse file for now<commit_after><|endoftext|>


<commit_before>(function () {
    'use strict';

    angular.module('djangularRestFramework', ['angularExtQ', 'jmdobry.angular-cache'])
        .factory('drf', ['$rootScope', '$http', '$angularCacheFactory', 'extQ', function ($rootScope, $http, $angularCacheFactory, extQ) {
            var equals = angular.equals;
            var forEach = angular.forEach;
            var isDefined = angular.isDefined;
            var isUndefined = angular.isUndefined;

            var cacheOptions = {
                maxAge: 86400000,
                storageMode: 'localStorage'
            };

            var defaultOptions = {
                cache: true
            };

            var api = {
                optionsCache: $angularCacheFactory('optionsCache', cacheOptions),
                urlCache: $angularCacheFactory('urlCache', cacheOptions),
                objectCache: $angularCacheFactory('objectCache', cacheOptions),

                getPage: function (url, options, deferred, items) {
                    $http({
                        method: 'GET',
                        url: url,
                        params: options.params
                    }).then(function (response) {
                        // If the response has pages it will be structured
                        // differently.
                        var data;
                        if (angular.isDefined(response.data.results)) {
                            data = response.data.results;
                        } else {
                            data = response.data;
                        }

                        if (angular.isDefined(response.data.count) && angular.isUndefined(options.limit)) {
                            options.limit = response.data.count;
                        }

                        deferred.update(data);
                        items = items.concat(data);

                        if (isDefined(response.data.next) && response.data.next !== null && items.length < options.limit) {
                            api.getPage(response.data.next, options, deferred, items);
                        } else {
                            if (isDefined(options.limit)) {
                                items = items.splice(0, options.limit);
                            }
                            deferred.resolve(items);
                        }

                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });
                },

                stream: function (url, options) {
                    var deferred = extQ.defer(['update']);
                    var items = [];

                    api.getPage(url, options, deferred, items);

                    return deferred.promise;
                },

                load: function (url, options) {
                    var deferred = extQ.defer();

                    $http({
                        method: 'GET',
                        url: url,
                        params: options.params
                    }).then(function (response) {
                        deferred.resolve(response);
                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });

                    return deferred.promise;
                },

                loadList: function (url, options, deferred) {
                    options = angular.extend(defaultOptions, options);
                    deferred = deferred || extQ.defer(['add', 'update', 'remove']);

                    if (options.cache) {
                        // Load list of item URLs from urlCache.
                        var cached = api.urlCache.get(url);
                        if (isDefined(options.limit) && isDefined(cached)) {
                            cached = cached.splice(0, options.limit);
                        }
                        forEach(cached, function (url) {
                            var obj = api.objectCache.get(url);
                            if (isDefined(obj)) {
                                deferred.add(obj);
                            }
                        });
                    }

                    var seen = {};
                    api.stream(url, options).update(function (list) {
                        // Stream the list
                        forEach(list, function (item) {
                            seen[item.url] = item;
                            if (options.cache) {
                                var cached = api.objectCache.get(item.url);
                                if (isUndefined(cached)) {
                                    api.objectCache.put(item.url, item);
                                    deferred.add(item);
                                } else if (!equals(cached, item)) {
                                    api.objectCache.put(item.url, item);
                                    deferred.update(item);
                                }
                            } else {
                                deferred.add(item);
                            }
                        });
                    }).then(function (list) {
                        if (options.cache) {
                            // Remove items from the cache if they were not returned
                            // in the list.
                            if (cached) {
                                forEach(cached, function (url) {
                                    if (isUndefined(seen[url])) {
                                        deferred.remove(url);
                                        api.objectCache.remove(url);
                                    }
                                });
                            }

                            // Update the urlCache with a list of URLs.
                            var urls = [];
                            forEach(list, function (item) {
                                if (isDefined(item.url)) {
                                    urls.push(item.url);
                                }
                            });
                            api.urlCache.put(url, urls);
                        }

                        deferred.resolve(list);
                    });

                    return deferred.promise;
                },

                loadItem: function (url, options, deferred) {
                    options = angular.extend(defaultOptions, options);
                    deferred = deferred || extQ.defer(['add', 'update', 'remove']);

                    if (options.cache) {
                        // Load the item from the cache.
                        var cached = api.objectCache.get(url);
                        if (isDefined(cached)) {
                            deferred.add(cached);
                        }
                    }

                    api.load(url, options).then(function (response) {
                        var item = response.data;
                        if (options.cache) {
                            if (isUndefined(cached)) {
                                api.objectCache.put(url, item);
                                deferred.add(item);
                            } else if (!equals(cached, item)) {
                                api.objectCache.put(url, item);
                                deferred.update(item);
                            }
                        }

                        deferred.resolve(item);
                    });

                    return deferred.promise;
                },

                loadOptions: function (url, options, deferred) {
                    options = angular.extend(defaultOptions, options);
                    deferred = deferred || extQ.defer();

                    if (options.cache) {
                        // Load the options from the cache.
                        var cached = api.optionsCache.get(url);
                        if (isDefined(cached)) {
                            deferred.resolve(cached);
                        }
                    }

                    $http({
                        method: 'OPTIONS',
                        url: url
                    }).then(function (response) {
                        if (options.cache) {
                            if (!equals(cached, response.data)) {
                                api.optionsCache.put(url, response.data);
                            }
                        }

                        deferred.resolve(response.data);
                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });
                }
            };

            return api;
        }]);
}());
<commit_msg>loadOptions should return the data and url.<commit_after>(function () {
    'use strict';

    angular.module('djangularRestFramework', ['angularExtQ', 'jmdobry.angular-cache'])
        .factory('drf', ['$rootScope', '$http', '$angularCacheFactory', 'extQ', function ($rootScope, $http, $angularCacheFactory, extQ) {
            var equals = angular.equals;
            var forEach = angular.forEach;
            var isDefined = angular.isDefined;
            var isUndefined = angular.isUndefined;

            var cacheOptions = {
                maxAge: 86400000,
                storageMode: 'localStorage'
            };

            var defaultOptions = {
                cache: true
            };

            var api = {
                optionsCache: $angularCacheFactory('optionsCache', cacheOptions),
                urlCache: $angularCacheFactory('urlCache', cacheOptions),
                objectCache: $angularCacheFactory('objectCache', cacheOptions),

                getPage: function (url, options, deferred, items) {
                    $http({
                        method: 'GET',
                        url: url,
                        params: options.params
                    }).then(function (response) {
                        // If the response has pages it will be structured
                        // differently.
                        var data;
                        if (angular.isDefined(response.data.results)) {
                            data = response.data.results;
                        } else {
                            data = response.data;
                        }

                        if (angular.isDefined(response.data.count) && angular.isUndefined(options.limit)) {
                            options.limit = response.data.count;
                        }

                        deferred.update(data);
                        items = items.concat(data);

                        if (isDefined(response.data.next) && response.data.next !== null && items.length < options.limit) {
                            api.getPage(response.data.next, options, deferred, items);
                        } else {
                            if (isDefined(options.limit)) {
                                items = items.splice(0, options.limit);
                            }
                            deferred.resolve(items);
                        }

                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });
                },

                stream: function (url, options) {
                    var deferred = extQ.defer(['update']);
                    var items = [];

                    api.getPage(url, options, deferred, items);

                    return deferred.promise;
                },

                load: function (url, options) {
                    var deferred = extQ.defer();

                    $http({
                        method: 'GET',
                        url: url,
                        params: options.params
                    }).then(function (response) {
                        deferred.resolve(response);
                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });

                    return deferred.promise;
                },

                loadList: function (url, options, deferred) {
                    options = angular.extend(defaultOptions, options);
                    deferred = deferred || extQ.defer(['add', 'update', 'remove']);

                    if (options.cache) {
                        // Load list of item URLs from urlCache.
                        var cached = api.urlCache.get(url);
                        if (isDefined(options.limit) && isDefined(cached)) {
                            cached = cached.splice(0, options.limit);
                        }
                        forEach(cached, function (url) {
                            var obj = api.objectCache.get(url);
                            if (isDefined(obj)) {
                                deferred.add(obj);
                            }
                        });
                    }

                    var seen = {};
                    api.stream(url, options).update(function (list) {
                        // Stream the list
                        forEach(list, function (item) {
                            seen[item.url] = item;
                            if (options.cache) {
                                var cached = api.objectCache.get(item.url);
                                if (isUndefined(cached)) {
                                    api.objectCache.put(item.url, item);
                                    deferred.add(item);
                                } else if (!equals(cached, item)) {
                                    api.objectCache.put(item.url, item);
                                    deferred.update(item);
                                }
                            } else {
                                deferred.add(item);
                            }
                        });
                    }).then(function (list) {
                        if (options.cache) {
                            // Remove items from the cache if they were not returned
                            // in the list.
                            if (cached) {
                                forEach(cached, function (url) {
                                    if (isUndefined(seen[url])) {
                                        deferred.remove(url);
                                        api.objectCache.remove(url);
                                    }
                                });
                            }

                            // Update the urlCache with a list of URLs.
                            var urls = [];
                            forEach(list, function (item) {
                                if (isDefined(item.url)) {
                                    urls.push(item.url);
                                }
                            });
                            api.urlCache.put(url, urls);
                        }

                        deferred.resolve(list);
                    });

                    return deferred.promise;
                },

                loadItem: function (url, options, deferred) {
                    options = angular.extend(defaultOptions, options);
                    deferred = deferred || extQ.defer(['add', 'update', 'remove']);

                    if (options.cache) {
                        // Load the item from the cache.
                        var cached = api.objectCache.get(url);
                        if (isDefined(cached)) {
                            deferred.add(cached);
                        }
                    }

                    api.load(url, options).then(function (response) {
                        var item = response.data;
                        if (options.cache) {
                            if (isUndefined(cached)) {
                                api.objectCache.put(url, item);
                                deferred.add(item);
                            } else if (!equals(cached, item)) {
                                api.objectCache.put(url, item);
                                deferred.update(item);
                            }
                        }

                        deferred.resolve(item);
                    });

                    return deferred.promise;
                },

                loadOptions: function (url, options, deferred) {
                    options = angular.extend(defaultOptions, options);
                    deferred = deferred || extQ.defer();

                    if (options.cache) {
                        // Load the options from the cache.
                        var cached = api.optionsCache.get(url);
                        if (isDefined(cached)) {
                            deferred.resolve({data: cached, url: url});
                        }
                    }

                    $http({
                        method: 'OPTIONS',
                        url: url
                    }).then(function (response) {
                        if (options.cache) {
                            if (!equals(cached, response.data)) {
                                api.optionsCache.put(url, response.data);
                            }
                        }

                        deferred.resolve({data: response.data, url: url});
                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });
                }
            };

            return api;
        }]);
}());
<|endoftext|>


<commit_before>let Vue

class Store {
  constructor({
    state,
    actions,
    mutations,
    getters
  }) {
    this.actions = actions
    this.mutations = mutations
    this.getters = {}
    this._watcherVM = new Vue()
    const store = this
    const computed = {}

    forEachValue(getters, (fn, key) => {
      computed[key] = () => {
        const state = store.state
        return fn(state)
      }
      Object.defineProperty(store.getters, key, {
        get: () => {
          return store._vm[key]
        },
        enumerable: true
      })
    })
    store._vm = new Vue({
      data: {
        $$state: state
      },
      computed
    })
  }

  get state() {
    return this._vm._data.$$state
  }

  set state(state) {
    this._vm._data.$$state = state
  }

  commit(mutation, options) {
    if (mutation === 'router/ROUTE_CHANGED') {
      return Vue.set(this.state, 'route', options)
    }
    return this.mutations[mutation].call(null, this.state, options)
  }

  dispatch(action, options) {
    const result = this.actions[action].call(null, {
      commit: this.commit.bind(this),
      state: this.state,
      dispatch: this.dispatch.bind(this)
    }, options)
    if (result && typeof result.then === 'function') {
      return result
    } else {
      return Promise.resolve(result)
    }
  }

  watch(getter, cb, options) {
    return this._watcherVM.$watch(() => getter(this.state, this.getters), cb, options)
  }

  replaceState(state) {
    this._vm._data.$$state = state
  }

  registerModule(path, rawModule) {
    this.state.route = rawModule
  }

}

function install(_Vue) {
  Vue = _Vue
  Vue.mixin({ beforeCreate: vuexInit })
}

const mapGetters = (getters) => {
  const res = {}
  getters.forEach(item => {
    res[item] = function() {
      const result = this.$store.getters[item]
      return result
    }
  })
  return res
}

function vuexInit() {
  const options = this.$options
  // store injection
  if (options.store) {
    this.$store = options.store
  } else if (options.parent && options.parent.$store) {
    this.$store = options.parent.$store
  }
}

export default {
  install,
  Store
}

export {
  mapGetters
}

function forEachValue(obj, fn) {
  Object.keys(obj).forEach(key => fn(obj[key], key))
}
<commit_msg>[前端] 去除webpack externals中的vuex<commit_after>let Vue

class Store {
  constructor({
    state,
    actions,
    mutations,
    getters
  }) {
    this.actions = actions
    this.mutations = mutations
    this.getters = {}
    this._watcherVM = new Vue()
    const store = this
    const computed = {}

    forEachValue(getters, (fn, key) => {
      computed[key] = () => {
        const state = store.state
        return fn(state)
      }
      Object.defineProperty(store.getters, key, {
        get: () => {
          return store._vm[key]
        },
        enumerable: true
      })
    })
    store._vm = new Vue({
      data: {
        $$state: state
      },
      computed
    })
  }

  get state() {
    return this._vm._data.$$state
  }

  set state(state) {
    this._vm._data.$$state = state
  }

  commit(mutation, options) {
    if (mutation === 'router/ROUTE_CHANGED') {
      return Vue.set(this.state, 'route', options)
    }
    return this.mutations[mutation].call(null, this.state, options)
  }

  dispatch(action, options) {
    const result = this.actions[action].call(null, {
      commit: this.commit.bind(this),
      state: this.state,
      dispatch: this.dispatch.bind(this)
    }, options)
    if (result && typeof result.then === 'function') {
      return result
    } else {
      return Promise.resolve(result)
    }
  }

  watch(getter, cb, options) {
    return this._watcherVM.$watch(() => getter(this.state, this.getters), cb, options)
  }

  replaceState(state) {
    this._vm._data.$$state = state
  }

  registerModule(path, rawModule) {
    this.state.route = rawModule
  }

}

function install(_Vue) {
  if (Vue || _Vue.isInstalled === true) return
  _Vue.isInstalled = true
  Vue = _Vue
  Vue.mixin({ beforeCreate: vuexInit })
}

const mapGetters = (getters) => {
  const res = {}
  getters.forEach(item => {
    res[item] = function() {
      const result = this.$store.getters[item]
      return result
    }
  })
  return res
}

function vuexInit() {
  const options = this.$options
  // store injection
  if (options.store) {
    this.$store = options.store
  } else if (options.parent && options.parent.$store) {
    this.$store = options.parent.$store
  }
}

export default {
  install,
  Store
}

export {
  mapGetters
}

function forEachValue(obj, fn) {
  Object.keys(obj).forEach(key => fn(obj[key], key))
}
<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash')
var moment = require('moment')

var request = require('./request')
var macros = require('./macros')

var BaseData = require('./BaseData')
var Meeting = require('./Meeting')

function Section(config) {
	BaseData.prototype.constructor.apply(this, arguments);
	if (!config._id && !(config.host && config.termId && config.subject && config.classId && config.crn)) {
		elog('ERROR section needs host, termId, subject, classId, crn or _id', config)
	};

	//loading status is done if any sign that has data
	if (config.dataStatus !== undefined) {
		this.dataStatus = config.dataStatus
	}
	else if (this.lastUpdateTime !== undefined || this.meetings) {
		this.dataStatus = macros.DATASTATUS_DONE
	}
	else {
		this.dataStatus = macros.DATASTATUS_NOTSTARTED
	}

	//start times of all non-exam meetings
	this.startTimesStrings = []

	//pointer to the class instance that contains this
	this.classInstance = null;

	//seperate reasons to meet: eg Lecture or Lab.
	//each of these then has times, and days
	this.meetings = []

	//Professors, eg ["Oana Veliche"]
	this.profs = []

	this.processServerData(config)

	//TODO remove this...
	this.weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
}

macros.inherent(BaseData, Section)

Section.requiredPath = ['host', 'termId', 'subject', 'classId']
Section.optionalPath = ['crn']
Section.API_ENDPOINT = '/listSections'

Section.prototype.meetsOnWeekends = function () {

	for (var i = 0; i < this.meetings.length; i++) {
		var meeting = this.meetings[i];

		if (meeting.getMeetsOnWeekends()) {
			return true;
		};
	}
	return false;
}

Section.prototype.getAllMeetingMoments = function(ignoreExams) {
	if (ignoreExams === undefined) {
		ignoreExams = true;
	};

	var retVal = [];
	this.meetings.forEach(function (meeting) {
		if (ignoreExams && meeting.getIsExam()) {
			return;
		}

		retVal = retVal.concat(_.flatten(meeting.times));
	}.bind(this))

	retVal.sort(function (a, b) {
		if (a.start.unix()> b.start.unix()) {
			return 1;
		}
		else if (a.start.unix() < b.start.unix()) {
			return -1;
		}
		else {
			return 0;
		}
	}.bind(this))

	return retVal;
};

//returns [false,true,false,true,false,true,false] if meeting mon, wed, fri
Section.prototype.getWeekDaysAsBooleans = function () {

	var retVal = [false, false, false, false, false, false, false];

	this.getAllMeetingMoments().forEach(function (time) {
		retVal[time.start.day()] = true;
	}.bind(this))

	return retVal;
};

Section.prototype.getWeekDaysAsStringArray = function () {

	var retVal = [];

	this.getAllMeetingMoments().forEach(function (time) {
		var day = time.start.format('dddd');
		if (_(retVal).includes(day)) {
			return;
		}
		retVal.push(day);
	}.bind(this))

	return retVal;
};

//returns true if has exam, else false
Section.prototype.getHasExam = function () {
	for (var i = 0; i < this.meetings.length; i++) {
		if (this.meetings[i].getIsExam()) {
			return true;
		}
	}
	return false;
};

//returns the {start:end:} moment object of the first exam found
//else returns null
Section.prototype.getExamMoments = function () {
	for (var i = 0; i < this.meetings.length; i++) {
		var meeting = this.meetings[i]
		if (meeting.getIsExam()) {
			if (meeting.times.length > 0) {
				return meeting.times[0][0];
			};
		};
	};
	return null;
};

Section.prototype.getProfs = function() {
	var retVal = [];
	this.meetings.forEach(function (meeting) {
		meeting.profs.forEach(function (prof) {
			if (!_(retVal).includes(prof)) {
				retVal.push(prof);
			};
		}.bind(this))
	}.bind(this))

	return retVal;
};

Section.prototype.getLocations = function(ignoreExams) {
	if (ignoreExams === undefined) {
		ignoreExams = true;
	};

	var retVal = [];
	this.meetings.forEach(function (meeting) {
		if (ignoreExams && meeting.getIsExam()) {
			return;
		};

		var where = meeting.where;
		if (!_(retVal).includes(where)) {
			retVal.push(where);
		};
	}.bind(this))
	return retVal;
};

Section.prototype.getUniqueStartTimes = function(ignoreExams) {
	if (ignoreExams === undefined) {
		ignoreExams = true;
	};

	var retVal = [];

	this.getAllMeetingMoments(ignoreExams).forEach(function (time) {
		var string = time.start.format('h:mm a');
		if (!_(retVal).includes(string)) {
			retVal.push(string)
		};
	}.bind(this))

	return retVal;
};

Section.prototype.getUniqueEndTimes = function(ignoreExams) {
	if (ignoreExams === undefined) {
		ignoreExams = true;
	};

	var retVal = [];

	this.getAllMeetingMoments(ignoreExams).forEach(function (time) {
		var string = time.end.format('h:mm a');
		if (!_(retVal).includes(string)) {
			retVal.push(string)
		};
	}.bind(this))

	return retVal;
};

// Network methods

Section.prototype.download = function (callback) {
	if (!callback) {
		callback = function () {}
	}

	BaseData.prototype.download.call(this, function (err) {
		if (err) {
			console.log("ERROR in list sections", err, this)
			return callback(err);
		}

		this.processServerData();

		callback(null, this)

	}.bind(this))
}

Section.prototype.processServerData = function () {

	var newMeetings = []

	this.meetings.forEach(function (serverData) {
		newMeetings.push(new Meeting(serverData))
	}.bind(this))

	this.meetings = newMeetings;
};

Section.prototype.compareTo = function (other) {

	if (this.meetings.length == 0 && other.meetings.length === 0) {
		return 0;
	}

	if (this.meetings[0].times.length === 0) {
		return 1;
	}
	if (other.meetings[0].times.length === 0) {
		return -1;
	}
	if (this.meetings[0].times[0][0].start.unix() < other.meetings[0].times[0][0].start.unix()) {
		return -1;
	}
	if (this.meetings[0].times[0][0].start.unix() > other.meetings[0].times[0][0].start.unix()) {
		return 1;
	}
	else {
		return 0;
	}
};

module.exports = Section;
<commit_msg>removed more old code<commit_after>'use strict';
var _ = require('lodash')
var moment = require('moment')

var request = require('./request')
var macros = require('./macros')

var BaseData = require('./BaseData')
var Meeting = require('./Meeting')

function Section(config) {
	BaseData.prototype.constructor.apply(this, arguments);
	if (!config._id && !(config.host && config.termId && config.subject && config.classId && config.crn)) {
		elog('ERROR section needs host, termId, subject, classId, crn or _id', config)
	};

	//loading status is done if any sign that has data
	if (config.dataStatus !== undefined) {
		this.dataStatus = config.dataStatus
	}
	else if (this.lastUpdateTime !== undefined || this.meetings) {
		this.dataStatus = macros.DATASTATUS_DONE
	}
	else {
		this.dataStatus = macros.DATASTATUS_NOTSTARTED
	}

	//start times of all non-exam meetings
	this.startTimesStrings = []

	//pointer to the class instance that contains this
	this.classInstance = null;

	//seperate reasons to meet: eg Lecture or Lab.
	//each of these then has times, and days
	this.meetings = []

	//Professors, eg ["Oana Veliche"]
	this.profs = []

	this.processServerData(config)
}

macros.inherent(BaseData, Section)

Section.requiredPath = ['host', 'termId', 'subject', 'classId']
Section.optionalPath = ['crn']
Section.API_ENDPOINT = '/listSections'

Section.prototype.meetsOnWeekends = function () {

	for (var i = 0; i < this.meetings.length; i++) {
		var meeting = this.meetings[i];

		if (meeting.getMeetsOnWeekends()) {
			return true;
		};
	}
	return false;
}

Section.prototype.getAllMeetingMoments = function(ignoreExams) {
	if (ignoreExams === undefined) {
		ignoreExams = true;
	};

	var retVal = [];
	this.meetings.forEach(function (meeting) {
		if (ignoreExams && meeting.getIsExam()) {
			return;
		}

		retVal = retVal.concat(_.flatten(meeting.times));
	}.bind(this))

	retVal.sort(function (a, b) {
		if (a.start.unix()> b.start.unix()) {
			return 1;
		}
		else if (a.start.unix() < b.start.unix()) {
			return -1;
		}
		else {
			return 0;
		}
	}.bind(this))

	return retVal;
};

//returns [false,true,false,true,false,true,false] if meeting mon, wed, fri
Section.prototype.getWeekDaysAsBooleans = function () {

	var retVal = [false, false, false, false, false, false, false];

	this.getAllMeetingMoments().forEach(function (time) {
		retVal[time.start.day()] = true;
	}.bind(this))

	return retVal;
};

Section.prototype.getWeekDaysAsStringArray = function () {

	var retVal = [];

	this.getAllMeetingMoments().forEach(function (time) {
		var day = time.start.format('dddd');
		if (_(retVal).includes(day)) {
			return;
		}
		retVal.push(day);
	}.bind(this))

	return retVal;
};

//returns true if has exam, else false
Section.prototype.getHasExam = function () {
	for (var i = 0; i < this.meetings.length; i++) {
		if (this.meetings[i].getIsExam()) {
			return true;
		}
	}
	return false;
};

//returns the {start:end:} moment object of the first exam found
//else returns null
Section.prototype.getExamMoments = function () {
	for (var i = 0; i < this.meetings.length; i++) {
		var meeting = this.meetings[i]
		if (meeting.getIsExam()) {
			if (meeting.times.length > 0) {
				return meeting.times[0][0];
			};
		};
	};
	return null;
};

Section.prototype.getProfs = function() {
	var retVal = [];
	this.meetings.forEach(function (meeting) {
		meeting.profs.forEach(function (prof) {
			if (!_(retVal).includes(prof)) {
				retVal.push(prof);
			};
		}.bind(this))
	}.bind(this))

	return retVal;
};

Section.prototype.getLocations = function(ignoreExams) {
	if (ignoreExams === undefined) {
		ignoreExams = true;
	};

	var retVal = [];
	this.meetings.forEach(function (meeting) {
		if (ignoreExams && meeting.getIsExam()) {
			return;
		};

		var where = meeting.where;
		if (!_(retVal).includes(where)) {
			retVal.push(where);
		};
	}.bind(this))
	return retVal;
};

Section.prototype.getUniqueStartTimes = function(ignoreExams) {
	if (ignoreExams === undefined) {
		ignoreExams = true;
	};

	var retVal = [];

	this.getAllMeetingMoments(ignoreExams).forEach(function (time) {
		var string = time.start.format('h:mm a');
		if (!_(retVal).includes(string)) {
			retVal.push(string)
		};
	}.bind(this))

	return retVal;
};

Section.prototype.getUniqueEndTimes = function(ignoreExams) {
	if (ignoreExams === undefined) {
		ignoreExams = true;
	};

	var retVal = [];

	this.getAllMeetingMoments(ignoreExams).forEach(function (time) {
		var string = time.end.format('h:mm a');
		if (!_(retVal).includes(string)) {
			retVal.push(string)
		};
	}.bind(this))

	return retVal;
};

// Network methods

Section.prototype.download = function (callback) {
	if (!callback) {
		callback = function () {}
	}

	BaseData.prototype.download.call(this, function (err) {
		if (err) {
			console.log("ERROR in list sections", err, this)
			return callback(err);
		}

		this.processServerData();

		callback(null, this)

	}.bind(this))
}

Section.prototype.processServerData = function () {

	var newMeetings = []

	this.meetings.forEach(function (serverData) {
		newMeetings.push(new Meeting(serverData))
	}.bind(this))

	this.meetings = newMeetings;
};

Section.prototype.compareTo = function (other) {

	if (this.meetings.length == 0 && other.meetings.length === 0) {
		return 0;
	}

	if (this.meetings[0].times.length === 0) {
		return 1;
	}
	if (other.meetings[0].times.length === 0) {
		return -1;
	}
	if (this.meetings[0].times[0][0].start.unix() < other.meetings[0].times[0][0].start.unix()) {
		return -1;
	}
	if (this.meetings[0].times[0][0].start.unix() > other.meetings[0].times[0][0].start.unix()) {
		return 1;
	}
	else {
		return 0;
	}
};

module.exports = Section;
<|endoftext|>