<commit_before>var listLayoutTemplate = require('./list/listLayout.html'),
    listTemplate = require ('./list/list.html'),
    showTemplate = require('./show/show.html'),
    createTemplate = require('./form/create.html'),
    editTemplate = require('./form/edit.html'),
    deleteTemplate = require('./delete/delete.html'),
    batchDeleteTemplate = require('./delete/batchDelete.html');

function templateProvider(viewName, defaultView) {
    return ['$stateParams', 'NgAdminConfiguration', function ($stateParams, Configuration) {
        var customTemplate;
        var view = Configuration().getViewByEntityAndType($stateParams.entity, viewName);
        customTemplate = view.template();
        if (customTemplate) return customTemplate;
        customTemplate = Configuration().customTemplate()(viewName);
        if (customTemplate) return customTemplate;
        return defaultView;
    }];
}

function viewProvider(viewName) {
    return ['$stateParams', 'NgAdminConfiguration', function ($stateParams, Configuration) {
        var view;
        try {
            view = Configuration().getViewByEntityAndType($stateParams.entity, viewName);
        } catch (e) {
            var error404 = new Error('Unknown view or entity name');
            error404.status = 404; // trigger the 404 error
            throw error404;
        }
        if (!view.enabled) {
            throw new Error('The ' + viewName + ' is disabled for this entity');
        }
        return view;
    }];
}

function dataStoreProvider() {
    return ['AdminDescription', function (AdminDescription) {
        return AdminDescription.getDataStore();
    }];
}

function routing($stateProvider) {

    $stateProvider
        .state('listLayout', {
            abstract: true,
            url: '/:entity/list',
            params: {
                entity: null
            },
            parent: 'main',
            controller: 'ListLayoutController',
            controllerAs: 'llCtrl',
            templateProvider: templateProvider('ListView', listLayoutTemplate),
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('ListView'),
                filterData: ['ReadQueries', 'view', function (ReadQueries, view) {
                    return ReadQueries.getAllReferencedData(view.getFilterReferences(false));
                }],
                filterEntries: ['dataStore', 'view', 'filterData', function (dataStore, view, filterData) {
                    var filters = view.getFilterReferences(false);
                    var filterEntries;

                    for (var name in filterData) {
                        filterEntries = dataStore.mapEntries(
                            filters[name].targetEntity().name(),
                            filters[name].targetEntity().identifier(),
                            [filters[name].targetField()],
                            filterData[name]
                        );

                        dataStore.setEntries(
                            filters[name].targetEntity().uniqueId + '_choices',
                            filterEntries
                        );
                    }

                    return true;
                }]
            }
        })
        .state('list', {
            url: '?{search:json}&page&sortField&sortDir',
            params: {
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            parent: 'listLayout',
            views: {
                grid: {
                    controller: 'ListController',
                    controllerAs: 'listController',
                    template: listTemplate,
                    resolve: {
                        dataStore: dataStoreProvider(),
                        view: viewProvider('ListView'),
                        response: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
                            var page = $stateParams.page,
                                filters = $stateParams.search,
                                sortField = $stateParams.sortField,
                                sortDir = $stateParams.sortDir;

                            return ReadQueries.getAll(view, page, filters, sortField, sortDir);
                        }],
                        totalItems: ['response', function (response) {
                            return response.totalItems;
                        }],
                        nonOptimizedReferencedData: ['ReadQueries', 'view', 'response', function (ReadQueries, view, response) {
                            return ReadQueries.getFilteredReferenceData(view.getNonOptimizedReferences(), response.data);
                        }],
                        optimizedReferencedData: ['ReadQueries', 'view', 'response', function (ReadQueries, view, response) {
                            return ReadQueries.getOptimizedReferencedData(view.getOptimizedReferences(), response.data);
                        }],
                        referencedEntries: ['dataStore', 'view', 'nonOptimizedReferencedData', 'optimizedReferencedData', function (dataStore, view, nonOptimizedReferencedData, optimizedReferencedData) {
                            var references = view.getReferences(),
                                referencedData = angular.extend(nonOptimizedReferencedData, optimizedReferencedData),
                                referencedEntries;

                            for (var name in referencedData) {
                                referencedEntries = dataStore.mapEntries(
                                    references[name].targetEntity().name(),
                                    references[name].targetEntity().identifier(),
                                    [references[name].targetField()],
                                    referencedData[name]
                                );

                                dataStore.setEntries(
                                    references[name].targetEntity().uniqueId + '_values',
                                    referencedEntries
                                );
                            }

                            return true;
                        }],
                        entries: ['dataStore', 'view', 'response', 'referencedEntries', function (dataStore, view, response, referencedEntries) {
                            var entries = dataStore.mapEntries(
                                view.entity.name(),
                                view.identifier(),
                                view.getFields(),
                                response.data
                            );

                            // shortcut to diplay collection of entry with included referenced values
                            dataStore.fillReferencesValuesFromCollection(entries, view.getReferences(), true);

                            // set entries here ???
                            dataStore.setEntries(
                                view.getEntity().uniqueId,
                                entries
                            );

                            return true;
                        }],
                    }
                }
            }
        });

    $stateProvider
        .state('show', {
            parent: 'main',
            url: '/:entity/show/:id?sortField&sortDir',
            controller: 'ShowController',
            controllerAs: 'showController',
            templateProvider: templateProvider('ShowView', showTemplate),
            params: {
                entity: null,
                id: null,
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('ShowView'),
                rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
                    return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
                }],
                entry: ['dataStore', 'view', 'rawEntry', function(dataStore, view, rawEntry) {
                    return dataStore.mapEntry(
                        view.entity.name(),
                        view.identifier(),
                        view.getFields(),
                        rawEntry
                    );
                }],
                nonOptimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
                    return ReadQueries.getFilteredReferenceData(view.getNonOptimizedReferences(), [entry.values]);
                }],
                optimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
                    return ReadQueries.getOptimizedReferencedData(view.getOptimizedReferences(), [entry.values]);
                }],
                referencedEntries: ['dataStore', 'view', 'nonOptimizedReferencedData', 'optimizedReferencedData', function (dataStore, view, nonOptimizedReferencedData, optimizedReferencedData) {
                    var references = view.getReferences(),
                        referencedData = angular.extend(nonOptimizedReferencedData, optimizedReferencedData),
                        referencedEntries;

                    for (var name in referencedData) {
                        referencedEntries = dataStore.mapEntries(
                            references[name].targetEntity().name(),
                            references[name].targetEntity().identifier(),
                            [references[name].targetField()],
                            referencedData[name]
                        );

                        dataStore.setEntries(
                            references[name].targetEntity().uniqueId + '_values',
                            referencedEntries
                        );
                    }

                    return true;
                }],
                referencedListData: ['$stateParams', 'ReadQueries', 'view', 'entry', function ($stateParams, ReadQueries, view, entry) {
                    var referencedLists = view.getReferencedLists();
                    var sortField = $stateParams.sortField;
                    var sortDir = $stateParams.sortDir;

                    return ReadQueries.getReferencedListData(referencedLists, sortField, sortDir, entry.identifierValue);
                }],
                referencedListEntries: ['dataStore', 'view', 'referencedListData', function (dataStore, view, referencedListData) {
                    var referencedLists = view.getReferencedLists();
                    var referencedList;
                    var referencedListEntries;

                    for (var i in referencedLists) {
                        referencedList = referencedLists[i];
                        referencedListEntries = referencedListData[i];

                        referencedListEntries = dataStore.mapEntries(
                            referencedList.targetEntity().name(),
                            referencedList.targetEntity().identifier(),
                            referencedList.targetFields(),
                            referencedListEntries
                        );

                        dataStore.setEntries(
                            referencedList.targetEntity().uniqueId + '_list',
                            referencedListEntries
                        );
                    }
                }],
                entryWithReferences: ['dataStore', 'view', 'entry', 'referencedEntries', function(dataStore, view, entry, referencedEntries) {
                    dataStore.fillReferencesValuesFromEntry(entry, view.getReferences(), true);

                    dataStore.addEntry(view.getEntity().uniqueId, entry);
                    return true;
                }]
            }
        });

    $stateProvider
        .state('create', {
            parent: 'main',
            url: '/:entity/create',
            controller: 'FormController',
            controllerAs: 'formController',
            templateProvider: templateProvider('CreateView', createTemplate),
            params: {
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('CreateView'),
                entry: ['dataStore', 'view', function (dataStore, view) {
                    var entry = dataStore.createEntry(view.entity.name(), view.identifier(), view.getFields());
                    dataStore.addEntry(view.getEntity().uniqueId, entry);

                    return entry;
                }],
                choiceData: ['ReadQueries', 'view', function (ReadQueries, view) {
                    return ReadQueries.getAllReferencedData(view.getReferences(false));
                }],
                choiceEntries: ['dataStore', 'view', 'choiceData', function (dataStore, view, filterData) {
                    var choices = view.getReferences(false);
                    var choiceEntries;

                    for (var name in filterData) {
                        choiceEntries = dataStore.mapEntries(
                            choices[name].targetEntity().name(),
                            choices[name].targetEntity().identifier(),
                            [choices[name].targetField()],
                            filterData[name]
                        );

                        dataStore.setEntries(
                            choices[name].targetEntity().uniqueId + '_choices',
                            choiceEntries
                        );
                    }

                    return true;
                }]
            }
        });

    $stateProvider
        .state('edit', {
            parent: 'main',
            url: '/:entity/edit/:id?sortField&sortDir',
            controller: 'FormController',
            controllerAs: 'formController',
            templateProvider: templateProvider('EditView', editTemplate),
            params: {
                entity: null,
                id: null,
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('EditView'),
                rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
                    return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
                }],
                entry: ['dataStore', 'view', 'rawEntry', function(dataStore, view, rawEntry) {
                    return dataStore.mapEntry(
                        view.entity.name(),
                        view.identifier(),
                        view.getFields(),
                        rawEntry
                    );
                }],
                nonOptimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
                    return ReadQueries.getFilteredReferenceData(view.getNonOptimizedReferences(), [entry.values]);
                }],
                optimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
                    return ReadQueries.getOptimizedReferencedData(view.getOptimizedReferences(), [entry.values]);
                }],
                referencedEntries: ['dataStore', 'view', 'nonOptimizedReferencedData', 'optimizedReferencedData', function (dataStore, view, nonOptimizedReferencedData, optimizedReferencedData) {
                    var references = view.getReferences(),
                        referencedData = angular.extend(nonOptimizedReferencedData, optimizedReferencedData),
                        referencedEntries;

                    for (var name in referencedData) {
                        referencedEntries = dataStore.mapEntries(
                            references[name].targetEntity().name(),
                            references[name].targetEntity().identifier(),
                            [references[name].targetField()],
                            referencedData[name]
                        );

                        dataStore.setEntries(
                            references[name].targetEntity().uniqueId + '_values',
                            referencedEntries
                        );
                    }

                    return true;
                }],
                referencedListData: ['$stateParams', 'ReadQueries', 'view', 'entry', function ($stateParams, ReadQueries, view, entry) {
                    var referencedLists = view.getReferencedLists();
                    var sortField = $stateParams.sortField;
                    var sortDir = $stateParams.sortDir;

                    return ReadQueries.getReferencedListData(referencedLists, sortField, sortDir, entry.identifierValue);
                }],
                referencedListEntries: ['dataStore', 'view', 'referencedListData', function (dataStore, view, referencedListData) {
                    var referencedLists = view.getReferencedLists();
                    var referencedList;
                    var referencedListEntries;

                    for (var i in referencedLists) {
                        referencedList = referencedLists[i];
                        referencedListEntries = referencedListData[i];

                        referencedListEntries = dataStore.mapEntries(
                            referencedList.targetEntity().name(),
                            referencedList.targetEntity().identifier(),
                            referencedList.targetFields(),
                            referencedListEntries
                        );

                        dataStore.setEntries(
                            referencedList.targetEntity().uniqueId + '_list',
                            referencedListEntries
                        );
                    }
                }],
                entryWithReferences: ['dataStore', 'view', 'entry', 'referencedEntries', function(dataStore, view, entry, referencedEntries) {
                    dataStore.fillReferencesValuesFromEntry(entry, view.getReferences(), true);

                    dataStore.addEntry(view.getEntity().uniqueId, entry);
                    return true;
                }],
                choiceData: ['ReadQueries', 'view', function (ReadQueries, view) {
                    return ReadQueries.getAllReferencedData(view.getReferences(false));
                }],
                choiceEntries: ['dataStore', 'view', 'choiceData', function (dataStore, view, filterData) {
                    var choices = view.getReferences(false);
                    var choiceEntries;

                    for (var name in filterData) {
                        choiceEntries = dataStore.mapEntries(
                            choices[name].targetEntity().name(),
                            choices[name].targetEntity().identifier(),
                            [choices[name].targetField()],
                            filterData[name]
                        );

                        dataStore.setEntries(
                            choices[name].targetEntity().uniqueId + '_choices',
                            choiceEntries
                        );
                    }

                    return true;
                }]
            }
        });

    $stateProvider
        .state('delete', {
            parent: 'main',
            url: '/:entity/delete/:id',
            controller: 'DeleteController',
            controllerAs: 'deleteController',
            templateProvider: templateProvider('DeleteView', deleteTemplate),
            params: {
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('DeleteView'),
                params: ['$stateParams', function ($stateParams) {
                    return $stateParams;
                }],
                rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
                    return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
                }],
                entry: ['dataStore', 'view', 'rawEntry', function(dataStore, view, rawEntry) {
                    return dataStore.mapEntry(
                        view.entity.name(),
                        view.identifier(),
                        view.getFields(),
                        rawEntry
                    );
                }],
            }
        });

    $stateProvider
        .state('batchDelete', {
            parent: 'main',
            url: '/:entity/batch-delete/{ids:json}',
            controller: 'BatchDeleteController',
            controllerAs: 'batchDeleteController',
            templateProvider: templateProvider('BatchDeleteView', batchDeleteTemplate),
            params: {
                entity: null,
                ids: [],
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                view: viewProvider('BatchDeleteView'),
                params: ['$stateParams', function ($stateParams) {
                    return $stateParams;
                }]
            }
        });
}

