<commit_before>/*
  Define translations using LE Utils license names as keys
*/

import { createTranslator } from 'kolibri.utils.i18n';

const licenseShortNameStrings = {
  'CC BY': {
    message: 'CC BY',
    context:
      'Abbreviated name of the Creative Commons "BY" license.\nFor more info, see https://creativecommons.org/licenses/by/2.0/',
  },
  'CC BY-SA': {
    message: 'CC BY-SA',
    context:
      'Abbreviated name of the Creative Commons "BY-SA" license.\nFor more info, see https://creativecommons.org/licenses/by-sa/2.0/',
  },
  'CC BY-ND': {
    message: 'CC BY-ND',
    context:
      'Abbreviated name of the Creative Commons "BY-ND" license.\nFor more info, see https://creativecommons.org/licenses/by-nd/2.0/',
  },
  'CC BY-NC': {
    message: 'CC BY-NC',
    context:
      'Abbreviated name of the Creative Commons "BY-NC" license.\nFor more info, see https://creativecommons.org/licenses/by-nc/2.0/',
  },
  'CC BY-NC-SA': {
    message: 'CC BY-NC-SA',
    context:
      'Abbreviated name of the Creative Commons "BY-NC-SA" license.\nFor more info, see https://creativecommons.org/licenses/by-nc-sa/2.0/',
  },
  'CC BY-NC-ND': {
    message: 'CC BY-NC-ND',
    context:
      'Abbreviated name of the Creative Commons "BY-NC-ND" license.\nFor more info, see https://creativecommons.org/licenses/by-nc-nd/2.0/',
  },
  'All Rights Reserved': {
    message: 'All rights reserved',
    context: 'For more info, see https://en.wikipedia.org/wiki/All_rights_reserved',
  },
  'Public Domain': {
    message: 'Public domain',
    context: 'For more info, see https://en.wikipedia.org/wiki/Public_domain',
  },
  'Special Permissions': {
    message: 'Special permissions',
    context: 'A special licensing arrangement was reached with the copyright owner',
  },
};

const licenseLongNameStrings = {
  'CC BY': {
    message: 'Creative Commons: attribution',
    context:
      'Long-form name of the Creative Commons "BY" license.\nFor more info, see https://creativecommons.org/licenses/by/2.0/',
  },
  'CC BY-SA': {
    message: 'Creative Commons: attribution, share-alike',
    context:
      'Long-form name of the Creative Commons "BY-SA" license.\nFor more info, see https://creativecommons.org/licenses/by-sa/2.0/',
  },
  'CC BY-ND': {
    message: 'Creative Commons: attribution, no derivatives',
    context:
      'Long-form name of the Creative Commons "BY-ND" license.\nFor more info, see https://creativecommons.org/licenses/by-nd/2.0/',
  },
  'CC BY-NC': {
    message: 'Creative Commons: attribution, non-commercial',
    context:
      'Long-form name of the Creative Commons "BY-NC" license.\nFor more info, see https://creativecommons.org/licenses/by-nc/2.0/',
  },
  'CC BY-NC-SA': {
    message: 'Creative Commons: attribution, non-commercial, share-alike',
    context:
      'Long-form name of the Creative Commons "BY-NC-SA" license.\nFor more info, see https://creativecommons.org/licenses/by-nc-sa/2.0/',
  },
  'CC BY-NC-ND': {
    message: 'Creative Commons: attribution, non-commercial, no derivatives',
    context:
      'Long-form name of the Creative Commons "BY-NC-ND" license.\nFor more info, see https://creativecommons.org/licenses/by-nc-nd/2.0/',
  },
  'All Rights Reserved': {
    message: 'All rights reserved',
    context: 'For more info, see https://en.wikipedia.org/wiki/All_rights_reserved',
  },
  'Public Domain': {
    message: 'Public domain',
    context: 'For more info, see https://en.wikipedia.org/wiki/Public_domain',
  },
  'Special Permissions': {
    message: 'Special permissions',
    context: 'A special licensing arrangement was reached with the copyright owner',
  },
};

const licenseDescriptionConsumerStrings = {
  'CC BY': {
    message:
      'You may distribute, adapt, and build upon this resource – even commercially – as long as you give credit to the author.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by/2.0/',
  },
  'CC BY-SA': {
    message:
      'You may adapt and build upon this resource – even commercially – as long as you credit the author and license your new resources under identical terms. All new resources based on yours must also carry the same license.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-sa/2.0/',
  },
  'CC BY-ND': {
    message:
      'You may reuse the resource for any purpose, including commercially. However it cannot be adapted, and credit must be provided to the author.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-nd/2.0/',
  },
  'CC BY-NC': {
    message:
      'You may adapt and build upon this resource non-commercially. Your new resources must credit the author and also be non-commercial.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-nc/2.0/',
  },
  'CC BY-NC-SA': {
    message:
      'You may adapt, and build upon this resource non-commercially, as long as you give credit to the author and license your new resources under identical terms.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-nc-sa/2.0/',
  },
  'CC BY-NC-ND': {
    message:
      'You may download this resource and share it with others as long as you give credit to the author. You may not adapt it in any way or use it commercially.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-nc-sd/2.0/',
  },
  'All Rights Reserved': {
    message:
      'You may not distribute, adapt, or build upon this resource without permission from the copyright owner.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://en.wikipedia.org/wiki/All_rights_reserved',
  },
  'Public Domain': {
    message:
      'This resource is free of known restrictions under copyright law. You may distribute, adapt, and build upon this resource, even commercially.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://en.wikipedia.org/wiki/Public_domain',
  },
  'Special Permissions': {
    message:
      'This resource has a special license. Contact the owner of this license for a description of what you are allowed to do with it.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nA special licensing arrangement was reached with the copyright owner',
  },
};