routing.$inject = ['$stateProvider'];

module.exports = routing;
<commit_msg>Prepare move of mapEntry from datastore to view<commit_after>var listLayoutTemplate = require('./list/listLayout.html'),
    listTemplate = require ('./list/list.html'),
    showTemplate = require('./show/show.html'),
    createTemplate = require('./form/create.html'),
    editTemplate = require('./form/edit.html'),
    deleteTemplate = require('./delete/delete.html'),
    batchDeleteTemplate = require('./delete/batchDelete.html');

function templateProvider(viewName, defaultView) {
    return ['$stateParams', 'NgAdminConfiguration', function ($stateParams, Configuration) {
        var customTemplate;
        var view = Configuration().getViewByEntityAndType($stateParams.entity, viewName);
        customTemplate = view.template();
        if (customTemplate) return customTemplate;
        customTemplate = Configuration().customTemplate()(viewName);
        if (customTemplate) return customTemplate;
        return defaultView;
    }];
}

function viewProvider(viewName) {
    return ['$stateParams', 'NgAdminConfiguration', function ($stateParams, Configuration) {
        var view;
        try {
            view = Configuration().getViewByEntityAndType($stateParams.entity, viewName);
        } catch (e) {
            var error404 = new Error('Unknown view or entity name');
            error404.status = 404; // trigger the 404 error
            throw error404;
        }
        if (!view.enabled) {
            throw new Error('The ' + viewName + ' is disabled for this entity');
        }
        return view;
    }];
}

function dataStoreProvider() {
    return ['AdminDescription', function (AdminDescription) {
        return AdminDescription.getDataStore();
    }];
}