const licenseDescriptionCreatorStrings = {
  'CC BY': {
    message:
      'This license lets others distribute, adapt, and build upon your resource – even commercially – as long as they credit you for the original creation. This is the most accommodating of the Creative Commons licenses. Recommended for maximum dissemination and use of licensed materials.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by/2.0/',
  },
  'CC BY-SA': {
    message:
      'This license lets others adapt and build upon your resource – even commercially – as long as they credit you and license their new resources under identical terms. This license is often compared to “copyleft” free and open source software licenses. All new resources based on yours will carry the same license, so any derivatives will also allow commercial use. This is the license used by Wikipedia. It recommended for materials that use resources from Wikipedia or similarly licensed projects.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-sa/2.0/',
  },
  'CC BY-ND': {
    message:
      'This license lets others reuse the resource for any purpose, including commercially. However it cannot be shared with others in adapted form, and credit must be provided to you.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-nd/2.0/',
  },
  'CC BY-NC': {
    message:
      'This license lets others adapt and build upon your resource non-commercially. Although their new derivative resources must credit you and be non-commercial, they don’t have to be licensed under the same terms.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-nc/2.0/',
  },
  'CC BY-NC-SA': {
    message:
      'This license lets others adapt and build upon your resource non-commercially, as long as they credit you and license their new resources under the identical terms.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-nc-sa/2.0/',
  },
  'CC BY-NC-ND': {
    message:
      'This license is the most restrictive of the six main Creative Commons licenses. It only allows others to download your resources and share them with others as long as they credit you, but they can’t change them in any way or use them commercially.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-nc-nd/2.0/',
  },
  'All Rights Reserved': {
    message:
      'You reserve all the rights provided by copyright law, and others may not legally distribute, adapt, or build upon this resource without your permission.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://en.wikipedia.org/wiki/All_rights_reserved',
  },
  'Public Domain': {
    message: 'This resource is free of known restrictions under copyright law.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://en.wikipedia.org/wiki/Public_domain',
  },
  'Special Permissions': {
    message:
      'This is a custom license to use when the other options do not apply. You are responsible for creating a description of what this license entails and communicating it with users.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nA special licensing arrangement was reached with the copyright owner',
  },
};

const shortNameTranslator = createTranslator('ShortLicenseNames', licenseShortNameStrings);
const longNameTranslator = createTranslator('LongLicenseNames', licenseLongNameStrings);
const creatorDescriptionTranslator = createTranslator(
  'LicenseDescriptionsForCreators',
  licenseDescriptionCreatorStrings
);
const consumerDescriptionTranslator = createTranslator(
  'LicenseDescriptionsForConsumers',
  licenseDescriptionConsumerStrings
);

// Translated short-form license names
export function licenseShortName(leUtilsLicenseName) {
  if (licenseShortNameStrings[leUtilsLicenseName]) {
    return shortNameTranslator.$tr(leUtilsLicenseName);
  }
  return leUtilsLicenseName;
}

// Translated long-form license names
export function licenseLongName(leUtilsLicenseName) {
  if (licenseLongNameStrings[leUtilsLicenseName]) {
    return longNameTranslator.$tr(leUtilsLicenseName);
  }
  return leUtilsLicenseName;
}

// Translated license descriptions, aimed at creators of the content
export function licenseDescriptionForCreator(leUtilsLicenseName, leUtilsLicenseDescription) {
  if (licenseDescriptionCreatorStrings[leUtilsLicenseName]) {
    return creatorDescriptionTranslator.$tr(leUtilsLicenseName);
  }
  return leUtilsLicenseDescription;
}

// Translated license descriptions, aimed at users and consumers of the content
export function licenseDescriptionForConsumer(leUtilsLicenseName, leUtilsLicenseDescription) {
  if (licenseDescriptionConsumerStrings[leUtilsLicenseName]) {
    return consumerDescriptionTranslator.$tr(leUtilsLicenseName);
  }
  return leUtilsLicenseDescription;
}
<commit_msg>missing word<commit_after>/*
  Define translations using LE Utils license names as keys
*/

import { createTranslator } from 'kolibri.utils.i18n';

const licenseShortNameStrings = {
  'CC BY': {
    message: 'CC BY',
    context:
      'Abbreviated name of the Creative Commons "BY" license.\nFor more info, see https://creativecommons.org/licenses/by/2.0/',
  },
  'CC BY-SA': {
    message: 'CC BY-SA',
    context:
      'Abbreviated name of the Creative Commons "BY-SA" license.\nFor more info, see https://creativecommons.org/licenses/by-sa/2.0/',
  },
  'CC BY-ND': {
    message: 'CC BY-ND',
    context:
      'Abbreviated name of the Creative Commons "BY-ND" license.\nFor more info, see https://creativecommons.org/licenses/by-nd/2.0/',
  },
  'CC BY-NC': {
    message: 'CC BY-NC',
    context:
      'Abbreviated name of the Creative Commons "BY-NC" license.\nFor more info, see https://creativecommons.org/licenses/by-nc/2.0/',
  },
  'CC BY-NC-SA': {
    message: 'CC BY-NC-SA',
    context:
      'Abbreviated name of the Creative Commons "BY-NC-SA" license.\nFor more info, see https://creativecommons.org/licenses/by-nc-sa/2.0/',
  },
  'CC BY-NC-ND': {
    message: 'CC BY-NC-ND',
    context:
      'Abbreviated name of the Creative Commons "BY-NC-ND" license.\nFor more info, see https://creativecommons.org/licenses/by-nc-nd/2.0/',
  },
  'All Rights Reserved': {
    message: 'All rights reserved',
    context: 'For more info, see https://en.wikipedia.org/wiki/All_rights_reserved',
  },
  'Public Domain': {
    message: 'Public domain',
    context: 'For more info, see https://en.wikipedia.org/wiki/Public_domain',
  },
  'Special Permissions': {
    message: 'Special permissions',
    context: 'A special licensing arrangement was reached with the copyright owner',
  },
};

const licenseLongNameStrings = {
  'CC BY': {
    message: 'Creative Commons: attribution',
    context:
      'Long-form name of the Creative Commons "BY" license.\nFor more info, see https://creativecommons.org/licenses/by/2.0/',
  },
  'CC BY-SA': {
    message: 'Creative Commons: attribution, share-alike',
    context:
      'Long-form name of the Creative Commons "BY-SA" license.\nFor more info, see https://creativecommons.org/licenses/by-sa/2.0/',
  },
  'CC BY-ND': {
    message: 'Creative Commons: attribution, no derivatives',
    context:
      'Long-form name of the Creative Commons "BY-ND" license.\nFor more info, see https://creativecommons.org/licenses/by-nd/2.0/',
  },
  'CC BY-NC': {
    message: 'Creative Commons: attribution, non-commercial',
    context:
      'Long-form name of the Creative Commons "BY-NC" license.\nFor more info, see https://creativecommons.org/licenses/by-nc/2.0/',
  },
  'CC BY-NC-SA': {
    message: 'Creative Commons: attribution, non-commercial, share-alike',
    context:
      'Long-form name of the Creative Commons "BY-NC-SA" license.\nFor more info, see https://creativecommons.org/licenses/by-nc-sa/2.0/',
  },
  'CC BY-NC-ND': {
    message: 'Creative Commons: attribution, non-commercial, no derivatives',
    context:
      'Long-form name of the Creative Commons "BY-NC-ND" license.\nFor more info, see https://creativecommons.org/licenses/by-nc-nd/2.0/',
  },
  'All Rights Reserved': {
    message: 'All rights reserved',
    context: 'For more info, see https://en.wikipedia.org/wiki/All_rights_reserved',
  },
  'Public Domain': {
    message: 'Public domain',
    context: 'For more info, see https://en.wikipedia.org/wiki/Public_domain',
  },
  'Special Permissions': {
    message: 'Special permissions',
    context: 'A special licensing arrangement was reached with the copyright owner',
  },
};

const licenseDescriptionConsumerStrings = {
  'CC BY': {
    message:
      'You may distribute, adapt, and build upon this resource – even commercially – as long as you give credit to the author.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by/2.0/',
  },
  'CC BY-SA': {
    message:
      'You may adapt and build upon this resource – even commercially – as long as you credit the author and license your new resources under identical terms. All new resources based on yours must also carry the same license.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-sa/2.0/',
  },
  'CC BY-ND': {
    message:
      'You may reuse the resource for any purpose, including commercially. However it cannot be adapted, and credit must be provided to the author.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-nd/2.0/',
  },
  'CC BY-NC': {
    message:
      'You may adapt and build upon this resource non-commercially. Your new resources must credit the author and also be non-commercial.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-nc/2.0/',
  },
  'CC BY-NC-SA': {
    message:
      'You may adapt, and build upon this resource non-commercially, as long as you give credit to the author and license your new resources under identical terms.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-nc-sa/2.0/',
  },
  'CC BY-NC-ND': {
    message:
      'You may download this resource and share it with others as long as you give credit to the author. You may not adapt it in any way or use it commercially.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://creativecommons.org/licenses/by-nc-sd/2.0/',
  },
  'All Rights Reserved': {
    message:
      'You may not distribute, adapt, or build upon this resource without permission from the copyright owner.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://en.wikipedia.org/wiki/All_rights_reserved',
  },
  'Public Domain': {
    message:
      'This resource is free of known restrictions under copyright law. You may distribute, adapt, and build upon this resource, even commercially.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nFor more info, see https://en.wikipedia.org/wiki/Public_domain',
  },
  'Special Permissions': {
    message:
      'This resource has a special license. Contact the owner of this license for a description of what you are allowed to do with it.',
    context:
      'License details from the perspective of the resource consumer or end-user.\nA special licensing arrangement was reached with the copyright owner',
  },
};

const licenseDescriptionCreatorStrings = {
  'CC BY': {
    message:
      'This license lets others distribute, adapt, and build upon your resource – even commercially – as long as they credit you for the original creation. This is the most accommodating of the Creative Commons licenses. Recommended for maximum dissemination and use of licensed materials.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by/2.0/',
  },
  'CC BY-SA': {
    message:
      'This license lets others adapt and build upon your resource – even commercially – as long as they credit you and license their new resources under identical terms. This license is often compared to “copyleft” free and open source software licenses. All new resources based on yours will carry the same license, so any derivatives will also allow commercial use. This is the license used by Wikipedia. It is recommended for materials that use resources from Wikipedia or similarly licensed projects.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-sa/2.0/',
  },
  'CC BY-ND': {
    message:
      'This license lets others reuse the resource for any purpose, including commercially. However it cannot be shared with others in adapted form, and credit must be provided to you.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-nd/2.0/',
  },
  'CC BY-NC': {
    message:
      'This license lets others adapt and build upon your resource non-commercially. Although their new derivative resources must credit you and be non-commercial, they don’t have to be licensed under the same terms.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-nc/2.0/',
  },
  'CC BY-NC-SA': {
    message:
      'This license lets others adapt and build upon your resource non-commercially, as long as they credit you and license their new resources under the identical terms.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-nc-sa/2.0/',
  },
  'CC BY-NC-ND': {
    message:
      'This license is the most restrictive of the six main Creative Commons licenses. It only allows others to download your resources and share them with others as long as they credit you, but they can’t change them in any way or use them commercially.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://creativecommons.org/licenses/by-nc-nd/2.0/',
  },
  'All Rights Reserved': {
    message:
      'You reserve all the rights provided by copyright law, and others may not legally distribute, adapt, or build upon this resource without your permission.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://en.wikipedia.org/wiki/All_rights_reserved',
  },
  'Public Domain': {
    message: 'This resource is free of known restrictions under copyright law.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nFor more info, see https://en.wikipedia.org/wiki/Public_domain',
  },
  'Special Permissions': {
    message:
      'This is a custom license to use when the other options do not apply. You are responsible for creating a description of what this license entails and communicating it with users.',
    context:
      'License details from the perspective of the resource creator, author, or copyright owner.\nA special licensing arrangement was reached with the copyright owner',
  },
};

const shortNameTranslator = createTranslator('ShortLicenseNames', licenseShortNameStrings);
const longNameTranslator = createTranslator('LongLicenseNames', licenseLongNameStrings);
const creatorDescriptionTranslator = createTranslator(
  'LicenseDescriptionsForCreators',
  licenseDescriptionCreatorStrings
);
const consumerDescriptionTranslator = createTranslator(
  'LicenseDescriptionsForConsumers',
  licenseDescriptionConsumerStrings
);

// Translated short-form license names
export function licenseShortName(leUtilsLicenseName) {
  if (licenseShortNameStrings[leUtilsLicenseName]) {
    return shortNameTranslator.$tr(leUtilsLicenseName);
  }
  return leUtilsLicenseName;
}

// Translated long-form license names
export function licenseLongName(leUtilsLicenseName) {
  if (licenseLongNameStrings[leUtilsLicenseName]) {
    return longNameTranslator.$tr(leUtilsLicenseName);
  }
  return leUtilsLicenseName;
}

// Translated license descriptions, aimed at creators of the content
export function licenseDescriptionForCreator(leUtilsLicenseName, leUtilsLicenseDescription) {
  if (licenseDescriptionCreatorStrings[leUtilsLicenseName]) {
    return creatorDescriptionTranslator.$tr(leUtilsLicenseName);
  }
  return leUtilsLicenseDescription;
}