function routing($stateProvider) {

    $stateProvider
        .state('listLayout', {
            abstract: true,
            url: '/:entity/list',
            params: {
                entity: null
            },
            parent: 'main',
            controller: 'ListLayoutController',
            controllerAs: 'llCtrl',
            templateProvider: templateProvider('ListView', listLayoutTemplate),
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('ListView'),
                filterData: ['ReadQueries', 'view', function (ReadQueries, view) {
                    return ReadQueries.getAllReferencedData(view.getFilterReferences(false));
                }],
                filterEntries: ['dataStore', 'view', 'filterData', function (dataStore, view, filterData) {
                    var filters = view.getFilterReferences(false);
                    var filterEntries;

                    for (var name in filterData) {
                        filterEntries = dataStore.mapEntries(
                            filters[name].targetEntity().name(),
                            filters[name].targetEntity().identifier(),
                            [filters[name].targetField()],
                            filterData[name]
                        );

                        dataStore.setEntries(
                            filters[name].targetEntity().uniqueId + '_choices',
                            filterEntries
                        );
                    }

                    return true;
                }]
            }
        })
        .state('list', {
            url: '?{search:json}&page&sortField&sortDir',
            params: {
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            parent: 'listLayout',
            views: {
                grid: {
                    controller: 'ListController',
                    controllerAs: 'listController',
                    template: listTemplate,
                    resolve: {
                        dataStore: dataStoreProvider(),
                        view: viewProvider('ListView'),
                        response: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
                            var page = $stateParams.page,
                                filters = $stateParams.search,
                                sortField = $stateParams.sortField,
                                sortDir = $stateParams.sortDir;

                            return ReadQueries.getAll(view, page, filters, sortField, sortDir);
                        }],
                        totalItems: ['response', function (response) {
                            return response.totalItems;
                        }],
                        nonOptimizedReferencedData: ['ReadQueries', 'view', 'response', function (ReadQueries, view, response) {
                            return ReadQueries.getFilteredReferenceData(view.getNonOptimizedReferences(), response.data);
                        }],
                        optimizedReferencedData: ['ReadQueries', 'view', 'response', function (ReadQueries, view, response) {
                            return ReadQueries.getOptimizedReferencedData(view.getOptimizedReferences(), response.data);
                        }],
                        referencedEntries: ['dataStore', 'view', 'nonOptimizedReferencedData', 'optimizedReferencedData', function (dataStore, view, nonOptimizedReferencedData, optimizedReferencedData) {
                            var references = view.getReferences(),
                                referencedData = angular.extend(nonOptimizedReferencedData, optimizedReferencedData),
                                referencedEntries;

                            for (var name in referencedData) {
                                referencedEntries = dataStore.mapEntries(
                                    references[name].targetEntity().name(),
                                    references[name].targetEntity().identifier(),
                                    [references[name].targetField()],
                                    referencedData[name]
                                );

                                dataStore.setEntries(
                                    references[name].targetEntity().uniqueId + '_values',
                                    referencedEntries
                                );
                            }

                            return true;
                        }],
                        entries: ['dataStore', 'view', 'response', 'referencedEntries', function (dataStore, view, response, referencedEntries) {
                            var entries = view.mapEntries(response.data);

                            // shortcut to diplay collection of entry with included referenced values
                            dataStore.fillReferencesValuesFromCollection(entries, view.getReferences(), true);

                            // set entries here ???
                            dataStore.setEntries(
                                view.getEntity().uniqueId,
                                entries
                            );

                            return true;
                        }],
                    }
                }
            }
        });

    $stateProvider
        .state('show', {
            parent: 'main',
            url: '/:entity/show/:id?sortField&sortDir',
            controller: 'ShowController',
            controllerAs: 'showController',
            templateProvider: templateProvider('ShowView', showTemplate),
            params: {
                entity: null,
                id: null,
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('ShowView'),
                rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
                    return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
                }],
                entry: ['view', 'rawEntry', function(view, rawEntry) {
                    return view.mapEntry(rawEntry);
                }],
                nonOptimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
                    return ReadQueries.getFilteredReferenceData(view.getNonOptimizedReferences(), [entry.values]);
                }],
                optimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
                    return ReadQueries.getOptimizedReferencedData(view.getOptimizedReferences(), [entry.values]);
                }],
                referencedEntries: ['dataStore', 'view', 'nonOptimizedReferencedData', 'optimizedReferencedData', function (dataStore, view, nonOptimizedReferencedData, optimizedReferencedData) {
                    var references = view.getReferences(),
                        referencedData = angular.extend(nonOptimizedReferencedData, optimizedReferencedData),
                        referencedEntries;

                    for (var name in referencedData) {
                        referencedEntries = dataStore.mapEntries(
                            references[name].targetEntity().name(),
                            references[name].targetEntity().identifier(),
                            [references[name].targetField()],
                            referencedData[name]
                        );

                        dataStore.setEntries(
                            references[name].targetEntity().uniqueId + '_values',
                            referencedEntries
                        );
                    }

                    return true;
                }],
                referencedListData: ['$stateParams', 'ReadQueries', 'view', 'entry', function ($stateParams, ReadQueries, view, entry) {
                    var referencedLists = view.getReferencedLists();
                    var sortField = $stateParams.sortField;
                    var sortDir = $stateParams.sortDir;

                    return ReadQueries.getReferencedListData(referencedLists, sortField, sortDir, entry.identifierValue);
                }],
                referencedListEntries: ['dataStore', 'view', 'referencedListData', function (dataStore, view, referencedListData) {
                    var referencedLists = view.getReferencedLists();
                    var referencedList;
                    var referencedListEntries;

                    for (var i in referencedLists) {
                        referencedList = referencedLists[i];
                        referencedListEntries = referencedListData[i];

                        referencedListEntries = dataStore.mapEntries(
                            referencedList.targetEntity().name(),
                            referencedList.targetEntity().identifier(),
                            referencedList.targetFields(),
                            referencedListEntries
                        );

                        dataStore.setEntries(
                            referencedList.targetEntity().uniqueId + '_list',
                            referencedListEntries
                        );
                    }
                }],
                entryWithReferences: ['dataStore', 'view', 'entry', 'referencedEntries', function(dataStore, view, entry, referencedEntries) {
                    dataStore.fillReferencesValuesFromEntry(entry, view.getReferences(), true);

                    dataStore.addEntry(view.getEntity().uniqueId, entry);
                    return true;
                }]
            }
        });

    $stateProvider
        .state('create', {
            parent: 'main',
            url: '/:entity/create',
            controller: 'FormController',
            controllerAs: 'formController',
            templateProvider: templateProvider('CreateView', createTemplate),
            params: {
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('CreateView'),
                entry: ['dataStore', 'view', function (dataStore, view) {
                    var entry = dataStore.createEntry(view.entity.name(), view.identifier(), view.getFields());
                    dataStore.addEntry(view.getEntity().uniqueId, entry);

                    return entry;
                }],
                choiceData: ['ReadQueries', 'view', function (ReadQueries, view) {
                    return ReadQueries.getAllReferencedData(view.getReferences(false));
                }],
                choiceEntries: ['dataStore', 'view', 'choiceData', function (dataStore, view, filterData) {
                    var choices = view.getReferences(false);
                    var choiceEntries;

                    for (var name in filterData) {
                        choiceEntries = dataStore.mapEntries(
                            choices[name].targetEntity().name(),
                            choices[name].targetEntity().identifier(),
                            [choices[name].targetField()],
                            filterData[name]
                        );

                        dataStore.setEntries(
                            choices[name].targetEntity().uniqueId + '_choices',
                            choiceEntries
                        );
                    }

                    return true;
                }]
            }
        });

    $stateProvider
        .state('edit', {
            parent: 'main',
            url: '/:entity/edit/:id?sortField&sortDir',
            controller: 'FormController',
            controllerAs: 'formController',
            templateProvider: templateProvider('EditView', editTemplate),
            params: {
                entity: null,
                id: null,
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('EditView'),
                rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
                    return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
                }],
                entry: ['view', 'rawEntry', function(view, rawEntry) {
                    return view.mapEntry(rawEntry);
                }],
                nonOptimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
                    return ReadQueries.getFilteredReferenceData(view.getNonOptimizedReferences(), [entry.values]);
                }],
                optimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
                    return ReadQueries.getOptimizedReferencedData(view.getOptimizedReferences(), [entry.values]);
                }],
                referencedEntries: ['dataStore', 'view', 'nonOptimizedReferencedData', 'optimizedReferencedData', function (dataStore, view, nonOptimizedReferencedData, optimizedReferencedData) {
                    var references = view.getReferences(),
                        referencedData = angular.extend(nonOptimizedReferencedData, optimizedReferencedData),
                        referencedEntries;

                    for (var name in referencedData) {
                        referencedEntries = dataStore.mapEntries(
                            references[name].targetEntity().name(),
                            references[name].targetEntity().identifier(),
                            [references[name].targetField()],
                            referencedData[name]
                        );

                        dataStore.setEntries(
                            references[name].targetEntity().uniqueId + '_values',
                            referencedEntries
                        );
                    }

                    return true;
                }],
                referencedListData: ['$stateParams', 'ReadQueries', 'view', 'entry', function ($stateParams, ReadQueries, view, entry) {
                    var referencedLists = view.getReferencedLists();
                    var sortField = $stateParams.sortField;
                    var sortDir = $stateParams.sortDir;

                    return ReadQueries.getReferencedListData(referencedLists, sortField, sortDir, entry.identifierValue);
                }],
                referencedListEntries: ['dataStore', 'view', 'referencedListData', function (dataStore, view, referencedListData) {
                    var referencedLists = view.getReferencedLists();
                    var referencedList;
                    var referencedListEntries;

                    for (var i in referencedLists) {
                        referencedList = referencedLists[i];
                        referencedListEntries = referencedListData[i];

                        referencedListEntries = dataStore.mapEntries(
                            referencedList.targetEntity().name(),
                            referencedList.targetEntity().identifier(),
                            referencedList.targetFields(),
                            referencedListEntries
                        );

                        dataStore.setEntries(
                            referencedList.targetEntity().uniqueId + '_list',
                            referencedListEntries
                        );
                    }
                }],
                entryWithReferences: ['dataStore', 'view', 'entry', 'referencedEntries', function(dataStore, view, entry, referencedEntries) {
                    dataStore.fillReferencesValuesFromEntry(entry, view.getReferences(), true);

                    dataStore.addEntry(view.getEntity().uniqueId, entry);
                    return true;
                }],
                choiceData: ['ReadQueries', 'view', function (ReadQueries, view) {
                    return ReadQueries.getAllReferencedData(view.getReferences(false));
                }],
                choiceEntries: ['dataStore', 'view', 'choiceData', function (dataStore, view, filterData) {
                    var choices = view.getReferences(false);
                    var choiceEntries;

                    for (var name in filterData) {
                        choiceEntries = dataStore.mapEntries(
                            choices[name].targetEntity().name(),
                            choices[name].targetEntity().identifier(),
                            [choices[name].targetField()],
                            filterData[name]
                        );

                        dataStore.setEntries(
                            choices[name].targetEntity().uniqueId + '_choices',
                            choiceEntries
                        );
                    }

                    return true;
                }]
            }
        });

    $stateProvider
        .state('delete', {
            parent: 'main',
            url: '/:entity/delete/:id',
            controller: 'DeleteController',
            controllerAs: 'deleteController',
            templateProvider: templateProvider('DeleteView', deleteTemplate),
            params: {
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                dataStore: dataStoreProvider(),
                view: viewProvider('DeleteView'),
                params: ['$stateParams', function ($stateParams) {
                    return $stateParams;
                }],
                rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
                    return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
                }],
                entry: ['view', 'rawEntry', function(view, rawEntry) {
                    return view.mapEntry(rawEntry);
                }],
            }
        });

    $stateProvider
        .state('batchDelete', {
            parent: 'main',
            url: '/:entity/batch-delete/{ids:json}',
            controller: 'BatchDeleteController',
            controllerAs: 'batchDeleteController',
            templateProvider: templateProvider('BatchDeleteView', batchDeleteTemplate),
            params: {
                entity: null,
                ids: [],
                page: null,
                search: null,
                sortField: null,
                sortDir: null
            },
            resolve: {
                view: viewProvider('BatchDeleteView'),
                params: ['$stateParams', function ($stateParams) {
                    return $stateParams;
                }]
            }
        });
}