// Translated license descriptions, aimed at users and consumers of the content
export function licenseDescriptionForConsumer(leUtilsLicenseName, leUtilsLicenseDescription) {
  if (licenseDescriptionConsumerStrings[leUtilsLicenseName]) {
    return consumerDescriptionTranslator.$tr(leUtilsLicenseName);
  }
  return leUtilsLicenseDescription;
}
<|endoftext|>


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

    function Datagrid($timeout, $compile, DatasetGridService, FilterService) {
        return {
            restrict: 'E',
            template: '

',
            bindToController: true,
            controllerAs: 'datagridCtrl',
            controller: function() {},
            link: function (scope, iElement) {
                var options, grid, colHeaderElements = [];

                //------------------------------------------------------------------------------------------------------
                //------------------------------------------------COL UTILES--------------------------------------------
                //------------------------------------------------------------------------------------------------------

                /**
                 * Reset columns class
                 */
                var resetColumnsClass = function() {
                    _.forEach(grid.getColumns(), function(column) {
                        column.cssClass = null;
                    });
                };

                /**
                 * Reset the cells css
                 */
                var resetCellStyles = function() {
                    grid.setCellCssStyles('highlight', {});
                };

                /**
                 * Adapt backend column to slick column. The name with div id depending on index is important. It is used to insert column header dropdown and quality bar
                 * @param col - the backend column to adapt
                 * @param index - column index
                 * @returns {{id: *, field: *, name: string}}
                 */
                var columnItem = function (col, index) {
                    var divId = 'datagrid-header-' + index;
                    var colItem = {
                        id: col.id,
                        field: col.id,
                        name: '

'
                    };

                    return colItem;
                };

                /**
                 * Insert the dataset headers (dropdown actions and quality bars)
                 */
                var insertDatasetHeaders = function () {
                    _.forEach(DatasetGridService.data.columns, function (col, index) {
                        var headerScope = scope.$new(true);
                        headerScope.columns = col;
                        headerScope.metadata = DatasetGridService.metadata;
                        var headerElement = angular.element('<datagrid-header column="columns" metadata="metadata"></datagrid-header>');
                        $compile(headerElement)(headerScope);

                        colHeaderElements.push(headerElement);
                        angular.element('#datagrid-header-' + index).append(headerElement);
                    });
                };

                /**
                 * Remove header elements
                 */
                var clearHeaders = function () {
                    _.forEach(colHeaderElements, function (element) {
                        element.remove();
                    });
                    colHeaderElements = [];
                };

                //------------------------------------------------------------------------------------------------------
                //-------------------------------------------------LISTENERS--------------------------------------------
                //------------------------------------------------------------------------------------------------------
                /**
                 * Attach listeners for big table row management
                 */
                var attachLongTableListeners = function() {
                    DatasetGridService.dataView.onRowCountChanged.subscribe(function () {
                        grid.updateRowCount();
                        grid.render();
                    });
                    DatasetGridService.dataView.onRowsChanged.subscribe(function (e, args) {
                        grid.invalidateRows(args.rows);
                        grid.render();
                    });
                };

                /**
                 * Attach listeners for custom directives management in headers
                 */
                var attachColumnHeaderListeners = function() {
                    //destroy old elements and insert compiled column header directives
                    grid.onColumnsReordered.subscribe(function () {
                        clearHeaders();
                        insertDatasetHeaders();
                    });
                };

                /**
                 * Attach cell action listeners (click, active change, ...)
                 */
                var attachCellListeners = function() {
                    //get clicked content and highlight cells in clicked column containing the content
                    grid.onClick.subscribe(function (e,args) {
                        var config = {};
                        var column = grid.getColumns()[args.cell];
                        var content = DatasetGridService.dataView.getItem(args.row)[column.id];

                        var rowsContainingWord = DatasetGridService.getRowsContaining(column.id, content);
                        _.forEach(rowsContainingWord, function(rowId) {
                            config[rowId] = {};
                            config[rowId][column.id] = 'highlight';
                        });

                        grid.setCellCssStyles('highlight', config);
                        grid.invalidate();

                        $timeout(function() {
                            DatasetGridService.selectedColumnId = column.id;
                        });
                    });

                    //change selected cell column background
                    grid.onActiveCellChanged.subscribe(function(e,args) {
                        if(angular.isDefined(args.cell)) {
                            resetColumnsClass();
                            grid.getColumns()[args.cell].cssClass = 'selected';
                            grid.invalidate();
                        }
                    });
                };

                //------------------------------------------------------------------------------------------------------
                //---------------------------------------------------INIT-----------------------------------------------
                //------------------------------------------------------------------------------------------------------
                /**
                 * Init Slick grid and attach listeners on dataview and grid
                 */
                var initGridIfNeeded = function () {
                    if(grid) {
                        return;
                    }

                    options = {
                        editable: false,
                        enableAddRow: false,
                        enableCellNavigation: true,
                        enableTextSelectionOnCells: true
                    };
                    grid = new Slick.Grid('#datagrid', DatasetGridService.dataView, [], options);

                    //listeners
                    attachLongTableListeners();
                    attachColumnHeaderListeners();
                    attachCellListeners();
                };

                //------------------------------------------------------------------------------------------------------
                //--------------------------------------------------UPDATE----------------------------------------------
                //------------------------------------------------------------------------------------------------------
                /**
                 * Clear and update columns
                 * @param dataCols
                 */
                var updateColumns = function (dataCols) {
                    clearHeaders();

                    var columns = _.map(dataCols, function (col, index) {
                        return columnItem(col, index);
                    });
                    grid.setColumns(columns);

                    insertDatasetHeaders();
                };

                /**
                 * Render grid on dataView update
                 */
                var updateData = function () {
                    resetCellStyles();
                    grid.resetActiveCell();
                    grid.invalidate();
                };

                //------------------------------------------------------------------------------------------------------
                //-------------------------------------------------WATCHERS---------------------------------------------
                //------------------------------------------------------------------------------------------------------
                /**
                 * Update grid columns on backend column change
                 */
                scope.$watch(
                    function () {
                        return DatasetGridService.data ? DatasetGridService.data.columns : null;
                    },
                    function (cols) {
                        if (cols) {
                            initGridIfNeeded();
                            updateColumns(cols);
                            grid.autosizeColumns();
                        }
                    }
                );

                /**
                 * Update data on backend value change
                 */
                scope.$watch(
                    function () {
                        return DatasetGridService.data ? DatasetGridService.data.records : null;
                    },
                    function (records) {
                        if(records) {
                            initGridIfNeeded();
                            updateData();
                        }
                    }
                );

                /**
                 * When filter change, displayed values change, so we reset active cell and cell styles
                 */
                scope.$watchCollection(
                    function () {
                        return FilterService.filters;
                    },
                    function () {
                        if(grid) {
                            resetCellStyles();
                            grid.resetActiveCell();
                        }
                    }
                );

                /**
                 * Destroy scope on element destroy
                 */
                iElement.on('$destroy', function () {
                    scope.$destroy();
                });
            }
        };
    }

    angular.module('data-prep.datagrid')
        .directive('datagrid', Datagrid);
})();