routing.$inject = ['$stateProvider'];

module.exports = routing;
<|endoftext|>


<commit_before>angular.module('n52.core.legend')
    .component('swcLabelMapper', {
        bindings: {
            label: '<'
        },
        templateUrl: 'n52.core.legend.label-mapper',
        controller: ['$http', '$q', 'labelMapperSrvc',
            function($http, $q, labelMapperSrvc) {
                this.$onInit = function() {
                    labelMapperSrvc.getMappedLabel(this.label).then((label) => {
                        this.determinedLabel = label;
                    });
                };
            }
        ]
    })
    .service('labelMapperSrvc', ['$q', '$http', 'settingsService',
        function($q, $http, settingsService) {

            var findUrls = function(text) {
                var source = (text || '').toString();
                var urlArray = [];
                var url;
                var matchArray;
                var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?&\/\/=]+)/g;
                while ((matchArray = regexToken.exec(source)) !== null) {
                    var token = matchArray[0];
                    urlArray.push(token);
                }
                return urlArray;
            };

            this.getMappedLabel = function(label) {
                return $q(function(resolve, reject) {
                    if (!settingsService.solveLabels) {
                        resolve(label);
                    }
                    var urls = findUrls(label);
                    if (urls.length > 0) {
                        var request = [];
                        urls.forEach((url) => {
                            labelUrl = settingsService.proxyUrl ? settingsService.proxyUrl + url : url;
                            request.push($http.get(labelUrl, {
                                cache: true
                            }).then((response) => {
                                var xml = jQuery.parseXML(response.data);
                                label = label.replace(url, $(xml).find('prefLabel').text());
                            }, (error) => {}));
                        });
                        $q.all(request).then(() => {
                            resolve(label);
                        });
                    } else {
                        resolve(label);
                    }
                });
            };
        }
    ]);
<commit_msg>update label mapper<commit_after>angular.module('n52.core.legend')
    .component('swcLabelMapper', {
        bindings: {
            label: '<'
        },
        templateUrl: 'n52.core.legend.label-mapper',
        controller: ['$http', '$q', 'labelMapperSrvc',
            function($http, $q, labelMapperSrvc) {
                this.$onInit = function() {
                    labelMapperSrvc.getMappedLabel(this.label).then((label) => {
                        this.determinedLabel = label;
                    });
                };
            }
        ]
    })
    .service('labelMapperSrvc', ['$q', '$http', 'settingsService',
        function($q, $http, settingsService) {

            var findUrls = function(text) {
                var source = (text || '').toString();
                var urlArray = [];
                var url;
                var matchArray;
                var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?&\/\/=]+)/g;
                while ((matchArray = regexToken.exec(source)) !== null) {
                    var token = matchArray[0];
                    urlArray.push(token);
                }
                return urlArray;
            };

            this.getMappedLabel = function(label) {
                return $q(function(resolve, reject) {
                    if (!settingsService.solveLabels) {
                        resolve(label);
                    } else {
                        var urls = findUrls(label);
                        if (urls.length > 0) {
                            var request = [];
                            urls.forEach((url) => {
                                labelUrl = settingsService.proxyUrl ? settingsService.proxyUrl + url : url;
                                request.push($http.get(labelUrl, {
                                    cache: true
                                }).then((response) => {
                                    var xml = jQuery.parseXML(response.data);
                                    label = label.replace(url, $(xml).find('prefLabel').text());
                                }, (error) => {}));
                            });
                            $q.all(request).then(() => {
                                resolve(label);
                            });
                        } else {
                            resolve(label);
                        }
                    }
                });
            };
        }
    ]);
<|endoftext|>


<commit_before>app.service('DashboardServices', function($q, $http){
  var mockData =
  [
      {
        "host":"elgervanboxtel.nl",
        "errordata": [
        {
          "errorComponent":"RegisterController.js",
          "line":23,
          "column":64,
          "ip":"206.45.67.30",
          "occurrences":1523
        },{
          "errorComponent":"RegisterController.js",
          "line":128,
          "column":99,
          "ip":"127.0.0.1",
          "occurrences":1478
        },{
          "errorComponent":"RegisterController.js",
          "line":542,
          "column":33,
          "ip":"172.56.52.13",
          "occurrences":892
        },{
          "errorComponent":"app.js",
          "line":150,
          "column":30,
          "ip":"127.0.0.1",
          "occurrences":253
        },{
          "errorComponent":"LoginController.js",
          "line":1501,
          "column":20,
          "ip":"82.26.64.3",
          "occurrences":240
        },{
          "errorComponent":"RegisterController.js",
          "line":88,
          "column":126,
          "ip":"72.62.84.2",
          "occurrences":55
        },{
          "errorComponent":"RegisterController.js",
          "line":23,
          "column":64,
          "ip":"98.26.35.2",
          "occurrences":12
        }]
      },
      {
        "host":"wouterroosendaal.nl",
        "errordata": [
        {
          "errorComponent":"TargetController.js",
          "line":16,
          "column":44,
          "ip":"206.45.67.30",
          "occurrences":1409
        },{
          "errorComponent":"TargetController.js",
          "line":222,
          "column":69,
          "ip":"127.0.0.1",
          "occurrences":1253
        },{
          "errorComponent":"TargetController.js",
          "line":857,
          "column":82,
          "ip":"172.56.52.13",
          "occurrences":398
        },{
          "errorComponent":"app.js",
          "line":150,
          "column":30,
          "ip":"127.0.0.1",
          "occurrences":309
        },{
          "errorComponent":"app.js",
          "line":1501,
          "column":20,
          "ip":"82.26.64.3",
          "occurrences":210
        },{
          "errorComponent":"MockService.js",
          "line":88,
          "column":126,
          "ip":"72.62.84.2",
          "occurrences":109
        },{
          "errorComponent":"MockService.js",
          "line":23,
          "column":64,
          "ip":"98.26.35.2",
          "occurrences":94
        }]
      },
      {
        "host":"tuvok.nl",
        "errordata": [
        {
          "errorComponent":"StarfleetController.js",
          "line":76,
          "column":12,
          "ip":"206.45.67.30",
          "occurrences":1809
        },{
          "errorComponent":"StarfleetController.js",
          "line":45,
          "column":21,
          "ip":"127.0.0.1",
          "occurrences":1478
        },{
          "errorComponent":"StarfleetController.js",
          "line":35,
          "column":12,
          "ip":"172.56.52.13",
          "occurrences":1209
        },{
          "errorComponent":"app.js",
          "line":76,
          "column":45,
          "ip":"127.0.0.1",
          "occurrences":987
        },{
          "errorComponent":"LoginController.js",
          "line":12,
          "column":33,
          "ip":"82.26.64.3",
          "occurrences":876
        },{
          "errorComponent":"StarfleetController.js",
          "line":66,
          "column":67,
          "ip":"72.62.84.2",
          "occurrences":654
        },{
          "errorComponent":"StarfleetController.js",
          "line":12,
          "column":123,
          "ip":"98.26.35.2",
          "occurrences":43
        }]
      }
  ],
  /**
   * Returns all domains which the current user is registered to
   */
  getMockHosts = function(){
    return $q(function(resolve, reject) {
      var mockHosts = [];
      for (var i = 0; i < mockData.length; i++) {
        mockHosts.push({"host": mockData[i].host});
      }
      // mock a return object as retrieved from api
      var returnobject = {};
      returnobject.data = {};
      returnobject.data.hosts = mockHosts;
      resolve(returnobject);
    });
  },
  getMockData = function(host) {
    return $q(function(resolve, reject) {
      for (var i = 0; i < mockData.length; i++) {
        if (mockData[i].host === host) {
          // mock a return object as retrieved from api
          var returnobject = {};
          returnobject.data = {};
          returnobject.data.errordata = mockData[i].errordata;
          resolve(returnobject);
        }
      }
    });
  },
  getHosts = function() {
    return $http.get('/api/host');
  },
  getData = function(host) {
    return $http.get('/api/data/forhost', {"host": host});
  };
  return {
    getData:getData,
    getHosts:getHosts
  };

});<commit_msg>Use correct get request for error data per host<commit_after>app.service('DashboardServices', function($q, $http){
  var mockData =
  [
      {
        "host":"elgervanboxtel.nl",
        "errordata": [
        {
          "errorComponent":"RegisterController.js",
          "line":23,
          "column":64,
          "ip":"206.45.67.30",
          "occurrences":1523
        },{
          "errorComponent":"RegisterController.js",
          "line":128,
          "column":99,
          "ip":"127.0.0.1",
          "occurrences":1478
        },{
          "errorComponent":"RegisterController.js",
          "line":542,
          "column":33,
          "ip":"172.56.52.13",
          "occurrences":892
        },{
          "errorComponent":"app.js",
          "line":150,
          "column":30,
          "ip":"127.0.0.1",
          "occurrences":253
        },{
          "errorComponent":"LoginController.js",
          "line":1501,
          "column":20,
          "ip":"82.26.64.3",
          "occurrences":240
        },{
          "errorComponent":"RegisterController.js",
          "line":88,
          "column":126,
          "ip":"72.62.84.2",
          "occurrences":55
        },{
          "errorComponent":"RegisterController.js",
          "line":23,
          "column":64,
          "ip":"98.26.35.2",
          "occurrences":12
        }]
      },
      {
        "host":"wouterroosendaal.nl",
        "errordata": [
        {
          "errorComponent":"TargetController.js",
          "line":16,
          "column":44,
          "ip":"206.45.67.30",
          "occurrences":1409
        },{
          "errorComponent":"TargetController.js",
          "line":222,
          "column":69,
          "ip":"127.0.0.1",
          "occurrences":1253
        },{
          "errorComponent":"TargetController.js",
          "line":857,
          "column":82,
          "ip":"172.56.52.13",
          "occurrences":398
        },{
          "errorComponent":"app.js",
          "line":150,
          "column":30,
          "ip":"127.0.0.1",
          "occurrences":309
        },{
          "errorComponent":"app.js",
          "line":1501,
          "column":20,
          "ip":"82.26.64.3",
          "occurrences":210
        },{
          "errorComponent":"MockService.js",
          "line":88,
          "column":126,
          "ip":"72.62.84.2",
          "occurrences":109
        },{
          "errorComponent":"MockService.js",
          "line":23,
          "column":64,
          "ip":"98.26.35.2",
          "occurrences":94
        }]
      },
      {
        "host":"tuvok.nl",
        "errordata": [
        {
          "errorComponent":"StarfleetController.js",
          "line":76,
          "column":12,
          "ip":"206.45.67.30",
          "occurrences":1809
        },{
          "errorComponent":"StarfleetController.js",
          "line":45,
          "column":21,
          "ip":"127.0.0.1",
          "occurrences":1478
        },{
          "errorComponent":"StarfleetController.js",
          "line":35,
          "column":12,
          "ip":"172.56.52.13",
          "occurrences":1209
        },{
          "errorComponent":"app.js",
          "line":76,
          "column":45,
          "ip":"127.0.0.1",
          "occurrences":987
        },{
          "errorComponent":"LoginController.js",
          "line":12,
          "column":33,
          "ip":"82.26.64.3",
          "occurrences":876
        },{
          "errorComponent":"StarfleetController.js",
          "line":66,
          "column":67,
          "ip":"72.62.84.2",
          "occurrences":654
        },{
          "errorComponent":"StarfleetController.js",
          "line":12,
          "column":123,
          "ip":"98.26.35.2",
          "occurrences":43
        }]
      }
  ],
  /**
   * Returns all domains which the current user is registered to
   */
  getMockHosts = function(){
    return $q(function(resolve, reject) {
      var mockHosts = [];
      for (var i = 0; i < mockData.length; i++) {
        mockHosts.push({"host": mockData[i].host});
      }
      // mock a return object as retrieved from api
      var returnobject = {};
      returnobject.data = {};
      returnobject.data.hosts = mockHosts;
      resolve(returnobject);
    });
  },
  getMockData = function(host) {
    return $q(function(resolve, reject) {
      for (var i = 0; i < mockData.length; i++) {
        if (mockData[i].host === host) {
          // mock a return object as retrieved from api
          var returnobject = {};
          returnobject.data = {};
          returnobject.data.errordata = mockData[i].errordata;
          resolve(returnobject);
        }
      }
    });
  },
  getHosts = function() {
    return $http.get('/api/host');
  },
  getData = function(host) {
    return $http.get('/api/data/forhost', {
      params: { name: host }
    });
  };
  return {
    getData:getData,
    getHosts:getHosts
  };

});<|endoftext|>


<commit_before>import React, {
  useRef,
  forwardRef,
  useContext,
  useEffect,
  useMemo,
  useState,
  useCallback,
} from 'react';
import { ThemeContext } from 'styled-components';
import { Calendar as CalendarIcon } from 'grommet-icons/icons/Calendar';
import { defaultProps } from '../../default-props';
import { AnnounceContext } from '../../contexts/AnnounceContext';
import { MessageContext } from '../../contexts/MessageContext';
import { Box } from '../Box';
import { Button } from '../Button';
import { Calendar } from '../Calendar';
import { Drop } from '../Drop';
import { DropButton } from '../DropButton';
import { FormContext } from '../Form';
import { Keyboard } from '../Keyboard';
import { MaskedInput } from '../MaskedInput';
import { useForwardedRef } from '../../utils';
import { getTimestamp, normalizeForTimezone } from '../Calendar/utils';
import {
  formatToSchema,
  schemaToMask,
  valuesAreEqual,
  valueToText,
  textToValue,
} from './utils';
import { DateInputPropTypes } from './propTypes';

const DateInput = forwardRef(
  (
    {
      buttonProps, // when no format and not inline
      calendarProps,
      defaultValue,
      disabled,
      dropProps, // when inline isn't true
      format,
      id,
      icon,
      inline = false,
      inputProps, // for MaskedInput, when format is specified
      name,
      onChange,
      onFocus,
      plain,
      value: valueArg,
      messages,
      ...rest
    },
    refArg,
  ) => {
    const theme = useContext(ThemeContext) || defaultProps.theme;
    const announce = useContext(AnnounceContext);
    const { format: formatMessage } = useContext(MessageContext);
    const iconSize =
      (theme.dateInput.icon && theme.dateInput.icon.size) || 'medium';
    const { useFormInput } = useContext(FormContext);
    const ref = useForwardedRef(refArg);
    const containerRef = useRef();
    const [value, setValue] = useFormInput({
      name,
      value: valueArg,
      initialValue: defaultValue,
    });

    const timestamp = useMemo(() => {
      if (Array.isArray(defaultValue) && defaultValue.length)
        return getTimestamp(defaultValue[0]);
      if (typeof defaultValue === 'string') return getTimestamp(defaultValue);
      if (Array.isArray(value) && value.length) return getTimestamp(value[0]);
      // check to see if value is not an empty string
      // empty string should behave like undefined
      if (typeof value === 'string' && value.length) return getTimestamp(value);
      return undefined;
    }, [defaultValue, value]);

    // whether or not we should normalize the date based on the timestamp.
    // will be set to false if the initial timestamp is undefined (meaning
    // a user did not provide a defaultValue or value). in this case, we
    // will just rely on the UTC timestamp and don't need to normalize.
    const [normalize, setNormalize] = useState(true);

    // normalize value based on timestamp vs user's local timezone
    const normalizedDate = normalizeForTimezone(value, timestamp, normalize);
    // do we expect multiple dates?
    const range = Array.isArray(value) || (format && format.includes('-'));

    // parse format and build a formal schema we can use elsewhere
    const schema = useMemo(() => formatToSchema(format), [format]);

    // mask is only used when a format is provided
    const mask = useMemo(() => schemaToMask(schema), [schema]);

    // textValue is only used when a format is provided
    const [textValue, setTextValue] = useState(
      schema ? valueToText(normalizedDate, schema) : undefined,
    );

    // Setting the icon through `inputProps` is deprecated.
    // The `icon` prop should be used instead.
    const { icon: MaskedInputIcon, ...restOfInputProps } = inputProps || {};
    if (MaskedInputIcon) {
      console.warn(
        `Customizing the DateInput icon through inputProps is deprecated.
Use the icon prop instead.`,
      );
    }

    // We need to distinguish between the caller changing a Form value
    // and the user typing a date that he isn't finished with yet.
    // To handle this, we see if we have a value and the text value
    // associated with it doesn't align to it, then we update the text value.
    // We compare using textToValue to avoid "06/01/2021" not
    // matching "06/1/2021".
    useEffect(() => {
      if (schema && value !== undefined) {
        const nextTextValue = valueToText(normalizedDate, schema);
        if (
          !valuesAreEqual(
            textToValue(textValue, schema, range, timestamp),
            textToValue(nextTextValue, schema, range, timestamp),
          ) ||
          (textValue === '' && nextTextValue !== '')
        ) {
          setTextValue(nextTextValue);
        }
      }
    }, [range, schema, textValue, value, normalizedDate, timestamp]);

    // when format and not inline, whether to show the Calendar in a Drop
    const [open, setOpen] = useState();

    const openCalendar = useCallback(() => {
      setOpen(true);
      announce(formatMessage({ id: 'dateInput.enterCalendar', messages }));
    }, [announce, formatMessage, messages]);

    const closeCalendar = useCallback(() => {
      setOpen(false);
      announce(formatMessage({ id: 'dateInput.exitCalendar', messages }));
    }, [announce, formatMessage, messages]);

    const calendar = (
      <Calendar
        ref={inline ? ref : undefined}
        id={inline && !format ? id : undefined}
        range={range}
        date={range ? undefined : normalizedDate}
        // when caller initializes with empty array, dates should be undefined
        // allowing the user to select both begin and end of the range
        dates={range && value.length ? [normalizedDate] : undefined}
        // places focus on days grid when Calendar opens
        initialFocus={open ? 'days' : undefined}
        normalize={normalize}
        onSelect={
          disabled
            ? undefined
            : (nextValue) => {
                let normalizedValue;
                if (range && Array.isArray(nextValue))
                  [normalizedValue] = nextValue;
                // clicking an edge date removes it
                else if (range) normalizedValue = [nextValue, nextValue];
                else normalizedValue = nextValue;
                // timestamp will be undefined if no defaultValue or value have
                // been passed in, indicating that we should stay local if the
                // user first picks a date via the Calendar.
                let nextNormalize = normalize;
                if (timestamp === undefined) {
                  nextNormalize = false;
                  setNormalize(nextNormalize);
                }
                if (schema)
                  setTextValue(
                    valueToText(
                      normalizeForTimezone(
                        normalizedValue,
                        undefined,
                        nextNormalize,
                      ),
                      schema,
                    ),
                  );
                setValue(normalizedValue);
                if (onChange) onChange({ value: normalizedValue });
                if (open && !range) {
                  closeCalendar();
                  setTimeout(() => ref.current.focus(), 1);
                }
              }
        }
        {...{ ...calendarProps, timestamp }}
      />
    );

    const formContextValue = useMemo(
      () => ({
        useFormInput: ({ value: valueProp }) => [valueProp, () => {}],
      }),
      [],
    );

    if (!format) {
      // When no format is specified, we don't give the user a way to type
      if (inline) return calendar;

      return (
        <DropButton
          ref={ref}
          id={id}
          dropProps={{ align: { top: 'bottom', left: 'left' }, ...dropProps }}
          dropContent={calendar}
          icon={icon || MaskedInputIcon || <CalendarIcon size={iconSize} />}
          {...buttonProps}
        />
      );
    }

    const input = (
      <FormContext.Provider
        key="input"
        // don't let MaskedInput drive the Form
        value={formContextValue}
      >
        <Keyboard
          onEsc={open ? () => closeCalendar() : undefined}
          onSpace={openCalendar}
        >
          <Box
            ref={containerRef}
            border={!plain}
            round="xxsmall"
            direction="row"
            fill
          >
            <MaskedInput
              ref={ref}
              id={id}
              name={name}
              reverse
              disabled={disabled}
              mask={mask}
              plain
              {...restOfInputProps}
              {...rest}
              value={textValue}
              onChange={(event) => {
                const nextTextValue = event.target.value;
                setTextValue(nextTextValue);

                let localTimestamp;
                // get the UTC timestamp relative to the user's timezone
                // once a date is complete
                if (timestamp === undefined && Date.parse(nextTextValue))
                  [, localTimestamp] = new Date(nextTextValue)
                    .toISOString()
                    .split('T');

                // timestamp will be undefined if no defaultValue or value have
                // been passed in, indicating that we should stay local
                let nextNormalize = normalize;
                if (timestamp === undefined) {
                  nextNormalize = false;
                  setNormalize(nextNormalize);
                }
                const nextValue = textToValue(
                  nextTextValue,
                  schema,
                  range,
                  timestamp || localTimestamp,
                  nextNormalize,
                );

                // reset to original state
                if (nextValue === undefined) setNormalize(true);
                // update value even when undefined
                setValue(nextValue);
                if (onChange) {
                  event.persist(); // extract from React synthetic event pool
                  const adjustedEvent = event;
                  adjustedEvent.value = nextValue;
                  onChange(adjustedEvent);
                }
              }}
              onFocus={(event) => {
                announce(
                  formatMessage({ id: 'dateInput.openCalendar', messages }),
                );
                if (onFocus) onFocus(event);
              }}
            />
            <Button
              onClick={open ? closeCalendar : openCalendar}
              plain
              icon={icon || MaskedInputIcon || <CalendarIcon size={iconSize} />}
              margin={{ right: 'small' }}
            />
          </Box>
        </Keyboard>
      </FormContext.Provider>
    );

    if (inline) {
      return (
        <Box>
          {input}
          {calendar}
        </Box>
      );
    }

    if (open) {
      return [
        input,
        <Keyboard key="drop" onEsc={() => ref.current.focus()}>
          <Drop
            overflow="visible"
            id={id ? `${id}__drop` : undefined}
            target={ref.current}
            align={{ top: 'bottom', left: 'left', ...dropProps }}
            onEsc={closeCalendar}
            onClickOutside={({ target }) => {
              if (
                target !== containerRef.current &&
                !containerRef.current.contains(target)
              ) {
                closeCalendar();
              }
            }}
            {...dropProps}
          >
            {calendar}
          </Drop>
        </Keyboard>,
      ];
    }

    return input;
  },
);