<commit_msg>TDP-68 : scroll grid to top on data change<commit_after>(function () {
    'use strict';

    function Datagrid($timeout, $compile, DatasetGridService, FilterService) {
        return {
            restrict: 'E',
            template: '

',
            bindToController: true,
            controllerAs: 'datagridCtrl',
            controller: function() {},
            link: function (scope, iElement) {
                var options, grid, colHeaderElements = [];

                //------------------------------------------------------------------------------------------------------
                //------------------------------------------------COL UTILES--------------------------------------------
                //------------------------------------------------------------------------------------------------------

                /**
                 * Reset columns class
                 */
                var resetColumnsClass = function() {
                    _.forEach(grid.getColumns(), function(column) {
                        column.cssClass = null;
                    });
                };

                /**
                 * Reset the cells css
                 */
                var resetCellStyles = function() {
                    grid.setCellCssStyles('highlight', {});
                };

                /**
                 * Adapt backend column to slick column. The name with div id depending on index is important. It is used to insert column header dropdown and quality bar
                 * @param col - the backend column to adapt
                 * @param index - column index
                 * @returns {{id: *, field: *, name: string}}
                 */
                var columnItem = function (col, index) {
                    var divId = 'datagrid-header-' + index;
                    var colItem = {
                        id: col.id,
                        field: col.id,
                        name: '

'
                    };

                    return colItem;
                };

                /**
                 * Insert the dataset headers (dropdown actions and quality bars)
                 */
                var insertDatasetHeaders = function () {
                    _.forEach(DatasetGridService.data.columns, function (col, index) {
                        var headerScope = scope.$new(true);
                        headerScope.columns = col;
                        headerScope.metadata = DatasetGridService.metadata;
                        var headerElement = angular.element('<datagrid-header column="columns" metadata="metadata"></datagrid-header>');
                        $compile(headerElement)(headerScope);

                        colHeaderElements.push(headerElement);
                        angular.element('#datagrid-header-' + index).append(headerElement);
                    });
                };

                /**
                 * Remove header elements
                 */
                var clearHeaders = function () {
                    _.forEach(colHeaderElements, function (element) {
                        element.remove();
                    });
                    colHeaderElements = [];
                };

                //------------------------------------------------------------------------------------------------------
                //-------------------------------------------------LISTENERS--------------------------------------------
                //------------------------------------------------------------------------------------------------------
                /**
                 * Attach listeners for big table row management
                 */
                var attachLongTableListeners = function() {
                    DatasetGridService.dataView.onRowCountChanged.subscribe(function () {
                        grid.updateRowCount();
                        grid.render();
                    });
                    DatasetGridService.dataView.onRowsChanged.subscribe(function (e, args) {
                        grid.invalidateRows(args.rows);
                        grid.render();
                    });
                };

                /**
                 * Attach listeners for custom directives management in headers
                 */
                var attachColumnHeaderListeners = function() {
                    //destroy old elements and insert compiled column header directives
                    grid.onColumnsReordered.subscribe(function () {
                        clearHeaders();
                        insertDatasetHeaders();
                    });
                };

                /**
                 * Attach cell action listeners (click, active change, ...)
                 */
                var attachCellListeners = function() {
                    //get clicked content and highlight cells in clicked column containing the content
                    grid.onClick.subscribe(function (e,args) {
                        var config = {};
                        var column = grid.getColumns()[args.cell];
                        var content = DatasetGridService.dataView.getItem(args.row)[column.id];

                        var rowsContainingWord = DatasetGridService.getRowsContaining(column.id, content);
                        _.forEach(rowsContainingWord, function(rowId) {
                            config[rowId] = {};
                            config[rowId][column.id] = 'highlight';
                        });

                        grid.setCellCssStyles('highlight', config);
                        grid.invalidate();

                        $timeout(function() {
                            DatasetGridService.selectedColumnId = column.id;
                        });
                    });

                    //change selected cell column background
                    grid.onActiveCellChanged.subscribe(function(e,args) {
                        if(angular.isDefined(args.cell)) {
                            resetColumnsClass();
                            grid.getColumns()[args.cell].cssClass = 'selected';
                            grid.invalidate();
                        }
                    });
                };

                //------------------------------------------------------------------------------------------------------
                //---------------------------------------------------INIT-----------------------------------------------
                //------------------------------------------------------------------------------------------------------
                /**
                 * Init Slick grid and attach listeners on dataview and grid
                 */
                var initGridIfNeeded = function () {
                    if(grid) {
                        return;
                    }

                    options = {
                        editable: false,
                        enableAddRow: false,
                        enableCellNavigation: true,
                        enableTextSelectionOnCells: true
                    };
                    grid = new Slick.Grid('#datagrid', DatasetGridService.dataView, [], options);

                    //listeners
                    attachLongTableListeners();
                    attachColumnHeaderListeners();
                    attachCellListeners();
                };

                //------------------------------------------------------------------------------------------------------
                //--------------------------------------------------UPDATE----------------------------------------------
                //------------------------------------------------------------------------------------------------------
                /**
                 * Clear and update columns
                 * @param dataCols
                 */
                var updateColumns = function (dataCols) {
                    clearHeaders();

                    var columns = _.map(dataCols, function (col, index) {
                        return columnItem(col, index);
                    });
                    grid.setColumns(columns);

                    insertDatasetHeaders();
                };

                /**
                 * Render grid on dataView update
                 */
                var updateData = function () {
                    resetCellStyles();
                    grid.resetActiveCell();
                    grid.invalidate();
                };

                //------------------------------------------------------------------------------------------------------
                //-------------------------------------------------WATCHERS---------------------------------------------
                //------------------------------------------------------------------------------------------------------
                /**
                 * Update grid columns on backend column change
                 */
                scope.$watch(
                    function () {
                        return DatasetGridService.data ? DatasetGridService.data.columns : null;
                    },
                    function (cols) {
                        if (cols) {
                            initGridIfNeeded();
                            updateColumns(cols);
                            grid.autosizeColumns();
                        }
                    }
                );

                /**
                 * Update data on backend value change
                 */
                scope.$watch(
                    function () {
                        return DatasetGridService.data ? DatasetGridService.data.records : null;
                    },
                    function (records) {
                        if(records) {
                            initGridIfNeeded();
                            updateData();
                        }
                    }
                );

                /**
                 * Scroll to top when loaded dataset change
                 */
                scope.$watch(
                    function () {
                        return DatasetGridService.metadata;
                    },
                    function (metadata) {
                        if(metadata) {
                            grid.scrollRowToTop(0);
                        }
                    }
                );

                /**
                 * When filter change, displayed values change, so we reset active cell and cell styles
                 */
                scope.$watchCollection(
                    function () {
                        return FilterService.filters;
                    },
                    function () {
                        if(grid) {
                            resetCellStyles();
                            grid.resetActiveCell();
                            grid.scrollRowToTop(0);
                        }
                    }
                );

                /**
                 * Destroy scope on element destroy
                 */
                iElement.on('$destroy', function () {
                    scope.$destroy();
                });
            }
        };
    }

    angular.module('data-prep.datagrid')
        .directive('datagrid', Datagrid);
})();