DateInput.displayName = 'DateInput';
DateInput.propTypes = DateInputPropTypes;

export { DateInput };
<commit_msg>Prevent DateInput from scrolling down the page when opening with space (#6022)<commit_after>import React, {
  useRef,
  forwardRef,
  useContext,
  useEffect,
  useMemo,
  useState,
  useCallback,
} from 'react';
import { ThemeContext } from 'styled-components';
import { Calendar as CalendarIcon } from 'grommet-icons/icons/Calendar';
import { defaultProps } from '../../default-props';
import { AnnounceContext } from '../../contexts/AnnounceContext';
import { MessageContext } from '../../contexts/MessageContext';
import { Box } from '../Box';
import { Button } from '../Button';
import { Calendar } from '../Calendar';
import { Drop } from '../Drop';
import { DropButton } from '../DropButton';
import { FormContext } from '../Form';
import { Keyboard } from '../Keyboard';
import { MaskedInput } from '../MaskedInput';
import { useForwardedRef } from '../../utils';
import { getTimestamp, normalizeForTimezone } from '../Calendar/utils';
import {
  formatToSchema,
  schemaToMask,
  valuesAreEqual,
  valueToText,
  textToValue,
} from './utils';
import { DateInputPropTypes } from './propTypes';

const DateInput = forwardRef(
  (
    {
      buttonProps, // when no format and not inline
      calendarProps,
      defaultValue,
      disabled,
      dropProps, // when inline isn't true
      format,
      id,
      icon,
      inline = false,
      inputProps, // for MaskedInput, when format is specified
      name,
      onChange,
      onFocus,
      plain,
      value: valueArg,
      messages,
      ...rest
    },
    refArg,
  ) => {
    const theme = useContext(ThemeContext) || defaultProps.theme;
    const announce = useContext(AnnounceContext);
    const { format: formatMessage } = useContext(MessageContext);
    const iconSize =
      (theme.dateInput.icon && theme.dateInput.icon.size) || 'medium';
    const { useFormInput } = useContext(FormContext);
    const ref = useForwardedRef(refArg);
    const containerRef = useRef();
    const [value, setValue] = useFormInput({
      name,
      value: valueArg,
      initialValue: defaultValue,
    });

    const timestamp = useMemo(() => {
      if (Array.isArray(defaultValue) && defaultValue.length)
        return getTimestamp(defaultValue[0]);
      if (typeof defaultValue === 'string') return getTimestamp(defaultValue);
      if (Array.isArray(value) && value.length) return getTimestamp(value[0]);
      // check to see if value is not an empty string
      // empty string should behave like undefined
      if (typeof value === 'string' && value.length) return getTimestamp(value);
      return undefined;
    }, [defaultValue, value]);

    // whether or not we should normalize the date based on the timestamp.
    // will be set to false if the initial timestamp is undefined (meaning
    // a user did not provide a defaultValue or value). in this case, we
    // will just rely on the UTC timestamp and don't need to normalize.
    const [normalize, setNormalize] = useState(true);

    // normalize value based on timestamp vs user's local timezone
    const normalizedDate = normalizeForTimezone(value, timestamp, normalize);
    // do we expect multiple dates?
    const range = Array.isArray(value) || (format && format.includes('-'));

    // parse format and build a formal schema we can use elsewhere
    const schema = useMemo(() => formatToSchema(format), [format]);

    // mask is only used when a format is provided
    const mask = useMemo(() => schemaToMask(schema), [schema]);

    // textValue is only used when a format is provided
    const [textValue, setTextValue] = useState(
      schema ? valueToText(normalizedDate, schema) : undefined,
    );

    // Setting the icon through `inputProps` is deprecated.
    // The `icon` prop should be used instead.
    const { icon: MaskedInputIcon, ...restOfInputProps } = inputProps || {};
    if (MaskedInputIcon) {
      console.warn(
        `Customizing the DateInput icon through inputProps is deprecated.
Use the icon prop instead.`,
      );
    }

    // We need to distinguish between the caller changing a Form value
    // and the user typing a date that he isn't finished with yet.
    // To handle this, we see if we have a value and the text value
    // associated with it doesn't align to it, then we update the text value.
    // We compare using textToValue to avoid "06/01/2021" not
    // matching "06/1/2021".
    useEffect(() => {
      if (schema && value !== undefined) {
        const nextTextValue = valueToText(normalizedDate, schema);
        if (
          !valuesAreEqual(
            textToValue(textValue, schema, range, timestamp),
            textToValue(nextTextValue, schema, range, timestamp),
          ) ||
          (textValue === '' && nextTextValue !== '')
        ) {
          setTextValue(nextTextValue);
        }
      }
    }, [range, schema, textValue, value, normalizedDate, timestamp]);

    // when format and not inline, whether to show the Calendar in a Drop
    const [open, setOpen] = useState();

    const openCalendar = useCallback(() => {
      setOpen(true);
      announce(formatMessage({ id: 'dateInput.enterCalendar', messages }));
    }, [announce, formatMessage, messages]);

    const closeCalendar = useCallback(() => {
      setOpen(false);
      announce(formatMessage({ id: 'dateInput.exitCalendar', messages }));
    }, [announce, formatMessage, messages]);

    const calendar = (
      <Calendar
        ref={inline ? ref : undefined}
        id={inline && !format ? id : undefined}
        range={range}
        date={range ? undefined : normalizedDate}
        // when caller initializes with empty array, dates should be undefined
        // allowing the user to select both begin and end of the range
        dates={range && value.length ? [normalizedDate] : undefined}
        // places focus on days grid when Calendar opens
        initialFocus={open ? 'days' : undefined}
        normalize={normalize}
        onSelect={
          disabled
            ? undefined
            : (nextValue) => {
                let normalizedValue;
                if (range && Array.isArray(nextValue))
                  [normalizedValue] = nextValue;
                // clicking an edge date removes it
                else if (range) normalizedValue = [nextValue, nextValue];
                else normalizedValue = nextValue;
                // timestamp will be undefined if no defaultValue or value have
                // been passed in, indicating that we should stay local if the
                // user first picks a date via the Calendar.
                let nextNormalize = normalize;
                if (timestamp === undefined) {
                  nextNormalize = false;
                  setNormalize(nextNormalize);
                }
                if (schema)
                  setTextValue(
                    valueToText(
                      normalizeForTimezone(
                        normalizedValue,
                        undefined,
                        nextNormalize,
                      ),
                      schema,
                    ),
                  );
                setValue(normalizedValue);
                if (onChange) onChange({ value: normalizedValue });
                if (open && !range) {
                  closeCalendar();
                  setTimeout(() => ref.current.focus(), 1);
                }
              }
        }
        {...{ ...calendarProps, timestamp }}
      />
    );

    const formContextValue = useMemo(
      () => ({
        useFormInput: ({ value: valueProp }) => [valueProp, () => {}],
      }),
      [],
    );

    if (!format) {
      // When no format is specified, we don't give the user a way to type
      if (inline) return calendar;

      return (
        <DropButton
          ref={ref}
          id={id}
          dropProps={{ align: { top: 'bottom', left: 'left' }, ...dropProps }}
          dropContent={calendar}
          icon={icon || MaskedInputIcon || <CalendarIcon size={iconSize} />}
          {...buttonProps}
        />
      );
    }

    const input = (
      <FormContext.Provider
        key="input"
        // don't let MaskedInput drive the Form
        value={formContextValue}
      >
        <Keyboard
          onEsc={open ? () => closeCalendar() : undefined}
          onSpace={(event) => {
            event.preventDefault();
            openCalendar();
          }}
        >
          <Box
            ref={containerRef}
            border={!plain}
            round="xxsmall"
            direction="row"
            fill
          >
            <MaskedInput
              ref={ref}
              id={id}
              name={name}
              reverse
              disabled={disabled}
              mask={mask}
              plain
              {...restOfInputProps}
              {...rest}
              value={textValue}
              onChange={(event) => {
                const nextTextValue = event.target.value;
                setTextValue(nextTextValue);

                let localTimestamp;
                // get the UTC timestamp relative to the user's timezone
                // once a date is complete
                if (timestamp === undefined && Date.parse(nextTextValue))
                  [, localTimestamp] = new Date(nextTextValue)
                    .toISOString()
                    .split('T');

                // timestamp will be undefined if no defaultValue or value have
                // been passed in, indicating that we should stay local
                let nextNormalize = normalize;
                if (timestamp === undefined) {
                  nextNormalize = false;
                  setNormalize(nextNormalize);
                }
                const nextValue = textToValue(
                  nextTextValue,
                  schema,
                  range,
                  timestamp || localTimestamp,
                  nextNormalize,
                );

                // reset to original state
                if (nextValue === undefined) setNormalize(true);
                // update value even when undefined
                setValue(nextValue);
                if (onChange) {
                  event.persist(); // extract from React synthetic event pool
                  const adjustedEvent = event;
                  adjustedEvent.value = nextValue;
                  onChange(adjustedEvent);
                }
              }}
              onFocus={(event) => {
                announce(
                  formatMessage({ id: 'dateInput.openCalendar', messages }),
                );
                if (onFocus) onFocus(event);
              }}
            />
            <Button
              onClick={open ? closeCalendar : openCalendar}
              plain
              icon={icon || MaskedInputIcon || <CalendarIcon size={iconSize} />}
              margin={{ right: 'small' }}
            />
          </Box>
        </Keyboard>
      </FormContext.Provider>
    );

    if (inline) {
      return (
        <Box>
          {input}
          {calendar}
        </Box>
      );
    }

    if (open) {
      return [
        input,
        <Keyboard key="drop" onEsc={() => ref.current.focus()}>
          <Drop
            overflow="visible"
            id={id ? `${id}__drop` : undefined}
            target={ref.current}
            align={{ top: 'bottom', left: 'left', ...dropProps }}
            onEsc={closeCalendar}
            onClickOutside={({ target }) => {
              if (
                target !== containerRef.current &&
                !containerRef.current.contains(target)
              ) {
                closeCalendar();
              }
            }}
            {...dropProps}
          >
            {calendar}
          </Drop>
        </Keyboard>,
      ];
    }

    return input;
  },
);

DateInput.displayName = 'DateInput';
DateInput.propTypes = DateInputPropTypes;

export { DateInput };
<|endoftext|>


<commit_before>import mixin from 'reactjs-mixin';
import React from 'react';

import FilterInputText from './FilterInputText';
import QueryParamsMixin from '../mixins/QueryParamsMixin';
import ServiceFilterTypes from '../constants/ServiceFilterTypes';

const METHODS_TO_BIND = ['setSearchString'];

class ServiceSearchFilter extends mixin(QueryParamsMixin) {
  static get defaultProps() {
    return {
    };
  }

  constructor() {
    super();

    this.state = {
      searchString: ''
    };

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  componentDidMount() {
    this.updateFilterStatus();
  }

  componentWillReceiveProps() {
    this.updateFilterStatus();
  }

  setSearchString(filterValue) {
    this.setQueryParam(ServiceFilterTypes.TEXT, filterValue);
    this.props.handleFilterChange(filterValue, ServiceFilterTypes.TEXT);
  }

  updateFilterStatus() {
    let {state} = this;
    let searchString =
      this.getQueryParamObject()[ServiceFilterTypes.TEXT] || '';

    if (searchString !== state.searchString) {
      this.setState({searchString},
        this.props.handleFilterChange.bind(null, searchString, ServiceFilterTypes.TEXT));
    }
  }

  render() {
    return (
      <FilterInputText
        handleFilterChange={this.setSearchString}
        inverseStyle={true}
        placeholder="Search"
        searchString={this.state.searchString} />
    );
  }
};

module.exports = ServiceSearchFilter;
<commit_msg>Suppress eslint error<commit_after>import mixin from 'reactjs-mixin';
/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */

import FilterInputText from './FilterInputText';
import QueryParamsMixin from '../mixins/QueryParamsMixin';
import ServiceFilterTypes from '../constants/ServiceFilterTypes';

const METHODS_TO_BIND = ['setSearchString'];

class ServiceSearchFilter extends mixin(QueryParamsMixin) {
  static get defaultProps() {
    return {
    };
  }