<|endoftext|>


<commit_before>export default function() {
  return [
    {title: 'Harry Potter 1'},
    {title: 'Harry Potter 2'},
    {title: 'Harry Potter 3'}
  ];
}<commit_msg>adding a few more titles for more content<commit_after>export default function() {
  return [
    {title: 'Harry Potter 1'},
    {title: 'Harry Potter 2'},
    {title: 'Harry Potter 3'},
    {title: 'Harry Potter 4'},
    {title: 'Harry Potter 5'},
    {title: 'Harry Potter 6'},
    {title: 'Harry Potter 7'},
    {title: 'Harry Potter 8'},
    {title: 'Fantastic Beasts And Where To Find Them'}
  ];
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
	init: function(component, event, helper) {
		var hourError = component.find("hourError");
		var minError = component.find("minuteError");

		component.find("hours").set("v.ariaDescribedBy", hourError.getGlobalId());
		component.find("minutes").set("v.ariaDescribedBy", minError.getGlobalId());
	},

	updateAmpm: function(component, event, helper) {
    	var amPmCmp = component.find("ampm");
        var isAndroid = $A.get("$Browser.isAndroid");
        if (isAndroid === true) { // On Android, if hour field is changed and then ampm select is clicked,
        	                      // the focus is still in hour field. That is, the hour value doesn't get updated.
            var hoursCmp = component.find("hours");
            var currentHourValue = hoursCmp.getElement().value;
            hoursCmp.setValue("v.value", currentHourValue);
            if (helper.validateHours(component)) {
                if (amPmCmp) { // it must be in 12 hour format
                    if (amPmCmp.get("v.value") == "am") {
                        component.set("v.hours", parseInt(currentHourValue));
                    } else {
                        component.set("v.hours", parseInt(currentHourValue) + 12);
                    }
                }
                component.set("v.isValid", true);
            } else {
            	component.set("v.isValid", false);
            }
            return;
        }

        if (component.get("v.isValid") === true) {
            var hours = component.get("v.hours");
            if (amPmCmp) {
                if (amPmCmp.get("v.value") == "am") {
                    component.set("v.hours", parseInt(hours) - 12);
                } else {
                    component.set("v.hours", parseInt(hours) + 12);
                }
            }
        }
    },

    updateHours: function(component, event, helper) {
        if (helper.validateHours(component)) {
            var hoursCmp = event.getSource();
            if (hoursCmp) {
                helper.updateHourValue(component, hoursCmp.get("v.value"));
                component.set("v.isValid", true);
                return;
            }
        }
        component.set("v.isValid", false);
    },

    updateMinutes: function(component, event, helper) {
        if (helper.validateMinutes(component)) {
            var minutesCmp = event.getSource();
            if (minutesCmp) {
                helper.updateMinuteValue(component, minutesCmp.get("v.value"));
                component.set("v.isValid", true);
                return;
            }
        }
        component.set("v.isValid", false);
    }
})<commit_msg>Change "cmp.setValue" to "cmp.set" @bug W-2427197@<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
	init: function(component, event, helper) {
		var hourError = component.find("hourError");
		var minError = component.find("minuteError");

		component.find("hours").set("v.ariaDescribedBy", hourError.getGlobalId());
		component.find("minutes").set("v.ariaDescribedBy", minError.getGlobalId());
	},

	updateAmpm: function(component, event, helper) {
    	var amPmCmp = component.find("ampm");
        var isAndroid = $A.get("$Browser.isAndroid");
        if (isAndroid === true) { // On Android, if hour field is changed and then ampm select is clicked,
        	                      // the focus is still in hour field. That is, the hour value doesn't get updated.
            var hoursCmp = component.find("hours");
            var currentHourValue = hoursCmp.getElement().value;
            hoursCmp.set("v.value", currentHourValue);
            if (helper.validateHours(component)) {
                if (amPmCmp) { // it must be in 12 hour format
                    if (amPmCmp.get("v.value") == "am") {
                        component.set("v.hours", parseInt(currentHourValue));
                    } else {
                        component.set("v.hours", parseInt(currentHourValue) + 12);
                    }
                }
                component.set("v.isValid", true);
            } else {
            	component.set("v.isValid", false);
            }
            return;
        }

        if (component.get("v.isValid") === true) {
            var hours = component.get("v.hours");
            if (amPmCmp) {
                if (amPmCmp.get("v.value") == "am") {
                    component.set("v.hours", parseInt(hours) - 12);
                } else {
                    component.set("v.hours", parseInt(hours) + 12);
                }
            }
        }
    },

    updateHours: function(component, event, helper) {
        if (helper.validateHours(component)) {
            var hoursCmp = event.getSource();
            if (hoursCmp) {
                helper.updateHourValue(component, hoursCmp.get("v.value"));
                component.set("v.isValid", true);
                return;
            }
        }
        component.set("v.isValid", false);
    },

    updateMinutes: function(component, event, helper) {
        if (helper.validateMinutes(component)) {
            var minutesCmp = event.getSource();
            if (minutesCmp) {
                helper.updateMinuteValue(component, minutesCmp.get("v.value"));
                component.set("v.isValid", true);
                return;
            }
        }
        component.set("v.isValid", false);
    }
})<|endoftext|>