  constructor() {
    super();

    this.state = {
      searchString: ''
    };

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  componentDidMount() {
    this.updateFilterStatus();
  }

  componentWillReceiveProps() {
    this.updateFilterStatus();
  }

  setSearchString(filterValue) {
    this.setQueryParam(ServiceFilterTypes.TEXT, filterValue);
    this.props.handleFilterChange(filterValue, ServiceFilterTypes.TEXT);
  }

  updateFilterStatus() {
    let {state} = this;
    let searchString =
      this.getQueryParamObject()[ServiceFilterTypes.TEXT] || '';

    if (searchString !== state.searchString) {
      this.setState({searchString},
        this.props.handleFilterChange.bind(null, searchString, ServiceFilterTypes.TEXT));
    }
  }

  render() {
    return (
      <FilterInputText
        handleFilterChange={this.setSearchString}
        inverseStyle={true}
        placeholder="Search"
        searchString={this.state.searchString} />
    );
  }
};

module.exports = ServiceSearchFilter;
<|endoftext|>


<commit_before>(function() {
    // Get application context
    var app = Sammy.apps['#main'];
    var store = app.store;

    // *********
    // Diagnosis
    // *********

    app.get('#/diagnosis', function (c) {
        c.api('GET', '/diagnosis/show?full', {}, function(data) {

            if (typeof(data.reports) === "undefined")
            {
                data.reports = [];
            }

            // Prepare data to be displayed ...
            for (var i = 0 ; i < data.reports.length ; i++)
            {
                // Convert timestamp to datetime
                data.reports[i].time = new Date(data.reports[i].timestamp*1000);
                data.reports[i].warnings = 0;
                data.reports[i].errors = 0;
                data.reports[i].ignored = 0;
                for (var j = 0 ; j < data.reports[i].items.length ; j++)
                {
                    var type_ = data.reports[i].items[j].status;
                    type_ = type_.toLowerCase();
                    var ignored = data.reports[i].items[j].ignored;
                    var icon = "";
                    var issue = false;

                    if (type_ == "success") {
                        icon = "check-circle";
                    }
                    else if (ignored == true) {
                        icon = type_;
                        if (type_ == "error") {
                            icon = "times"
                        }
                        type_ = "ignored";
                        data.reports[i].ignored++;
                    }
                    else if (type_ == "warning") {
                        icon = "warning";
                        issue = true;
                        data.reports[i].warnings++;
                    }
                    else if (type_ == "error") {
                        type_ = "danger";
                        icon = "times";
                        issue = true;
                        data.reports[i].errors++;
                    }
                    data.reports[i].items[j].status = type_;
                    data.reports[i].items[j].icon = icon;
                    data.reports[i].items[j].issue = issue;
                    // We want filter_args to be something like "dnsrecords,domain=yolo.test,category=xmpp"
                    data.reports[i].items[j].filter_args = data.reports[i].id;
                    for (prop in data.reports[i].items[j].meta) {
                        data.reports[i].items[j].filter_args = data.reports[i].items[j].filter_args + ","+prop+"="+data.reports[i].items[j].meta[prop];
                    }
                };
                data.reports[i].noIssues = data.reports[i].warnings + data.reports[i].errors ? false : true;
            };

            // Render and display the view
            c.view('diagnosis/diagnosis_show', data, function() {

                // Button for first diagnosis
                $("button[data-action='run-full-diagnosis']").click(function() {
                    c.api('POST', '/diagnosis/run', {}, function(data) {
                        c.refresh();
                    });
                });

                // Configure share with yunopaste button
                $("button[data-action='share']").click(function() {
                    c.api('GET', '/diagnosis/show?share', {}, function(data) {
                        c.hideLoader();
                        window.open(data.url, '_blank');
                    });
                });

                // Configure 'rerun diagnosis' button behavior
                $("button[data-action='rerun-diagnosis']").click(function() {
                    var category = $(this).data("category");
                    c.api('POST', '/diagnosis/run?force', {"categories": [category]}, function(data) {
                        c.refresh();
                    });
                });

                // Configure 'ignore' / 'unignore' buttons behavior
                $("button[data-action='ignore']").click(function() {
                    var filter_args = $(this).data("filter-args");
                    c.api('POST', '/diagnosis/ignore', {'add_filter': filter_args.split(',') }, function(data) {
                        c.refresh();
                    })
                });

                $("button[data-action='unignore']").click(function() {
                    var filter_args = $(this).data("filter-args");
                    c.api('POST', '/diagnosis/ignore', {'remove_filter': filter_args.split(',') }, function(data) {
                        c.refresh();
                    })
                });
            });
        });
    });

})();
<commit_msg>Refresh diagnosis when opening diagnosis view<commit_after>(function() {
    // Get application context
    var app = Sammy.apps['#main'];
    var store = app.store;

    // *********
    // Diagnosis
    // *********

    app.get('#/diagnosis', function (c) {
        c.api('POST', '/diagnosis/run?except-if-never-ran-yet', {}, function() {
            updateDiagnosisView();
        });
    });

    function updateDiagnosisView() {
        c.api('GET', '/diagnosis/show?full', {}, function(data) {

            if (typeof(data.reports) === "undefined")
            {
                data.reports = [];
            }

            // Prepare data to be displayed ...
            for (var i = 0 ; i < data.reports.length ; i++)
            {
                // Convert timestamp to datetime
                data.reports[i].time = new Date(data.reports[i].timestamp*1000);
                data.reports[i].warnings = 0;
                data.reports[i].errors = 0;
                data.reports[i].ignored = 0;
                for (var j = 0 ; j < data.reports[i].items.length ; j++)
                {
                    var type_ = data.reports[i].items[j].status;
                    type_ = type_.toLowerCase();
                    var ignored = data.reports[i].items[j].ignored;
                    var icon = "";
                    var issue = false;

                    if (type_ == "success") {
                        icon = "check-circle";
                    }
                    else if (ignored == true) {
                        icon = type_;
                        if (type_ == "error") {
                            icon = "times"
                        }
                        type_ = "ignored";
                        data.reports[i].ignored++;
                    }
                    else if (type_ == "warning") {
                        icon = "warning";
                        issue = true;
                        data.reports[i].warnings++;
                    }
                    else if (type_ == "error") {
                        type_ = "danger";
                        icon = "times";
                        issue = true;
                        data.reports[i].errors++;
                    }
                    data.reports[i].items[j].status = type_;
                    data.reports[i].items[j].icon = icon;
                    data.reports[i].items[j].issue = issue;
                    // We want filter_args to be something like "dnsrecords,domain=yolo.test,category=xmpp"
                    data.reports[i].items[j].filter_args = data.reports[i].id;
                    for (prop in data.reports[i].items[j].meta) {
                        data.reports[i].items[j].filter_args = data.reports[i].items[j].filter_args + ","+prop+"="+data.reports[i].items[j].meta[prop];
                    }
                };
                data.reports[i].noIssues = data.reports[i].warnings + data.reports[i].errors ? false : true;
            };

            // Render and display the view
            c.view('diagnosis/diagnosis_show', data, function() {

                // Button for first diagnosis
                $("button[data-action='run-full-diagnosis']").click(function() {
                    c.api('POST', '/diagnosis/run', {}, function(data) {
                        updateDiagnosisView();
                    });
                });

                // Configure share with yunopaste button
                $("button[data-action='share']").click(function() {
                    c.api('GET', '/diagnosis/show?share', {}, function(data) {
                        c.hideLoader();
                        window.open(data.url, '_blank');
                    });
                });

                // Configure 'rerun diagnosis' button behavior
                $("button[data-action='rerun-diagnosis']").click(function() {
                    var category = $(this).data("category");
                    c.api('POST', '/diagnosis/run?force', {"categories": [category]}, function(data) {
                        updateDiagnosisView();
                    });
                });

                // Configure 'ignore' / 'unignore' buttons behavior
                $("button[data-action='ignore']").click(function() {
                    var filter_args = $(this).data("filter-args");
                    c.api('POST', '/diagnosis/ignore', {'add_filter': filter_args.split(',') }, function(data) {
                        updateDiagnosisView();
                    })
                });

                $("button[data-action='unignore']").click(function() {
                    var filter_args = $(this).data("filter-args");
                    c.api('POST', '/diagnosis/ignore', {'remove_filter': filter_args.split(',') }, function(data) {
                        updateDiagnosisView();
                    })
                });
            });
        });
    }

})();
<|endoftext|>


<commit_before>#!/usr/bin/env node

// repl - explore pickup

const fs = require('fs')
const http = require('http')
const https = require('https')
const repl = require('repl')
const url = require('url')
const util = require('util')

const { Pickup, Feed, Entry } = require('./')

const server = repl.start({
  ignoreUndefined: true,
  input: process.stdin,
  output: process.stdout,
  prompt: 'pickup> ',
  useColors: true
})

const ctx = server.context

ctx.file = file
ctx.get = get
ctx.read = read
ctx.Entry = Entry
ctx.Feed = Feed

function file (path) {
  return fs.createReadStream(path).pipe(Pickup({ objectMode: true }))
}

function get (uri) {
  const urlObj = url.parse(uri)
  const mod = urlObj.protocol === 'http:' ? http : https

  const parser = Pickup({ objectMode: true })

  mod.get(urlObj, (res) => {
    res.pipe(parser)
  })

  return parser
}

// Reads all data of type from parser matching key. If type is not an Object,
// it replaces key, allowing you to just pass a key.
function read (parser, type, key) {
  parser.on('data', (obj) => {
    if (typeof type === 'string') key = type

    if (type instanceof Object && !(obj instanceof type)) return
    console.log(util.inspect(key ? obj[key] : obj, { colors: true }))
  })

  parser.once('end', () => {
    console.log('ok')
    server.displayPrompt()
  })
}
<commit_msg>Use pipeline and add parameters<commit_after>#!/usr/bin/env node

// repl - evaluate pickup

const fs = require('fs')
const http = require('http')
const https = require('https')
const repl = require('repl')
const url = require('url')
const { Pickup, Feed, Entry } = require('./')
const { inspect } = require('util')
const { pipeline, Writable } = require('readable-stream')

const server = repl.start({
  ignoreUndefined: true,
  input: process.stdin,
  output: process.stdout,
  prompt: 'pickup> ',
  useColors: true
})

function file (path) {
  return fs.createReadStream(path).pipe(
    new Pickup({ objectMode: true })
  )
}

function get (uri) {
  const urlObj = url.parse(uri)
  const mod = urlObj.protocol === 'http:' ? http : https

  const parser = new Pickup({ objectMode: true })

  mod.get(urlObj, (res) => {
    res.pipe(parser)
  })

  return parser
}

// Reads all data of type from parser matching key. You can skip type or pass
// Feed or Entry for only seeing to those. You might also limit messages.
function read (parser, type, key, limit = Infinity) {
  let count = 0

  pipeline(parser, new Writable({
    write (obj, enc, cb) {
      if (typeof type === 'string') key = type

      if (typeof type === 'number') {
        limit = type
        type = undefined
      }

      if (typeof key === 'number') {
        limit = key
        key = undefined
      }

      if (count >= limit) {
        return cb()
      }

      if (type instanceof Object && !(obj instanceof type)) {
        return cb()
      }

      console.log(inspect(key ? obj[key] : obj, { colors: true }))
      count++

      cb()
    },
    objectMode: true
  }), er => {
    console.log(er || 'ok')
    server.displayPrompt()
  })
}

function clear () {
  process.stdout.write('\u001B[2J\u001B[0;0f')
}

const ctx = server.context

ctx.Entry = Entry
ctx.Feed = Feed
ctx.clear = clear
ctx.file = file
ctx.get = get
ctx.read = read
<|endoftext|>