<commit_before>/* jshint node: true */
(function () {
    "use strict";

    function CookieAccessInfo(domain, path, secure, script) {
        if (this instanceof CookieAccessInfo) {
            this.domain = domain || undefined;
            this.path = path || "/";
            this.secure = !!secure;
            this.script = !!script;
            return this;
        }
        return new CookieAccessInfo(domain, path, secure, script);
    }
    exports.CookieAccessInfo = CookieAccessInfo;

    function Cookie(cookiestr, request_domain, request_path) {
        if (cookiestr instanceof Cookie) {
            return cookiestr;
        }
        if (this instanceof Cookie) {
            this.name = null;
            this.value = null;
            this.expiration_date = Infinity;
            this.path = String(request_path || "/");
            this.explicit_path = false;
            this.domain = request_domain || null;
            this.explicit_domain = false;
            this.secure = false; //how to define default?
            this.noscript = false; //httponly
            if (cookiestr) {
                this.parse(cookiestr, request_domain, request_path);
            }
            return this;
        }
        return new Cookie(cookiestr);
    }
    exports.Cookie = Cookie;

    Cookie.prototype.toString = function toString() {
        var str = [this.name + "=" + this.value];
        if (this.expiration_date !== Infinity) {
            str.push("expires=" + (new Date(this.expiration_date)).toGMTString());
        }
        if (this.domain) {
            str.push("domain=" + this.domain);
        }
        if (this.path) {
            str.push("path=" + this.path);
        }
        if (this.secure) {
            str.push("secure");
        }
        if (this.noscript) {
            str.push("httponly");
        }
        return str.join("; ");
    };

    Cookie.prototype.toValueString = function toValueString() {
        return this.name + "=" + this.value;
    };

    var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g;
    Cookie.prototype.parse = function parse(str, request_domain, request_path) {
        if (this instanceof Cookie) {
            var parts = str.split(";").filter(function (value) {
                    return !!value;
                }),
                pair = parts[0].match(/([^=]+)=([\s\S]*)/),
                key = pair[1],
                value = pair[2],
                i;
            this.name = key;
            this.value = value;

            for (i = 1; i < parts.length; i += 1) {
                pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/);
                key = pair[1].trim().toLowerCase();
                value = pair[2];
                switch (key) {
                case "httponly":
                    this.noscript = true;
                    break;
                case "expires":
                    this.expiration_date = value ?
                            Number(Date.parse(value)) :
                            Infinity;
                    break;
                case "path":
                    this.path = value ?
                            value.trim() :
                            "";
                    this.explicit_path = true;
                    break;
                case "domain":
                    this.domain = value ?
                            value.trim() :
                            "";
                    this.explicit_domain = !!this.domain;
                    break;
                case "secure":
                    this.secure = true;
                    break;
                }
            }

            if (!this.explicit_path) {
               this.path = request_path || "/";
            }
            if (!this.explicit_domain) {
               this.domain = request_domain;
            }

            return this;
        }
        return new Cookie().parse(str, request_domain, request_path);
    };

    Cookie.prototype.matches = function matches(access_info) {
        if (this.noscript && access_info.script ||
                this.secure && !access_info.secure ||
                !this.collidesWith(access_info)) {
            return false;
        }
        return true;
    };

    Cookie.prototype.collidesWith = function collidesWith(access_info) {
        if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) {
            return false;
        }
        if (this.path && access_info.path.indexOf(this.path) !== 0) {
            return false;
        }
        if (this.explicit_path && this.path !== access_info.path) {
           return false;
        }
        var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,'');
        var cookie_domain = this.domain && this.domain.replace(/^[\.]/,'');
        if (cookie_domain === access_domain) {
            return true;
        }
        if (cookie_domain) {
            if (!this.explicit_domain) {
                return false; // we already checked if the domains were exactly the same
            }
            var wildcard = access_domain.indexOf(cookie_domain);
            if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) {
                return false;
            }
            return true;
        }
        return true;
    };

    function CookieJar() {
        var cookies, cookies_list, collidable_cookie;
        if (this instanceof CookieJar) {
            cookies = Object.create(null); //name: [Cookie]

            this.setCookie = function setCookie(cookie, request_domain, request_path) {
                var remove, i;
                cookie = new Cookie(cookie, request_domain, request_path);
                //Delete the cookie if the set is past the current time
                remove = cookie.expiration_date <= Date.now();
                if (cookies[cookie.name] !== undefined) {
                    cookies_list = cookies[cookie.name];
                    for (i = 0; i < cookies_list.length; i += 1) {
                        collidable_cookie = cookies_list[i];
                        if (collidable_cookie.collidesWith(cookie)) {
                            if (remove) {
                                cookies_list.splice(i, 1);
                                if (cookies_list.length === 0) {
                                    delete cookies[cookie.name];
                                }
                                return false;
                            }
                            cookies_list[i] = cookie;
                            return cookie;
                        }
                    }
                    if (remove) {
                        return false;
                    }
                    cookies_list.push(cookie);
                    return cookie;
                }
                if (remove) {
                    return false;
                }
                cookies[cookie.name] = [cookie];
                return cookies[cookie.name];
            };
            //returns a cookie
            this.getCookie = function getCookie(cookie_name, access_info) {
                var cookie, i;
                cookies_list = cookies[cookie_name];
                if (!cookies_list) {
                    return;
                }
                for (i = 0; i < cookies_list.length; i += 1) {
                    cookie = cookies_list[i];
                    if (cookie.expiration_date <= Date.now()) {
                        if (cookies_list.length === 0) {
                            delete cookies[cookie.name];
                        }
                        continue;
                    }

                    if (cookie.matches(access_info)) {
                        return cookie;
                    }
                }
            };
            //returns a list of cookies
            this.getCookies = function getCookies(access_info) {
                var matches = [], cookie_name, cookie;
                for (cookie_name in cookies) {
                    cookie = this.getCookie(cookie_name, access_info);
                    if (cookie) {
                        matches.push(cookie);
                    }
                }
                matches.toString = function toString() {
                    return matches.join(":");
                };
                matches.toValueString = function toValueString() {
                    return matches.map(function (c) {
                        return c.toValueString();
                    }).join(';');
                };
                return matches;
            };

            return this;
        }
        return new CookieJar();
    }
    exports.CookieJar = CookieJar;

    //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned.
    CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) {
        cookies = Array.isArray(cookies) ?
                cookies :
                cookies.split(cookie_str_splitter);
        var successful = [],
            i,
            cookie;
        cookies = cookies.map(Cookie);
        for (i = 0; i < cookies.length; i += 1) {
            cookie = cookies[i];
            if (this.setCookie(cookie, request_domain, request_path)) {
                successful.push(cookie);
            }
        }
        return successful;
    };
}());
<commit_msg>Added fix to ensure that the request_domain and request_path get passed to the Cookie constructor.<commit_after>/* jshint node: true */
(function () {
    "use strict";

    function CookieAccessInfo(domain, path, secure, script) {
        if (this instanceof CookieAccessInfo) {
            this.domain = domain || undefined;
            this.path = path || "/";
            this.secure = !!secure;
            this.script = !!script;
            return this;
        }
        return new CookieAccessInfo(domain, path, secure, script);
    }
    exports.CookieAccessInfo = CookieAccessInfo;

    function Cookie(cookiestr, request_domain, request_path) {
        if (cookiestr instanceof Cookie) {
            return cookiestr;
        }
        if (this instanceof Cookie) {
            this.name = null;
            this.value = null;
            this.expiration_date = Infinity;
            this.path = String(request_path || "/");
            this.explicit_path = false;
            this.domain = request_domain || null;
            this.explicit_domain = false;
            this.secure = false; //how to define default?
            this.noscript = false; //httponly
            if (cookiestr) {
                this.parse(cookiestr, request_domain, request_path);
            }
            return this;
        }
        return new Cookie(cookiestr, request_domain, request_path);
    }
    exports.Cookie = Cookie;

    Cookie.prototype.toString = function toString() {
        var str = [this.name + "=" + this.value];
        if (this.expiration_date !== Infinity) {
            str.push("expires=" + (new Date(this.expiration_date)).toGMTString());
        }
        if (this.domain) {
            str.push("domain=" + this.domain);
        }
        if (this.path) {
            str.push("path=" + this.path);
        }
        if (this.secure) {
            str.push("secure");
        }
        if (this.noscript) {
            str.push("httponly");
        }
        return str.join("; ");
    };

    Cookie.prototype.toValueString = function toValueString() {
        return this.name + "=" + this.value;
    };

    var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g;
    Cookie.prototype.parse = function parse(str, request_domain, request_path) {
        if (this instanceof Cookie) {
            var parts = str.split(";").filter(function (value) {
                    return !!value;
                }),
                pair = parts[0].match(/([^=]+)=([\s\S]*)/),
                key = pair[1],
                value = pair[2],
                i;
            this.name = key;
            this.value = value;

            for (i = 1; i < parts.length; i += 1) {
                pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/);
                key = pair[1].trim().toLowerCase();
                value = pair[2];
                switch (key) {
                case "httponly":
                    this.noscript = true;
                    break;
                case "expires":
                    this.expiration_date = value ?
                            Number(Date.parse(value)) :
                            Infinity;
                    break;
                case "path":
                    this.path = value ?
                            value.trim() :
                            "";
                    this.explicit_path = true;
                    break;
                case "domain":
                    this.domain = value ?
                            value.trim() :
                            "";
                    this.explicit_domain = !!this.domain;
                    break;
                case "secure":
                    this.secure = true;
                    break;
                }
            }

            if (!this.explicit_path) {
               this.path = request_path || "/";
            }
            if (!this.explicit_domain) {
               this.domain = request_domain;
            }

            return this;
        }
        return new Cookie().parse(str, request_domain, request_path);
    };

    Cookie.prototype.matches = function matches(access_info) {
        if (this.noscript && access_info.script ||
                this.secure && !access_info.secure ||
                !this.collidesWith(access_info)) {
            return false;
        }
        return true;
    };

    Cookie.prototype.collidesWith = function collidesWith(access_info) {
        if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) {
            return false;
        }
        if (this.path && access_info.path.indexOf(this.path) !== 0) {
            return false;
        }
        if (this.explicit_path && this.path !== access_info.path) {
           return false;
        }
        var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,'');
        var cookie_domain = this.domain && this.domain.replace(/^[\.]/,'');
        if (cookie_domain === access_domain) {
            return true;
        }
        if (cookie_domain) {
            if (!this.explicit_domain) {
                return false; // we already checked if the domains were exactly the same
            }
            var wildcard = access_domain.indexOf(cookie_domain);
            if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) {
                return false;
            }
            return true;
        }
        return true;
    };

    function CookieJar() {
        var cookies, cookies_list, collidable_cookie;
        if (this instanceof CookieJar) {
            cookies = Object.create(null); //name: [Cookie]

            this.setCookie = function setCookie(cookie, request_domain, request_path) {
                var remove, i;
                cookie = new Cookie(cookie, request_domain, request_path);
                //Delete the cookie if the set is past the current time
                remove = cookie.expiration_date <= Date.now();
                if (cookies[cookie.name] !== undefined) {
                    cookies_list = cookies[cookie.name];
                    for (i = 0; i < cookies_list.length; i += 1) {
                        collidable_cookie = cookies_list[i];
                        if (collidable_cookie.collidesWith(cookie)) {
                            if (remove) {
                                cookies_list.splice(i, 1);
                                if (cookies_list.length === 0) {
                                    delete cookies[cookie.name];
                                }
                                return false;
                            }
                            cookies_list[i] = cookie;
                            return cookie;
                        }
                    }
                    if (remove) {
                        return false;
                    }
                    cookies_list.push(cookie);
                    return cookie;
                }
                if (remove) {
                    return false;
                }
                cookies[cookie.name] = [cookie];
                return cookies[cookie.name];
            };
            //returns a cookie
            this.getCookie = function getCookie(cookie_name, access_info) {
                var cookie, i;
                cookies_list = cookies[cookie_name];
                if (!cookies_list) {
                    return;
                }
                for (i = 0; i < cookies_list.length; i += 1) {
                    cookie = cookies_list[i];
                    if (cookie.expiration_date <= Date.now()) {
                        if (cookies_list.length === 0) {
                            delete cookies[cookie.name];
                        }
                        continue;
                    }

                    if (cookie.matches(access_info)) {
                        return cookie;
                    }
                }
            };
            //returns a list of cookies
            this.getCookies = function getCookies(access_info) {
                var matches = [], cookie_name, cookie;
                for (cookie_name in cookies) {
                    cookie = this.getCookie(cookie_name, access_info);
                    if (cookie) {
                        matches.push(cookie);
                    }
                }
                matches.toString = function toString() {
                    return matches.join(":");
                };
                matches.toValueString = function toValueString() {
                    return matches.map(function (c) {
                        return c.toValueString();
                    }).join(';');
                };
                return matches;
            };

            return this;
        }
        return new CookieJar();
    }
    exports.CookieJar = CookieJar;

    //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned.
    CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) {
        cookies = Array.isArray(cookies) ?
                cookies :
                cookies.split(cookie_str_splitter);
        var successful = [],
            i,
            cookie;
        cookies = cookies.map(function(item){
            return Cookie(item, request_domain, request_path);
        });
        for (i = 0; i < cookies.length; i += 1) {
            cookie = cookies[i];
            if (this.setCookie(cookie, request_domain, request_path)) {
                successful.push(cookie);
            }
        }
        return successful;
    };
}());
<|endoftext|>