<commit_before>;(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['knockout', 'jquery', 'osfutils', 'hgrid', 'js/dropzone-patch', 'bootstrap',
            'hgridrowselectionmodel', 'rowmovemanager', 'typeahead', 'handlebars'], factory);
    } else if (typeof $script === 'function') {
            $script.ready(['dropzone', 'dropzone-patch', 'hgrid',
            'hgridrowselectionmodel', 'rowmovemanager', 'typeahead', 'handlebars'], function () {
                global.ProjectOrganizer = factory(jQuery, global.HGrid, global.ko);
                $script.done('projectorganizer');
            });
    } else {
        global.ProjectOrganizer = factory(jQuery, global.HGrid, global.ko);
    }
}(this, function ($, HGrid, ko) {
    'use strict';

    //
    // Private Helper Functions
    //
    //
    // HGrid Customization
    //

    ProjectOrganizer.Html = $.extend({}, HGrid.Html);
    ProjectOrganizer.Col = {};
    ProjectOrganizer.Col.Name = $.extend({}, HGrid.Col.Name);

    function nameRowView(row) {
        var name = row.name.toString();

        var url = row.urls.fetch;
        var linkString = name;
        if (url != null) {
            linkString = '' + name + '';
        }

        var type = "project";
        if (row.isPointer) {
            type = "pointer";
        }
        return '' + linkString + '';

    }

    var dateModifiedColumn = {
        id: 'date-modified',
        text: 'Modified',
        // Using a function that receives `row` containing all the item information
        itemView: function (row) {
            if(row.modifiedDelta == 0){
                return "";
            }
            return moment.utc(row.dateModified).fromNow()+", "+row.modifiedBy.toString();
        },
        folderView: function (row) {
            if(row.modifiedDelta == 0){
                return "";
            }
            return moment.utc(row.dateModified).fromNow()+", "+row.modifiedBy.toString();
        },
        sortable: false,
        selectable: true,
        width: 40
    };

    var contributorsColumn = {
        id: 'contributors',
        text: 'Contributors',
        // Using a function that receives `row` containing all the item information
        itemView: function (row) {
            var contributorCount = row.contributors.length;
            if(contributorCount == 0){
                return "";
            }
            var contributorString = row.contributors[0].name.toString();
            if(contributorCount > 1) {
                contributorString += " +" + (contributorCount - 1);
            }
            return contributorString;
        },
        folderView: function (row) {
            var contributorCount = row.contributors.length;
            if(contributorCount == 0){
                return "";
            }
            var contributorString = row.contributors[0].name.toString();
            if(contributorCount > 1) {
                contributorString += " +" + (contributorCount - 1);
            }
            return contributorString;
        },
        sortable: false,
        selectable: true,
        // behavior: "selectAndMove",
        width: 30
    };

    ProjectOrganizer.Col.Name.selectable = true;
    ProjectOrganizer.Col.Name.sortable = false;
    ProjectOrganizer.Col.Name.itemView = function (row) {
        var name = row.name.toString();

        var url = row.urls.fetch;
        var linkString = name;
        var extraClass = "";
        if (url != null) {
            linkString = '' + name + '';
        }

        var type = "project";
        if (row.isPointer && !row.parentIsFolder) {
            type = "pointer"
        }
        if (row.isFolder) {
            type = "folder";
            if(!row.isSmartFolder) {
                extraClass = " dropzone";
            }
        }
        if (row.isSmartFolder) {
            extraClass += " smart-folder";

        }
        return '' + linkString + '';
    };
    ProjectOrganizer.Col.Name.folderView = ProjectOrganizer.Col.Name.itemView;

    var collapseAllInHGrid = function(grid) {
        grid.collapseAll();
    };

    var expandAllInHGrid = function(grid) {
        grid.getData().forEach(function(item) {
           grid.expandItem(item);
        });
    };

    var hgridInit = function(){
        var self = this;
        self.gridData = self.grid.grid.getData();
        self.myProjects = [];
        self.publicProjects = [];

        expandAllInHGrid(self.grid);

        // Expand/collapse All functions
        $(".pg-expand-all").click(function (){
            expandAllInHGrid(self.grid);
        });
        $(".pg-collapse-all").click(function (){
            collapseAllInHGrid(self.grid);
        });

        // This useful function found on StackOverflow http://stackoverflow.com/a/7385673
        // Used to hide the detail card when you click outside of it onto its containing div
        $(document).click(function (e) {
            var container = $("#project-grid");
            var altContainer = $(".project-details");

            if (!container.is(e.target) && !altContainer.is(e.target) // if the target of the click isn't the container...
                && container.has(e.target).length === 0 && altContainer.has(e.target).length === 0)// ... nor a descendant of the container
            {
                self.grid.grid.setSelectedRows([]);
                self.grid.grid.resetActiveCell();
            }
        });

        self.grid.grid.setSelectionModel(new Slick.RowSelectionModel());
        //
        // Grab the JSON for the contents of the smart folder. Add that data
        // to self.myProjects so that we can use it for the autocomplete
        //
        // /api/v1/search/projects/?term=amel&maxResults=5&includePublic=no&includeContributed=yes

        self.publicProjects = new Bloodhound({
            datumTokenizer: function (d) {
                return Bloodhound.tokenizers.whitespace(d.name);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: '/api/v1/search/projects/?term=%QUERY&maxResults=20&includePublic=yes&includeContributed=no',
                filter: function (projects) {
                    return $.map(projects, function (project) {
                        return {
                            name: project.value,
                            node_id: project.id,
                            category: project.category
                        };
                    });
                },
                limit: 10
            }

        });

        self.myProjects = new Bloodhound({
            datumTokenizer: function (d) {
                return Bloodhound.tokenizers.whitespace(d.name);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: '/api/v1/search/projects/?term=%QUERY&maxResults=20&includePublic=no&includeContributed=yes',
                filter: function (projects) {
                    return $.map(projects, function (project) {
                        return {
                            name: project.value,
                            node_id: project.id,
                            category: project.category
                        };
                    });
                },
                limit: 10
            }
        });

        //
        // When the selection changes, create the div that holds the detail information for the project including
        // whichever action buttons will work with that type of node. This is what will be changed by moving
        // to Knockout.js
        //

        self.grid.grid.onSelectedRowsChanged.subscribe(function () {
            var selectedRows = self.grid.grid.getSelectedRows();
            if (selectedRows.length == 1 ){
                self.myProjects.initialize();
                self.publicProjects.initialize();
                var linkName;
                var linkID;
                var theItem = self.grid.grid.getDataItem(selectedRows[0]);
                if (theItem.isFolder && !theItem.isSmartFolder) {
                    var getChildrenURL = theItem.apiURL + 'get_folder_pointers/';
                    var children;
                    $.getJSON(getChildrenURL, function (data) {
                        children = data;
                    });
                }
                var theParentNode = self.grid.grid.getData().getItemById(theItem.parentID);
                if (typeof theParentNode !== 'undefined') {
                    var theParentNodeID = theParentNode.node_id;
                     theItem.parentIsSmartFolder = theParentNode.isSmartFolder;
                }
                else {
                    theParentNodeID = "";
                    theItem.parentIsSmartFolder = true;
                }

                if(!theItem.isSmartFolder) {
                    createProjectDetailHTMLFromTemplate(theItem);
                    $('#findNode'+theItem.node_id).hide();
                    $('#findNode'+theItem.node_id+' .typeahead').typeahead({
                      highlight: true
                    },
                    {
                        name: 'my-projects',
                        displayKey: function(data){
                              return data.name;
                          },
                        source: self.myProjects.ttAdapter(),
                        templates: {
                        header: function(){
                            return '
My Projects
'
                        },
                        suggestion: function(data){
                              return '
'+data.name+'
';
                          }
                        }
                    },
                    {
                        name: 'public-projects',
                        displayKey: function(data){
                              return data.name;
                          },
                        source: self.publicProjects.ttAdapter(),
                        templates: {
                        header: function(){
                            return '
Public Projects
'
                        },
                        suggestion: function(data){
                              return '
'+data.name+'
';
                          }
                        }
                   });
                    $('#input'+theItem.node_id).bind('keyup', function(event){
                        var key = event.keyCode || event.which;
                        var buttonEnabled = (typeof $('#add-link-' + theItem.node_id).prop('disabled') !== "undefined");
                        if (key === 13 ) {
                            if(buttonEnabled) {
                                $('#add-link-' + theItem.node_id).click(); //submits if the control is active
                            }
                        }
                        else {
                            $('#add-link-warn-' + theItem.node_id).text("");
                            $('#add-link-' + theItem.node_id).attr("disabled", "disabled");
                            linkName = "";
                            linkID = "";
                        }
                    });
                    $('#input'+theItem.node_id).bind('typeahead:selected', function(obj, datum, name) {
                        if( children.indexOf(datum.node_id) == -1 ) {
                            $('#add-link-' + theItem.node_id).removeAttr('disabled');
                            linkName = datum.name;
                            linkID = datum.node_id;
                        } else  {
                            $('#add-link-warn-' + theItem.node_id).text("This project is already in the folder")
                        }
                    });
                    $('#add-link-'+theItem.node_id).click(function() {
                        var url = "/api/v1/pointer/"; // the script where you handle the form input.
                        var postData = JSON.stringify(
                            {
                                pointerID: linkID,
                                toNodeID: theItem.node_id
                            });
                        $.ajax({
                            type: "POST",
                            url: url,
                            data: postData,
                            contentType: 'application/json',
                            dataType: 'json',
                            success: function() {
                               reloadFolder(self, theItem, theParentNode);
                            }
                        });
                    });

                    $('#remove-link-'+theItem.node_id).click(function() {
                        var url = '/api/v1/folder/'+theParentNodeID+'/pointer/'+theItem.node_id;
                        var postData = JSON.stringify({});
                        $.ajax({
                            type: "DELETE",
                            url: url,
                            data: postData,
                            contentType: 'application/json',
                            dataType: 'json',
                            success: function() {
                                reloadFolder(self, theItem, theParentNode);
                            }
                        });
                    });
                    $('#delete-folder-'+theItem.node_id).click(function() {
                        var confirmationText = "Are you sure you want to delete this folder? This will also delete any folders inside this one. You will not delete any projects in this folder.";
                        bootbox.confirm(confirmationText, function(result) {
                            if (result !== null && result) {
                                var url = '/api/v1/folder/';
                                var postData = JSON.stringify({ 'node_id': theItem.node_id });
                                $.ajax({
                                    type: "DELETE",
                                    url: url,
                                    data: postData,
                                    contentType: 'application/json',
                                    dataType: 'json',
                                    success: function() {
                                        reloadFolder(self, theParentNode, theParentNode);
                                    }
                                });
                            }
                        });
                    });
                    $('#add-folder-'+theItem.node_id).click(function(){
                        $('#afc-'+theItem.node_id).show();
                    });
                    $('#add-folder-input'+theItem.node_id).bind('keyup',function() {
                        var contents = $.trim($(this).val());
                        if(contents === ''){
                            $('#add-folder-button'+theItem.node_id).attr("disabled", "disabled");
                        } else {
                            $('#add-folder-button'+theItem.node_id).removeAttr("disabled");
                        }
                    });

                     $('#add-folder-button'+theItem.node_id).click(function(){
                         var url = '/api/v1/folder/';
                         var postData = JSON.stringify({
                             node_id: theItem.node_id,
                             title: $.trim($('#add-folder-input'+theItem.node_id).val())
                         });
                         $.ajax({
                            type: "PUT",
                            url: url,
                            data: postData,
                            contentType: 'application/json',
                            dataType: 'json',
                            success: function() {
                               reloadFolder(self, theItem, theParentNode);
                            }
                        });
                     });
                    $('#rename-node-'+theItem.node_id).click(function(){
                        $('#rnc-'+theItem.node_id).show();
                    });
                     $('#rename-node-input'+theItem.node_id).bind('keyup',function() {
                        var contents = $.trim($(this).val());
                        if(contents === '' || contents === theItem.name){
                            $('#rename-node-button'+theItem.node_id).attr("disabled", "disabled");
                        } else {
                            $('#rename-node-button'+theItem.node_id).removeAttr("disabled");
                        }
                    });

                     $('#rename-node-button'+theItem.node_id).click(function(){
                         var url = theItem.apiURL+'edit/';
                         var postData = JSON.stringify({
                             name: 'title',
                             value: $.trim($('#rename-node-input'+theItem.node_id).val())
                         });
                         $.ajax({
                            type: "POST",
                            url: url,
                            data: postData,
                            contentType: 'application/json',
                            dataType: 'json',
                            success: function() {
                               reloadFolder(self, theParentNode, theParentNode);
                            }
                        });
                     });

                    $('#add-item-'+theItem.node_id).click(function(){
                        $('#buttons'+theItem.node_id).hide();
                        $('#findNode'+theItem.node_id).show();
                    });

                    $(".project-details").show();
                } else {
                    $(".project-details").hide();
                }
            } else {
                $(".project-details").hide();
            }

        }); // end onSelectedRowsChanged
    };

    function reloadFolder(self, theItem, theParentNode){
        var toReload = theParentNode;
        if (theItem.kind == 'folder') {
            toReload = theItem;
        }
        self.grid.reloadFolder(toReload);
        self.grid.grid.setSelectedRows([]);
        self.grid.grid.resetActiveCell();
    }

    function createProjectDetailHTMLFromTemplate(theItem){
        var detailTemplateSource   = $("#project-detail-template").html();
        Handlebars.registerHelper('commalist', function(items, options) {
            var out = '';

            for(var i=0, l=items.length; i<l; i++) {
                out = out + options.fn(items[i]) + (i!==(l-1) ? ", ":"");
            }
            return out;
        });
        var detailTemplate = Handlebars.compile(detailTemplateSource);
        var detailTemplateContext = {
            theItem: theItem,
            multipleContributors: theItem.contributors.length > 1,
            parentIsSmartFolder: theItem.parentIsSmartFolder
        };
        var displayHTML    = detailTemplate(detailTemplateContext);
        $(".project-details").html(displayHTML);
    }

    //
    // Public methods
    //

    function ProjectOrganizer(selector, options) {
        var self = this;
        var baseOptions = {
            width: '550',
            height: '600',
            columns: [
                ProjectOrganizer.Col.Name,
                dateModifiedColumn,
                contributorsColumn
                ],
            slickgridOptions: {
                editable: true,
                enableAddRow: false,
                enableCellNavigation: true,
                multiSelect: true,
                forceFitColumns: true,
                autoEdit: false
            },
            data: '/api/v1/dashboard/get_dashboard/',  // Where to get the initial data
            fetchUrl: function(folder) {
                return '/api/v1/dashboard/get_dashboard/' + folder.node_id;
            },
            init: hgridInit.bind(self)
        };

        self.selector = selector;
        self.options = $.extend({}, baseOptions, options);
        self.init(self);
    }

    ProjectOrganizer.prototype.init = function() {
        var self = this;
        self.grid = new HGrid(self.selector, self.options);

    };

    return ProjectOrganizer;
}));<commit_msg>Got rid of ko version of project organizer, which wasn't really anything yet.<commit_after><|endoftext|>


<commit_before>/*
 * entry_FRONTPAGE_ADS.js
 *
 * Module for loading styles and scripts related to front page ads only
 *
 */

define( ["jquery"], function( $ ) {

  // matchMedia() polyfill files
  var matchMediaArray = [
        "/wp-content/themes/kaidez-swiss/js/libs/matchMedia.addListener.js",
        "/wp-content/themes/kaidez-swiss/js/libs/matchMedia.js"
      ];

  /*
   * If the browser doesn't support matchMedia(), load in polyfill
   * files via a forEach() loop
   */
  if ( !window.matchMedia ) {
    return matchMediaArray.forEach( function( index ){
      $.getScript( index );
    });
  }

  // Lynda promo ad
  var lyndaPromo = {
        pageElement: "ad-spot-one",
        link: "http://www.lynda.com/promo/trial/Default.aspx?lpk35=7840&utm_medium=ldc-partner&utm_source=SSPRC&utm_content=753&utm_campaign=CD2146&cid=l0:en:pt:le:prosb:s0:0:ind:ssprc:CD2146&bid=753&aid=CD2146",
        imageSource: "http://lynda.directtrack.com/42/2146/753/",
        alt: "10-day free trial"
  };

  // Lynda gift ad
  var lyndaGift = {
        pageElement: "ad-spot-two",
        link: "https://www.lynda.com/giftsubscription/index.aspx?utm_medium=ldc-partner&utm_source=SSPRC&utm_content=11900&utm_campaign=CD2146&cid=l0:en:pt:le:prosb:s0:0:ind:ssprc:CD2146&bid=11900&aid=CD2146",
        imageSource : "http://lynda.directtrack.com/42/2146/11900/",
        alt: "Give lynda.com"
  };

  /*
   * buildAd(): Dynamically build and place ads on the front page.
   * "obj" is an object with 4 values:
   *
   * 1) "pageElement": the element already on the homepage where the
   * ad will load into.
   *
   * 2) "link": the link for the ad
   *
   * 3) "imageSource": the ad's image
   *
   * 4) "alt": the ad's alt tag
   *
   * "opts" is an optional object where extra attribute can be added
   * to either the ad's link or image tag. So if obj is called "myAd"
   * and a "title" attribute called "Some Company" needs to be added to
   * the obj's link tag, this is the configuration:
   *
   *   buildAd( myAd, {
   *     getTarget: "link",
   *     getAttr: "title",
   *     setAttr: "Some Company"
   *   });
   */
  function buildAd( obj, opts ) {

    // Get ad parts from obj
    var

      // The home page element where the ad will load into
      adPageTarget = document.getElementById( obj.pageElement ),

      // The ad's link
      getAdLink = obj.link,

      // The ad's image
      getAdImage = obj.imageSource,

      // The ad image's alt tag value
      getAdAltTag = obj.alt;

    // Dynamically create elements to build the ad
    var

      // Create an anchor tag
      setLinkTag = document.createElement( "a" ),

      // Create an image tag
      setLinkImage = document.createElement( "img" ),

      // Create a document fragment to batch load these elements
      adFragment = document.createDocumentFragment();

    // Set the link tags's href attribute
    setLinkTag.setAttribute( "href", getAdLink );

    // Set the link tags image's src and alt attributes
    $( setLinkImage ).attr({
      "src": getAdImage,
      "alt": getAdAltTag
    });

    /*
     * Build functionality where extra attributes can be added to
     * either an ad's image or link attribute. All this gets done via
     * the "opts" parameter for "buildAd".
     */

    /*
     * If no options are passed, let "opts" be an empty object. This
     * means that "opts" is completely optional
     */
    opts = opts || {};

    // If "getTarget" equals "image", add attributes to the link image
    if( opts.getTarget === "image" ) {
      setLinkImage.setAttribute( opts.getAttr, opts.setAttr );
    } else {

      // If "getTarget" equals "link", add attributes to the link
      if( opts.getTarget === "link" ) {
        setLinkTag.setAttribute( opts.getAttr, opts.setAttr );
      }
    }

   setLinkTag.appendChild( setLinkImage );
   adFragment.appendChild( setLinkTag );
   adPageTarget.appendChild( adFragment );

  }; // end buildAd()

  buildAd( lyndaPromo, {
    getTarget: "image",
    getAttr: "border",
    setAttr: 0
  });

    buildAd( lyndaGift, {
    getTarget: "image",
    getAttr: "border",
    setAttr: 0
  });

  // Set a base media query value that enquire.js always checks
  enquire.register( "( min-width: 768px )", {

    match : function() {},

    unmatch : function() {},

    setup : function() {},

    deferSetup : true

  });

}); // end "define()"<commit_msg>add comments<commit_after>/*
 * entry_FRONTPAGE_ADS.js
 *
 * Module for loading styles and scripts related to front page ads only
 *
 */

define( ["jquery"], function( $ ) {

  // matchMedia() polyfill files
  var matchMediaArray = [
        "/wp-content/themes/kaidez-swiss/js/libs/matchMedia.addListener.js",
        "/wp-content/themes/kaidez-swiss/js/libs/matchMedia.js"
      ];

  /*
   * If the browser doesn't support matchMedia(), load in polyfill
   * files via a forEach() loop
   */
  if ( !window.matchMedia ) {
    return matchMediaArray.forEach( function( index ){
      $.getScript( index );
    });
  }

  // Lynda promo ad
  var lyndaPromo = {
        pageElement: "ad-spot-one",
        link: "http://www.lynda.com/promo/trial/Default.aspx?lpk35=7840&utm_medium=ldc-partner&utm_source=SSPRC&utm_content=753&utm_campaign=CD2146&cid=l0:en:pt:le:prosb:s0:0:ind:ssprc:CD2146&bid=753&aid=CD2146",
        imageSource: "http://lynda.directtrack.com/42/2146/753/",
        alt: "10-day free trial"
  };

  // Lynda gift ad
  var lyndaGift = {
        pageElement: "ad-spot-two",
        link: "https://www.lynda.com/giftsubscription/index.aspx?utm_medium=ldc-partner&utm_source=SSPRC&utm_content=11900&utm_campaign=CD2146&cid=l0:en:pt:le:prosb:s0:0:ind:ssprc:CD2146&bid=11900&aid=CD2146",
        imageSource : "http://lynda.directtrack.com/42/2146/11900/",
        alt: "Give lynda.com"
  };

  /*
   * buildAd(): Dynamically build and place ads on the front page.
   * "obj" is an object with 4 values:
   *
   * 1) "pageElement": the element already on the homepage where the
   * ad will load into.
   *
   * 2) "link": the link for the ad
   *
   * 3) "imageSource": the ad's image
   *
   * 4) "alt": the ad's alt tag
   *
   * "opts" is an optional object where extra attribute can be added
   * to either the ad's link or image tag. So if obj is called "myAd"
   * and a "title" attribute called "Some Company" needs to be added to
   * the obj's link tag, this is the configuration:
   *
   *       buildAd( myAd, {
   *         getTarget: "link",
   *         getAttr: "title",
   *         setAttr: "Some Company"
   *       });
   */
  function buildAd( obj, opts ) {

    // Get ad parts from obj
    var

      // The home page element where the ad will load into
      adPageTarget = document.getElementById( obj.pageElement ),

      // The ad's link
      getAdLink = obj.link,

      // The ad's image
      getAdImage = obj.imageSource,

      // The ad image's alt tag value
      getAdAltTag = obj.alt;

    // Dynamically create elements to build the ad
    var

      // Create an anchor tag
      setLinkTag = document.createElement( "a" ),

      // Create an image tag
      setLinkImage = document.createElement( "img" ),

      // Create a document fragment to batch load these elements
      adFragment = document.createDocumentFragment();

    // Set the link tags's href attribute
    setLinkTag.setAttribute( "href", getAdLink );

    // Set the link tags image's src and alt attributes
    $( setLinkImage ).attr({
      "src": getAdImage,
      "alt": getAdAltTag
    });

    /*
     * Build functionality where extra attributes can be added to
     * either an ad's image or link attribute. All this gets done via
     * the "opts" parameter for "buildAd".
     */

    /*
     * If no options are passed, let "opts" be an empty object. This
     * means that "opts" is completely optional
     */
    opts = opts || {};

    // If "getTarget" equals "image", add attributes to the link image
    if( opts.getTarget === "image" ) {
      setLinkImage.setAttribute( opts.getAttr, opts.setAttr );
    } else {

      // If "getTarget" equals "link", add attributes to the link
      if( opts.getTarget === "link" ) {
        setLinkTag.setAttribute( opts.getAttr, opts.setAttr );
      }
    }

   // put image in link tag
   setLinkTag.appendChild( setLinkImage );

   // put link in document fragment
   adFragment.appendChild( setLinkTag );

   //put document fragment in page element
   adPageTarget.appendChild( adFragment );

  }; // end buildAd()

  // START BUILDING ADS

  // Lynda 10-day promo
  buildAd( lyndaPromo, {
    getTarget: "image",
    getAttr: "border",
    setAttr: 0
  });

  // Lynda gift
  buildAd( lyndaGift, {
    getTarget: "image",
    getAttr: "border",
    setAttr: 0
  });

  // Set a base media query value that enquire.js always checks
  enquire.register( "( min-width: 768px )", {

    match : function() {},

    unmatch : function() {},

    setup : function() {},

    deferSetup : true

  });

}); // end "define()"<|endoftext|>


<commit_before>function date_parse_from_format (format, dateArg) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: strtotime
	// -    depends on: date
	// -    depends on: date_parse
	// *     example 1: date_parse_from_format('j.n.Y H:iP', '6.1.2009 13:00+01:00');
	// *     returns 1: {year : 2006, month: 12, day: 12, hour: 10, minute: 0, second: 0, fraction: 0.5, warning_count: 0, warnings: [], error_count: 0, errors: [], is_localtime: false, zone_type: 1, zone: -60, is_dst:false}

    var ts=0, newtime=0, retObj={};

    try {
        ts = strtotime(dateArg);
        newtime = strtotime(date(format, ts));
        retObj = date_parse(newtime);
    }
    catch (e) {
        return false; // Presumably returns false, as with date_parse()
    }

    // Fix: need to add the following as well (base on dateArg for zone info, and use newtime for is_dst?)
    //zone_type: TIMELIB_ZONETYPE_OFFSET 1, TIMELIB_ZONETYPE_ABBR   2, TIMELIB_ZONETYPE_ID     3
    //zone: -60
    //is_dst: false

    return retObj;
}<commit_msg>Fix/build a little on date_parse_from_format<commit_after>function date_parse_from_format (format, dateArg) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: strtotime
	// -    depends on: date
	// -    depends on: date_parse
	// *     example 1: date_parse_from_format('j.n.Y H:iP', '6.1.2009 13:00+01:00');
	// *     returns 1: {year : 2006, month: 12, day: 12, hour: 10, minute: 0, second: 0, fraction: 0.5, warning_count: 0, warnings: [], error_count: 0, errors: [], is_localtime: false, zone_type: 1, zone: -60, is_dst:false}

    var newtime=0, retObj={};

    var _dst = function (t) {
        // Calculate Daylight Saving Time (derived from gettimeofday() code)
        var dst=0;
        var jan1 = new Date(t.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
        var june1 = new Date(t.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
        var temp = jan1.toUTCString();
        var jan2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
        temp = june1.toUTCString();
        var june2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
        var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
        var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);

        if (std_time_offset === daylight_time_offset) {
            dst = false; // daylight savings time is NOT observed
        }
        else {
            // positive is southern, negative is northern hemisphere
            var hemisphere = std_time_offset - daylight_time_offset;
            if (hemisphere >= 0) {
                std_time_offset = daylight_time_offset;
            }
            dst = true; // daylight savings time is observed
        }
        return dst;
    };

    try {
        newtime = 0; // fix: needs to use format, dateArg to return a time
        retObj = date_parse(newtime);
    }
    catch (e) {
        return false; // Presumably returns false, as with date_parse()
    }

    retObj.is_dst = _dst(newtime);

    // Fix: need to add the following as well
    //zone_type: TIMELIB_ZONETYPE_OFFSET 1, TIMELIB_ZONETYPE_ABBR   2, TIMELIB_ZONETYPE_ID     3
    //zone: -60

    return retObj;
}<|endoftext|>


<commit_before>/**
 * Component definition for the frost-chart-axis-tick-svg component
 */

import Ember from 'ember'
const {String: EmberString, isNone, run} = Ember
import computed, {readOnly} from 'ember-computed-decorators'
import {Component} from 'ember-frost-core'
import {PropTypes} from 'ember-prop-types'

export default Component.extend({

  // == Dependencies ==========================================================

  // == Keyword Properties ====================================================

  attributeBindings: ['transform'],
  tagName: 'g',

  // == PropTypes =============================================================

  propTypes: {
    // options
    axis: PropTypes.string.isRequired,
    coordinate: PropTypes.number.isRequired

    // state
  },

  getDefaultProps () {
    return {
      // options
      coordinate: null

      // state
    }
  },

  // == Computed Properties ===================================================

  @readOnly
  @computed('coordinate')
  transform (coordinate) {
    if (isNone(coordinate)) {
      return EmberString.htmlSafe('')
    }

    const axis = this.get('axis')
    const x = axis === 'x' ? coordinate : 0
    const y = axis === 'y' ? coordinate : 0

    return `translate(${x}, ${y})`
  },

  // == Functions =============================================================

  _dispatchRenderedTick () {
    this.dispatch({
      type: 'RENDERED_TICK',
      axis: this.get('axis'),
      // FIXME: #8 Fixe height and width measurement calculation
      tick: {
        height: this.$().outerHeight(true),
        width: this.$().outerWidth(true)
      }
    })
  },

  // == DOM Events ============================================================

  // == Lifecycle Hooks =======================================================

  didInsertElement () {
    this._super(...arguments)
    run.scheduleOnce('afterRender', this, this._dispatchRenderedTick)
  }

  // == Actions ===============================================================

})
<commit_msg>Fixed issue with NaN coordinate axis tick svg<commit_after>/**
 * Component definition for the frost-chart-axis-tick-svg component
 */

import Ember from 'ember'
const {String: EmberString, isNone, run} = Ember
import computed, {readOnly} from 'ember-computed-decorators'
import {Component} from 'ember-frost-core'
import {PropTypes} from 'ember-prop-types'

export default Component.extend({

  // == Dependencies ==========================================================

  // == Keyword Properties ====================================================

  attributeBindings: ['transform'],
  tagName: 'g',

  // == PropTypes =============================================================

  propTypes: {
    // options
    axis: PropTypes.string.isRequired,
    coordinate: PropTypes.number.isRequired

    // state
  },

  getDefaultProps () {
    return {
      // options
      coordinate: null

      // state
    }
  },

  // == Computed Properties ===================================================

  @readOnly
  @computed('coordinate')
  transform (coordinate) {
    if (isNone(coordinate) && isNaN(coordinate)) {
      return EmberString.htmlSafe('')
    }

    const axis = this.get('axis')
    const x = axis === 'x' ? coordinate : 0
    const y = axis === 'y' ? coordinate : 0

    return `translate(${x}, ${y})`
  },

  // == Functions =============================================================

  _dispatchRenderedTick () {
    this.dispatch({
      type: 'RENDERED_TICK',
      axis: this.get('axis'),
      // FIXME: #8 Fixe height and width measurement calculation
      tick: {
        height: this.$().outerHeight(true),
        width: this.$().outerWidth(true)
      }
    })
  },

  // == DOM Events ============================================================

  // == Lifecycle Hooks =======================================================

  didInsertElement () {
    this._super(...arguments)
    run.scheduleOnce('afterRender', this, this._dispatchRenderedTick)
  }

  // == Actions ===============================================================

})
<|endoftext|>


<commit_before>// @flow
/* eslint-disable global-require */

const BABEL_ALLOWED_VERSIONS = new Set([6, 7])
const DEFAULT_STATICS = [
  '.png',
  '.jpg',
  '.woff',
  '.woff2',
  '.ttf',
  '.otf',
  '.eot',
  '.svg',
  '.webp',
  '.jpeg',
  '.gif',
  '.apng',
  '.bmp',
]

function getPresetComponents({
  report: { cli: reportCLI = true } = {},
  transform: {
    cson = false,
    css = true,
    coffee = false,
    json = true,
    json5 = false,
    babel = false,
    js = true,
    less = false,
    sass = false,
    stylus = false,
    postcss = false,
    typescript = false,
  } = {},
  development = process.env.NODE_ENV !== 'production',
  generate: { js: generateJS = true, css: generateCSS = true, html: generateHTML = true } = {},
  optimize: { js: optimizeJS = !development, css: optimizeCSS = !development, html: optimizeHTML = !development } = {},
  statics = [],
  resolve = true,
  target = 'browser',
}: {
  report?: {
    cli?: boolean,
  },
  transform?: {
    cson?: boolean,
    css?: boolean,
    coffee?: boolean,
    json?: boolean,
    json5?: boolean,
    babel?: 6 | 7 | false,
    js?: boolean | { env: { [string]: string } },
    less?: boolean,
    sass?: boolean,
    stylus?: boolean,
    postcss?: boolean,
    typescript?: boolean,
  },
  development?: boolean,
  generate?: {
    js?: boolean,
    csss?: boolean,
    html?: boolean,
  },
  optimize?: {
    js?: boolean,
    css?: boolean,
    html?: boolean,
  },
  statics?: Array<string>,
  resolve?: boolean | { aliases: Object },
  target: 'node' | 'browser',
}) {
  const components = []
  const extensions = {
    css: new Set(['.css']),
    js: new Set(['.js', '.mjs']),
  }

  if (reportCLI) {
    components.push(require('pundle-reporter-cli')())
  }
  if (cson) {
    extensions.js.add('.cson')
    components.push(require('pundle-transformer-cson')())
  }
  if (coffee) {
    extensions.js.add('.coffee')
    components.push(require('pundle-transformer-coffee')())
  }
  if (json) {
    extensions.js.add('.json')
    components.push(require('pundle-transformer-json')())
  }
  if (json5) {
    if (!json) {
      extensions.js.add('.json')
    }
    extensions.js.add('.json5')
    components.push(
      require('pundle-transformer-json5')({
        extensions: json ? ['.json5'] : ['.json', '.json5'],
      }),
    )
  }
  if (babel) {
    if (!BABEL_ALLOWED_VERSIONS.has(babel)) {
      throw new Error(
        `preset-default expects config.babel to be any of ${Array.from(BABEL_ALLOWED_VERSIONS).join(
          ', ',
        )} but got: ${babel} (type ${typeof babel})`,
      )
    }
    components.push(
      require('pundle-transformer-babel')({
        version: babel,
      }),
    )
  }
  if (less) {
    extensions.css.add('.less')
    components.push(require('pundle-transformer-less')())
  }
  if (sass) {
    extensions.css.add('.scss')
    components.push(require('pundle-transformer-sass')())
  }
  if (stylus) {
    extensions.css.add('.styl')
    components.push(require('pundle-transformer-stylus')())
  }
  if (postcss) {
    components.push(require('pundle-transformer-postcss')())
  }
  if (typescript) {
    extensions.js.add('.ts')
    extensions.js.add('.tsx')
    components.push(require('pundle-transformer-typescript')())
  }
  if (js) {
    components.push(
      require('pundle-transformer-js')({
        env: js && js.env ? js.env : {},
        browser: target === 'browser',
      }),
    )
  }
  components.push(
    require('pundle-transformer-static')({
      extensions: statics.concat(DEFAULT_STATICS),
    }),
  )
  if (css) {
    components.push(
      require('pundle-transformer-css')({
        development,
        extensions: Array.from(extensions.css),
      }),
    )
  }
  if (resolve) {
    const resolverAliases = {
      ...(target === 'browser' ? require('pundle-resolver-aliases-browser') : {}),
      ...(resolve && resolve.aliases ? resolve.aliases : {}),
    }
    components.push(
      require('pundle-resolver-default')({
        formats: {
          js: Array.from(extensions.js),
          css: Array.from(extensions.css),
          static: statics.concat(DEFAULT_STATICS),
          ...(generateHTML ? { html: ['.html'] } : {}),
        },
        aliases: resolverAliases,
      }),
    )
  }
  if (generateJS) {
    components.push(require('pundle-chunk-generator-js')())
  }
  if (generateCSS) {
    components.push(require('pundle-chunk-generator-css')())
  }
  if (generateHTML) {
    components.push(require('pundle-chunk-generator-html')())
  }
  components.push(require('pundle-chunk-generator-static')())
  if (optimizeJS) {
    components.push(require('pundle-job-transformer-js-common')())
    components.push(
      require('pundle-chunk-transformer-js-uglify')({
        uglifier: 'terser',
      }),
    )
  }
  if (optimizeCSS) {
    /* TODO: Implement css chunk transformer */
  }
  if (optimizeHTML) {
    /* TODO: Implement html chunk transformer */
  }

  return components
}

module.exports = getPresetComponents
<commit_msg>:art: Minor inline in preset-default<commit_after>// @flow
/* eslint-disable global-require */

const BABEL_ALLOWED_VERSIONS = new Set([6, 7])
const DEFAULT_STATICS = [
  '.png',
  '.jpg',
  '.woff',
  '.woff2',
  '.ttf',
  '.otf',
  '.eot',
  '.svg',
  '.webp',
  '.jpeg',
  '.gif',
  '.apng',
  '.bmp',
]

function getPresetComponents({
  report: { cli: reportCLI = true } = {},
  transform: {
    cson = false,
    css = true,
    coffee = false,
    json = true,
    json5 = false,
    babel = false,
    js = true,
    less = false,
    sass = false,
    stylus = false,
    postcss = false,
    typescript = false,
  } = {},
  development = process.env.NODE_ENV !== 'production',
  generate: { js: generateJS = true, css: generateCSS = true, html: generateHTML = true } = {},
  optimize: { js: optimizeJS = !development, css: optimizeCSS = !development, html: optimizeHTML = !development } = {},
  statics = [],
  resolve = true,
  target = 'browser',
}: {
  report?: {
    cli?: boolean,
  },
  transform?: {
    cson?: boolean,
    css?: boolean,
    coffee?: boolean,
    json?: boolean,
    json5?: boolean,
    babel?: 6 | 7 | false,
    js?: boolean | { env: { [string]: string } },
    less?: boolean,
    sass?: boolean,
    stylus?: boolean,
    postcss?: boolean,
    typescript?: boolean,
  },
  development?: boolean,
  generate?: {
    js?: boolean,
    csss?: boolean,
    html?: boolean,
  },
  optimize?: {
    js?: boolean,
    css?: boolean,
    html?: boolean,
  },
  statics?: Array<string>,
  resolve?: boolean | { aliases: Object },
  target: 'node' | 'browser',
}) {
  const components = []
  const extensions = {
    css: new Set(['.css']),
    js: new Set(['.js', '.mjs']),
  }

  if (reportCLI) {
    components.push(require('pundle-reporter-cli')())
  }
  if (cson) {
    extensions.js.add('.cson')
    components.push(require('pundle-transformer-cson')())
  }
  if (coffee) {
    extensions.js.add('.coffee')
    components.push(require('pundle-transformer-coffee')())
  }
  if (json) {
    extensions.js.add('.json')
    components.push(require('pundle-transformer-json')())
  }
  if (json5) {
    extensions.js.add('.json')
    extensions.js.add('.json5')
    components.push(
      require('pundle-transformer-json5')({
        extensions: json ? ['.json5'] : ['.json', '.json5'],
      }),
    )
  }
  if (babel) {
    if (!BABEL_ALLOWED_VERSIONS.has(babel)) {
      throw new Error(
        `preset-default expects config.babel to be any of ${Array.from(BABEL_ALLOWED_VERSIONS).join(
          ', ',
        )} but got: ${babel} (type ${typeof babel})`,
      )
    }
    components.push(
      require('pundle-transformer-babel')({
        version: babel,
      }),
    )
  }
  if (less) {
    extensions.css.add('.less')
    components.push(require('pundle-transformer-less')())
  }
  if (sass) {
    extensions.css.add('.scss')
    components.push(require('pundle-transformer-sass')())
  }
  if (stylus) {
    extensions.css.add('.styl')
    components.push(require('pundle-transformer-stylus')())
  }
  if (postcss) {
    components.push(require('pundle-transformer-postcss')())
  }
  if (typescript) {
    extensions.js.add('.ts')
    extensions.js.add('.tsx')
    components.push(require('pundle-transformer-typescript')())
  }
  if (js) {
    components.push(
      require('pundle-transformer-js')({
        env: js && js.env ? js.env : {},
        browser: target === 'browser',
      }),
    )
  }
  components.push(
    require('pundle-transformer-static')({
      extensions: statics.concat(DEFAULT_STATICS),
    }),
  )
  if (css) {
    components.push(
      require('pundle-transformer-css')({
        development,
        extensions: Array.from(extensions.css),
      }),
    )
  }
  if (resolve) {
    const resolverAliases = {
      ...(target === 'browser' ? require('pundle-resolver-aliases-browser') : {}),
      ...(resolve && resolve.aliases ? resolve.aliases : {}),
    }
    components.push(
      require('pundle-resolver-default')({
        formats: {
          js: Array.from(extensions.js),
          css: Array.from(extensions.css),
          static: statics.concat(DEFAULT_STATICS),
          ...(generateHTML ? { html: ['.html'] } : {}),
        },
        aliases: resolverAliases,
      }),
    )
  }
  if (generateJS) {
    components.push(require('pundle-chunk-generator-js')())
  }
  if (generateCSS) {
    components.push(require('pundle-chunk-generator-css')())
  }
  if (generateHTML) {
    components.push(require('pundle-chunk-generator-html')())
  }
  components.push(require('pundle-chunk-generator-static')())
  if (optimizeJS) {
    components.push(require('pundle-job-transformer-js-common')())
    components.push(
      require('pundle-chunk-transformer-js-uglify')({
        uglifier: 'terser',
      }),
    )
  }
  if (optimizeCSS) {
    /* TODO: Implement css chunk transformer */
  }
  if (optimizeHTML) {
    /* TODO: Implement html chunk transformer */
  }

  return components
}

module.exports = getPresetComponents
<|endoftext|>


<commit_before>import { simpleParser } from "#SRC/js/utils/ParserUtil";
import Transaction from "#SRC/js/structs/Transaction";
import Util from "#SRC/js/utils/Util";

import { JSONParser as constraints } from "./serviceForm/MultiContainerConstraints";
import { JSONParser as fetch } from "./serviceForm/JSONReducers/Artifacts";
import { JSONParser as environmentVariables } from "./serviceForm/JSONReducers/MultiContainerEnvironmentVariables";
import { JSONParser as healthChecks } from "./serviceForm/JSONReducers/HealthChecks";
import { JSONParser as volumes } from "./serviceForm/JSONReducers/Volumes";
import { JSONParser as labels } from "./serviceForm/JSONReducers/Labels";
import { JSONParser as portDefinitions } from "./serviceForm/PortDefinitions";
import { JSONParser as portMappings } from "./serviceForm/PortMappings";
import { JSONParser as residency } from "./serviceForm/JSONReducers/MultiContainerResidency";
import { JSONParser as scaling } from "./serviceForm/MultiContainerScaling";
import { JSONParser as networks } from "./serviceForm/JSONReducers/Networks";
import { JSONParser as multiContainerNetwork } from "./serviceForm/MultiContainerNetwork";
import { JSONParser as volumeMounts } from "./serviceForm/MultiContainerVolumes";
import { JSONParser as containers } from "./serviceForm/JSONReducers/Containers";

module.exports = [
  simpleParser(["id"]),
  simpleParser(["instances"]),
  simpleParser(["cpus"]),
  simpleParser(["mem"]),
  simpleParser(["disk"]),
  simpleParser(["gpus"]),
  simpleParser(["cmd"]),
  function scheduling(state) {
    if (state == null) {
      return [];
    }

    if (state.scheduling == null) {
      return [];
    }

    return new Transaction(["scheduling"], Util.deepCopy(state.scheduling));
  },
  constraints,
  containers,
  environmentVariables,
  fetch,
  healthChecks,
  labels,
  volumes,
  multiContainerNetwork,
  networks,
  portDefinitions,
  portMappings, // Note: must come after portDefinitions, as it uses its information!
  residency,
  scaling,
  volumeMounts
];
<commit_msg>refactor: combine conditions<commit_after>import { simpleParser } from "#SRC/js/utils/ParserUtil";
import Transaction from "#SRC/js/structs/Transaction";
import Util from "#SRC/js/utils/Util";

import { JSONParser as constraints } from "./serviceForm/MultiContainerConstraints";
import { JSONParser as fetch } from "./serviceForm/JSONReducers/Artifacts";
import { JSONParser as environmentVariables } from "./serviceForm/JSONReducers/MultiContainerEnvironmentVariables";
import { JSONParser as healthChecks } from "./serviceForm/JSONReducers/HealthChecks";
import { JSONParser as volumes } from "./serviceForm/JSONReducers/Volumes";
import { JSONParser as labels } from "./serviceForm/JSONReducers/Labels";
import { JSONParser as portDefinitions } from "./serviceForm/PortDefinitions";
import { JSONParser as portMappings } from "./serviceForm/PortMappings";
import { JSONParser as residency } from "./serviceForm/JSONReducers/MultiContainerResidency";
import { JSONParser as scaling } from "./serviceForm/MultiContainerScaling";
import { JSONParser as networks } from "./serviceForm/JSONReducers/Networks";
import { JSONParser as multiContainerNetwork } from "./serviceForm/MultiContainerNetwork";
import { JSONParser as volumeMounts } from "./serviceForm/MultiContainerVolumes";
import { JSONParser as containers } from "./serviceForm/JSONReducers/Containers";

module.exports = [
  simpleParser(["id"]),
  simpleParser(["instances"]),
  simpleParser(["cpus"]),
  simpleParser(["mem"]),
  simpleParser(["disk"]),
  simpleParser(["gpus"]),
  simpleParser(["cmd"]),
  function scheduling(state) {
    if (state == null || state.scheduling == null) {
      return [];
    }

    return new Transaction(["scheduling"], Util.deepCopy(state.scheduling));
  },
  constraints,
  containers,
  environmentVariables,
  fetch,
  healthChecks,
  labels,
  volumes,
  multiContainerNetwork,
  networks,
  portDefinitions,
  portMappings, // Note: must come after portDefinitions, as it uses its information!
  residency,
  scaling,
  volumeMounts
];
<|endoftext|>


<commit_before>// Copyright (C) 2016 The Android Open Source Project
//
// 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.
(function() {
  'use strict';

  var COMMIT_MESSAGE_PATH = '/COMMIT_MSG';

  Polymer({
    is: 'gr-diff-view',

    /**
     * Fired when the title of the page should change.
     *
     * @event title-change
     */

    properties: {
      prefs: {
        type: Object,
        notify: true,
      },
      /**
       * URL params passed from the router.
       */
      params: {
        type: Object,
        observer: '_paramsChanged',
      },
      keyEventTarget: {
        type: Object,
        value: function() { return document.body; },
      },
      changeViewState: {
        type: Object,
        notify: true,
        value: function() { return {}; },
      },

      _patchRange: Object,
      _change: Object,
      _changeNum: String,
      _diff: Object,
      _fileList: {
        type: Array,
        value: function() { return []; },
      },
      _path: {
        type: String,
        observer: '_pathChanged',
      },
      _loggedIn: {
        type: Boolean,
        value: false,
      },
      _xhrPromise: Object,  // Used for testing.
    },

    behaviors: [
      Gerrit.KeyboardShortcutBehavior,
      Gerrit.RESTClientBehavior,
    ],

    ready: function() {
      app.accountReady.then(function() {
        this._loggedIn = app.loggedIn;
        if (this._loggedIn) {
          this._setReviewed(true);
        }
      }.bind(this));
    },

    attached: function() {
      if (this._path) {
        this.fire('title-change',
            {title: this._computeFileDisplayName(this._path)});
      }
      window.addEventListener('resize', this._boundWindowResizeHandler);
    },

    detached: function() {
      window.removeEventListener('resize', this._boundWindowResizeHandler);
    },

    _handleReviewedChange: function(e) {
      this._setReviewed(Polymer.dom(e).rootTarget.checked);
    },

    _setReviewed: function(reviewed) {
      this.$.reviewed.checked = reviewed;
      var method = reviewed ? 'PUT' : 'DELETE';
      var url = this.changeBaseURL(this._changeNum,
          this._patchRange.patchNum) + '/files/' +
          encodeURIComponent(this._path) + '/reviewed';
      this._send(method, url).catch(function(err) {
        alert('Couldn’t change file review status. Check the console ' +
            'and contact the PolyGerrit team for assistance.');
        throw err;
      }.bind(this));
    },

    _handleKey: function(e) {
      if (this.shouldSupressKeyboardShortcut(e)) { return; }

      switch (e.keyCode) {
        case 219:  // '['
          e.preventDefault();
          this._navToFile(this._fileList, -1);
          break;
        case 221:  // ']'
          e.preventDefault();
          this._navToFile(this._fileList, 1);
          break;
        case 78:  // 'n'
          if (e.shiftKey) {
            this.$.diff.scrollToNextCommentThread();
          } else {
            this.$.diff.scrollToNextDiffChunk();
          }
          break;
        case 80:  // 'p'
          if (e.shiftKey) {
            this.$.diff.scrollToPreviousCommentThread();
          } else {
            this.$.diff.scrollToPreviousDiffChunk();
          }
          break;
        case 65:  // 'a'
          if (!this._loggedIn) { return; }

          this.set('changeViewState.showReplyDialog', true);
          /* falls through */ // required by JSHint
        case 85:  // 'u'
          if (this._changeNum && this._patchRange.patchNum) {
            e.preventDefault();
            page.show(this._computeChangePath(
                this._changeNum,
                this._patchRange.patchNum,
                this._change && this._change.revisions));
          }
          break;
        case 188:  // ','
          this.$.diff.showDiffPreferences();
          break;
      }
    },

    _handleDiffRender: function() {
      if (window.location.hash.length > 0) {
        this.$.diff.scrollToLine(
            parseInt(window.location.hash.substring(1), 10));
      }
    },

    _navToFile: function(fileList, direction) {
      if (fileList.length == 0) { return; }

      var idx = fileList.indexOf(this._path) + direction;
      if (idx < 0 || idx > fileList.length - 1) {
        page.show(this._computeChangePath(
            this._changeNum,
            this._patchRange.patchNum,
            this._change && this._change.revisions));
        return;
      }
      page.show(this._computeDiffURL(this._changeNum,
                                     this._patchRange,
                                     fileList[idx]));
    },

    _paramsChanged: function(value) {
      if (value.view != this.tagName.toLowerCase()) { return; }

      this._changeNum = value.changeNum;
      this._patchRange = {
        patchNum: value.patchNum,
        basePatchNum: value.basePatchNum || 'PARENT',
      };
      this._path = value.path;

      this.fire('title-change',
          {title: this._computeFileDisplayName(this._path)});

      // When navigating away from the page, there is a possibility that the
      // patch number is no longer a part of the URL (say when navigating to
      // the top-level change info view) and therefore undefined in `params`.
      if (!this._patchRange.patchNum) {
        return;
      }

      this.$.diff.reload();
    },

    _pathChanged: function(path) {
      if (this._fileList.length == 0) { return; }

      this.set('changeViewState.selectedFileIndex',
          this._fileList.indexOf(path));

      if (this._loggedIn) {
        this._setReviewed(true);
      }
    },

    _computeDiffURL: function(changeNum, patchRange, path) {
      var patchStr = patchRange.patchNum;
      if (patchRange.basePatchNum != null &&
          patchRange.basePatchNum != 'PARENT') {
        patchStr = patchRange.basePatchNum + '..' + patchRange.patchNum;
      }
      return '/c/' + changeNum + '/' + patchStr + '/' + path;
    },

    _computeAvailablePatches: function(revisions) {
      var patchNums = [];
      for (var rev in revisions) {
        patchNums.push(revisions[rev]._number);
      }
      return patchNums.sort(function(a, b) { return a - b; });
    },

    _computeChangePath: function(changeNum, patchNum, revisions) {
      var base = '/c/' + changeNum + '/';

      // The change may not have loaded yet, making revisions unavailable.
      if (!revisions) {
        return base + patchNum;
      }

      var latestPatchNum = -1;
      for (var rev in revisions) {
        latestPatchNum = Math.max(latestPatchNum, revisions[rev]._number);
      }
      if (parseInt(patchNum, 10) != latestPatchNum) {
        return base + patchNum;
      }

      return base;
    },

    _computeFileDisplayName: function(path) {
      return path == COMMIT_MESSAGE_PATH ? 'Commit message' : path;
    },

    _computeChangeDetailPath: function(changeNum) {
      return '/changes/' + changeNum + '/detail';
    },

    _computeChangeDetailQueryParams: function() {
      return {O: this.listChangesOptionsToHex(
          this.ListChangesOption.ALL_REVISIONS
      )};
    },

    _computeFilesPath: function(changeNum, patchNum) {
      return this.changeBaseURL(changeNum, patchNum) + '/files';
    },

    _computeProjectConfigPath: function(project) {
      return '/projects/' + encodeURIComponent(project) + '/config';
    },

    _computeFileSelected: function(path, currentPath) {
      return path == currentPath;
    },

    _computeKeyNav: function(path, selectedPath, fileList) {
      var selectedIndex = fileList.indexOf(selectedPath);
      if (fileList.indexOf(path) == selectedIndex - 1) {
        return '[';
      }
      if (fileList.indexOf(path) == selectedIndex + 1) {
        return ']';
      }
      return '';
    },

    _handleFileTap: function(e) {
      this.$.dropdown.close();
    },

    _handleMobileSelectChange: function(e) {
      var path = Polymer.dom(e).rootTarget.value;
      page.show(
          this._computeDiffURL(this._changeNum, this._patchRange, path));
    },

    _handleFilesResponse: function(e, req) {
      this._fileList = Object.keys(e.detail.response).sort();
    },

    _showDropdownTapHandler: function(e) {
      this.$.dropdown.open();
    },

    _send: function(method, url) {
      var xhr = document.createElement('gr-request');
      this._xhrPromise = xhr.send({
        method: method,
        url: url,
      });
      return this._xhrPromise;
    },
  });
})();
<commit_msg>Fix failing gr-diff-view test<commit_after>// Copyright (C) 2016 The Android Open Source Project
//
// 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.
(function() {
  'use strict';

  var COMMIT_MESSAGE_PATH = '/COMMIT_MSG';

  Polymer({
    is: 'gr-diff-view',

    /**
     * Fired when the title of the page should change.
     *
     * @event title-change
     */

    properties: {
      prefs: {
        type: Object,
        notify: true,
      },
      /**
       * URL params passed from the router.
       */
      params: {
        type: Object,
        observer: '_paramsChanged',
      },
      keyEventTarget: {
        type: Object,
        value: function() { return document.body; },
      },
      changeViewState: {
        type: Object,
        notify: true,
        value: function() { return {}; },
      },

      _patchRange: Object,
      _change: Object,
      _changeNum: String,
      _diff: Object,
      _fileList: {
        type: Array,
        value: function() { return []; },
      },
      _path: {
        type: String,
        observer: '_pathChanged',
      },
      _loggedIn: {
        type: Boolean,
        value: false,
      },
      _xhrPromise: Object,  // Used for testing.
    },

    behaviors: [
      Gerrit.KeyboardShortcutBehavior,
      Gerrit.RESTClientBehavior,
    ],

    ready: function() {
      app.accountReady.then(function() {
        this._loggedIn = app.loggedIn;
        if (this._loggedIn) {
          this._setReviewed(true);
        }
      }.bind(this));
    },

    attached: function() {
      if (this._path) {
        this.fire('title-change',
            {title: this._computeFileDisplayName(this._path)});
      }
      window.addEventListener('resize', this._boundWindowResizeHandler);
    },

    detached: function() {
      window.removeEventListener('resize', this._boundWindowResizeHandler);
    },

    _handleReviewedChange: function(e) {
      this._setReviewed(Polymer.dom(e).rootTarget.checked);
    },

    _setReviewed: function(reviewed) {
      this.$.reviewed.checked = reviewed;
      var method = reviewed ? 'PUT' : 'DELETE';
      var url = this.changeBaseURL(this._changeNum,
          this._patchRange.patchNum) + '/files/' +
          encodeURIComponent(this._path) + '/reviewed';
      this._send(method, url).catch(function(err) {
        alert('Couldn’t change file review status. Check the console ' +
            'and contact the PolyGerrit team for assistance.');
        throw err;
      }.bind(this));
    },

    _handleKey: function(e) {
      if (this.shouldSupressKeyboardShortcut(e)) { return; }

      switch (e.keyCode) {
        case 219:  // '['
          e.preventDefault();
          this._navToFile(this._fileList, -1);
          break;
        case 221:  // ']'
          e.preventDefault();
          this._navToFile(this._fileList, 1);
          break;
        case 78:  // 'n'
          e.preventDefault();
          if (e.shiftKey) {
            this.$.diff.scrollToNextCommentThread();
          } else {
            this.$.diff.scrollToNextDiffChunk();
          }
          break;
        case 80:  // 'p'
          e.preventDefault();
          if (e.shiftKey) {
            this.$.diff.scrollToPreviousCommentThread();
          } else {
            this.$.diff.scrollToPreviousDiffChunk();
          }
          break;
        case 65:  // 'a'
          if (!this._loggedIn) { return; }

          this.set('changeViewState.showReplyDialog', true);
          /* falls through */ // required by JSHint
        case 85:  // 'u'
          if (this._changeNum && this._patchRange.patchNum) {
            e.preventDefault();
            page.show(this._computeChangePath(
                this._changeNum,
                this._patchRange.patchNum,
                this._change && this._change.revisions));
          }
          break;
        case 188:  // ','
          e.preventDefault();
          this.$.diff.showDiffPreferences();
          break;
      }
    },

    _handleDiffRender: function() {
      if (window.location.hash.length > 0) {
        this.$.diff.scrollToLine(
            parseInt(window.location.hash.substring(1), 10));
      }
    },

    _navToFile: function(fileList, direction) {
      if (fileList.length == 0) { return; }

      var idx = fileList.indexOf(this._path) + direction;
      if (idx < 0 || idx > fileList.length - 1) {
        page.show(this._computeChangePath(
            this._changeNum,
            this._patchRange.patchNum,
            this._change && this._change.revisions));
        return;
      }
      page.show(this._computeDiffURL(this._changeNum,
                                     this._patchRange,
                                     fileList[idx]));
    },

    _paramsChanged: function(value) {
      if (value.view != this.tagName.toLowerCase()) { return; }

      this._changeNum = value.changeNum;
      this._patchRange = {
        patchNum: value.patchNum,
        basePatchNum: value.basePatchNum || 'PARENT',
      };
      this._path = value.path;

      this.fire('title-change',
          {title: this._computeFileDisplayName(this._path)});

      // When navigating away from the page, there is a possibility that the
      // patch number is no longer a part of the URL (say when navigating to
      // the top-level change info view) and therefore undefined in `params`.
      if (!this._patchRange.patchNum) {
        return;
      }

      this.$.diff.reload();
    },

    _pathChanged: function(path) {
      if (this._fileList.length == 0) { return; }

      this.set('changeViewState.selectedFileIndex',
          this._fileList.indexOf(path));

      if (this._loggedIn) {
        this._setReviewed(true);
      }
    },

    _computeDiffURL: function(changeNum, patchRange, path) {
      var patchStr = patchRange.patchNum;
      if (patchRange.basePatchNum != null &&
          patchRange.basePatchNum != 'PARENT') {
        patchStr = patchRange.basePatchNum + '..' + patchRange.patchNum;
      }
      return '/c/' + changeNum + '/' + patchStr + '/' + path;
    },

    _computeAvailablePatches: function(revisions) {
      var patchNums = [];
      for (var rev in revisions) {
        patchNums.push(revisions[rev]._number);
      }
      return patchNums.sort(function(a, b) { return a - b; });
    },

    _computeChangePath: function(changeNum, patchNum, revisions) {
      var base = '/c/' + changeNum + '/';

      // The change may not have loaded yet, making revisions unavailable.
      if (!revisions) {
        return base + patchNum;
      }

      var latestPatchNum = -1;
      for (var rev in revisions) {
        latestPatchNum = Math.max(latestPatchNum, revisions[rev]._number);
      }
      if (parseInt(patchNum, 10) != latestPatchNum) {
        return base + patchNum;
      }

      return base;
    },

    _computeFileDisplayName: function(path) {
      return path == COMMIT_MESSAGE_PATH ? 'Commit message' : path;
    },

    _computeChangeDetailPath: function(changeNum) {
      return '/changes/' + changeNum + '/detail';
    },

    _computeChangeDetailQueryParams: function() {
      return {O: this.listChangesOptionsToHex(
          this.ListChangesOption.ALL_REVISIONS
      )};
    },

    _computeFilesPath: function(changeNum, patchNum) {
      return this.changeBaseURL(changeNum, patchNum) + '/files';
    },

    _computeProjectConfigPath: function(project) {
      return '/projects/' + encodeURIComponent(project) + '/config';
    },

    _computeFileSelected: function(path, currentPath) {
      return path == currentPath;
    },

    _computeKeyNav: function(path, selectedPath, fileList) {
      var selectedIndex = fileList.indexOf(selectedPath);
      if (fileList.indexOf(path) == selectedIndex - 1) {
        return '[';
      }
      if (fileList.indexOf(path) == selectedIndex + 1) {
        return ']';
      }
      return '';
    },

    _handleFileTap: function(e) {
      this.$.dropdown.close();
    },

    _handleMobileSelectChange: function(e) {
      var path = Polymer.dom(e).rootTarget.value;
      page.show(
          this._computeDiffURL(this._changeNum, this._patchRange, path));
    },

    _handleFilesResponse: function(e, req) {
      this._fileList = Object.keys(e.detail.response).sort();
    },

    _showDropdownTapHandler: function(e) {
      this.$.dropdown.open();
    },

    _send: function(method, url) {
      var xhr = document.createElement('gr-request');
      this._xhrPromise = xhr.send({
        method: method,
        url: url,
      });
      return this._xhrPromise;
    },
  });
})();
<|endoftext|>


<commit_before>/* eslint-disable flowtype/require-valid-file-annotation, no-console, import/extensions */
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import json from 'rollup-plugin-json';
import flow from 'rollup-plugin-flow';
import { terser } from 'rollup-plugin-terser';
import sourceMaps from 'rollup-plugin-sourcemaps';
import pkg from './package.json';

const cjs = {
  exports: 'named',
  format: 'cjs',
  sourcemap: true,
};

const esm = {
  format: 'esm',
  sourcemap: true,
};

const getCJS = override => ({ ...cjs, ...override });
const getESM = override => ({ ...esm, ...override });

const commonPlugins = [
  flow({
    // needed for sourcemaps to be properly generated
    pretty: true,
  }),
  sourceMaps(),
  json(),
  nodeResolve(),
  babel({
    configFile: require.resolve('../../babel.config.js'),
    exclude: ['node_modules/**', '../../node_modules/**'],
  }),
  commonjs({
    ignoreGlobal: true,
    namedExports: {
      'react-is': ['isElement', 'isValidElementType', 'ForwardRef', 'typeof'],
    },
  }),
  replace({
    __VERSION__: JSON.stringify(pkg.version),
  }),
];

const prodPlugins = [
  replace({
    'process.env.NODE_ENV': JSON.stringify('production'),
  }),
  terser({
    sourcemap: true,
  }),
];

const configBase = {
  input: './src/index.js',

  // \0 is rollup convention for generated in memory modules
  external: id => !id.startsWith('\0') && !id.startsWith('.') && !id.startsWith('/'),
  plugins: commonPlugins,
};

const globals = { react: 'React', 'react-dom': 'ReactDOM', 'react-is': 'ReactIs' };

const standaloneBaseConfig = {
  ...configBase,
  input: './src/index-standalone.js',
  output: {
    file: 'dist/styled-components.js',
    format: 'umd',
    globals,
    name: 'styled',
    sourcemap: true,
  },
  external: Object.keys(globals),
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(false),
    })
  ),
};

const standaloneConfig = {
  ...standaloneBaseConfig,
  plugins: standaloneBaseConfig.plugins.concat(
    replace({
      'process.env.NODE_ENV': JSON.stringify('development'),
    })
  ),
};

const standaloneProdConfig = {
  ...standaloneBaseConfig,
  output: {
    ...standaloneBaseConfig.output,
    file: 'dist/styled-components.min.js',
  },
  plugins: standaloneBaseConfig.plugins.concat(prodPlugins),
};

const serverConfig = {
  ...configBase,
  output: [
    getESM({ file: 'dist/styled-components.esm.js' }),
    getCJS({ file: 'dist/styled-components.cjs.js' }),
  ],
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(true),
    })
  ),
};

const browserConfig = {
  ...configBase,
  output: [
    getESM({ file: 'dist/styled-components.browser.esm.js' }),
    getCJS({ file: 'dist/styled-components.browser.cjs.js' }),
  ],
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(false),
    })
  ),
};

const nativeConfig = {
  ...configBase,
  input: './src/native/index.js',
  output: [
    getCJS({
      file: 'native/dist/styled-components.native.cjs.js',
    }),
    getESM({
      file: 'native/dist/styled-components.native.esm.js',
    }),
  ],
};

const primitivesConfig = {
  ...configBase,
  input: './src/primitives/index.js',
  output: [
    getESM({ file: 'primitives/dist/styled-components-primitives.esm.js' }),
    getCJS({
      file: 'primitives/dist/styled-components-primitives.cjs.js',
    }),
  ],
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(true),
    })
  ),
};

const macroConfig = Object.assign({}, configBase, {
  input: './src/macro/index.js',
  output: [
    getESM({ file: 'dist/styled-components-macro.esm.js' }),
    getCJS({ file: 'dist/styled-components-macro.cjs.js' }),
  ],
});

export default [
  standaloneConfig,
  standaloneProdConfig,
  serverConfig,
  browserConfig,
  nativeConfig,
  primitivesConfig,
  macroConfig,
];
<commit_msg>pre-minify things a bit<commit_after>/* eslint-disable flowtype/require-valid-file-annotation, no-console, import/extensions */
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import json from 'rollup-plugin-json';
import flow from 'rollup-plugin-flow';
import { terser } from 'rollup-plugin-terser';
import sourceMaps from 'rollup-plugin-sourcemaps';
import pkg from './package.json';

/**
 * NODE_ENV explicit replacement is only needed for standalone packages, as webpack
 * automatically will replace it otherwise in the downstream build.
 */

const cjs = {
  exports: 'named',
  format: 'cjs',
  sourcemap: true,
};

const esm = {
  format: 'esm',
  sourcemap: true,
};

const getCJS = override => ({ ...cjs, ...override });
const getESM = override => ({ ...esm, ...override });

const commonPlugins = [
  flow({
    // needed for sourcemaps to be properly generated
    pretty: true,
  }),
  sourceMaps(),
  json(),
  nodeResolve(),
  babel({
    configFile: require.resolve('../../babel.config.js'),
    exclude: ['node_modules/**', '../../node_modules/**'],
  }),
  commonjs({
    ignoreGlobal: true,
    namedExports: {
      'react-is': ['isElement', 'isValidElementType', 'ForwardRef', 'typeof'],
    },
  }),
  replace({
    __VERSION__: JSON.stringify(pkg.version),
  }),
];

// this should always be last
const minifierPlugin = terser({
  sourcemap: true,
});

const configBase = {
  input: './src/index.js',

  // \0 is rollup convention for generated in memory modules
  external: id => !id.startsWith('\0') && !id.startsWith('.') && !id.startsWith('/'),
  plugins: commonPlugins,
};

const globals = { react: 'React', 'react-dom': 'ReactDOM', 'react-is': 'ReactIs' };

const standaloneBaseConfig = {
  ...configBase,
  input: './src/index-standalone.js',
  output: {
    file: 'dist/styled-components.js',
    format: 'umd',
    globals,
    name: 'styled',
    sourcemap: true,
  },
  external: Object.keys(globals),
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(false),
    })
  ),
};

const standaloneConfig = {
  ...standaloneBaseConfig,
  plugins: standaloneBaseConfig.plugins.concat(
    replace({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
    minifierPlugin
  ),
};

const standaloneProdConfig = {
  ...standaloneBaseConfig,
  output: {
    ...standaloneBaseConfig.output,
    file: 'dist/styled-components.min.js',
  },
  plugins: standaloneBaseConfig.plugins.concat(
    replace({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    minifierPlugin
  ),
};

const serverConfig = {
  ...configBase,
  output: [
    getESM({ file: 'dist/styled-components.esm.js' }),
    getCJS({ file: 'dist/styled-components.cjs.js' }),
  ],
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(true),
    }),
    minifierPlugin
  ),
};

const browserConfig = {
  ...configBase,
  output: [
    getESM({ file: 'dist/styled-components.browser.esm.js' }),
    getCJS({ file: 'dist/styled-components.browser.cjs.js' }),
  ],
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(false),
    }),
    minifierPlugin
  ),
};

const nativeConfig = {
  ...configBase,
  input: './src/native/index.js',
  output: [
    getCJS({
      file: 'native/dist/styled-components.native.cjs.js',
    }),
    getESM({
      file: 'native/dist/styled-components.native.esm.js',
    }),
  ],
};

const primitivesConfig = {
  ...configBase,
  input: './src/primitives/index.js',
  output: [
    getESM({ file: 'primitives/dist/styled-components-primitives.esm.js' }),
    getCJS({
      file: 'primitives/dist/styled-components-primitives.cjs.js',
    }),
  ],
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(true),
    })
  ),
};

const macroConfig = Object.assign({}, configBase, {
  input: './src/macro/index.js',
  output: [
    getESM({ file: 'dist/styled-components-macro.esm.js' }),
    getCJS({ file: 'dist/styled-components-macro.cjs.js' }),
  ],
  plugins: configBase.plugins.concat(
    replace({
      __SERVER__: JSON.stringify(false),
    }),
    minifierPlugin
  ),
});

export default [
  standaloneConfig,
  standaloneProdConfig,
  serverConfig,
  browserConfig,
  nativeConfig,
  primitivesConfig,
  macroConfig,
];
<|endoftext|>


<commit_before>import React from 'react'
import {Field} from 'redux-form'
import _get from 'lodash/get'
import _pick from 'lodash/pick'
import {Layout, Panel, Typography} from 'tocco-ui'

import consoleLogger from '../consoleLogger'
import ReduxFormFieldAdapter from './ReduxFormFieldAdapter'
import {getFieldId} from './formDefinition'
import {transformFieldName} from './reduxForm'
import actions from '../actions'
import componentTypes from './enums/componentTypes'
import layoutTypes from './enums/layoutTypes'
import {isAction} from '../actions/actions'

export default (
  entity,
  model,
  formName,
  formDefinition,
  formValues,
  formFieldUtils,
  formFieldMapping,
  readOnlyFormFieldMapping,
  beforeRenderField,
  mode,
  componentMapping
) => {
  const isReadOnlyForm = formDefinition.readonly

  const formTraverser = children => {
    const result = []
    for (let i = 0; i < children.length; i++) {
      const child = children[i]
      if (child.componentType === componentTypes.LAYOUT) {
        const travers = () => formTraverser(child.children)
        result.push(createLayoutComponent(child, child.layoutType, i, travers))
      } else if (isAction(child.componentType)) {
        result.push(createAction(child, i))
      } else if (child.componentType === componentTypes.FIELD_SET) {
        result.push(createFieldSet(child, i))
      } else if (componentMapping && componentMapping[child.componentType]) {
        const component = componentMapping[child.componentType]
        const fieldName = child.id
        const modelField = model[fieldName]
        return component(child, modelField, i)
      }
    }

    return result
  }

  const createAction = (child, key) => {
    return <actions.Action
      definition={child}
      entity={entity.model}
      ids={[...(entity.key ? [entity.key] : [])]}
      mode={mode}
      key={'detailAction' + key}
    />
  }

  const createFieldSet = (fieldSet, key) => {
    const fieldDefinition = fieldSet.children.find(child => !isAction(child.componentType))

    if (!fieldDefinition) {
      return null
    }

    const formDefinitionField = {
      ...fieldDefinition,
      ..._pick(fieldSet, ['label', 'hidden', 'readonly', 'scopes'])

    }

    const fieldName = formDefinitionField.id
    const entityField = entity ? entity.paths[fieldName] : null
    const modelSelector = formDefinitionField.path
      ? formDefinitionField.path.split('.')[0]
      : formDefinitionField.id
    const modelField = model[modelSelector]

    const shouldRenderField = (formDefinitionField, entityField) => {
      if (mode && formDefinitionField.scopes && formDefinitionField.scopes.length > 0
        && !formDefinitionField.scopes.includes(mode)) {
        return false
      }

      if (formDefinitionField.hidden) {
        return false
      }

      if (beforeRenderField && beforeRenderField(formDefinitionField.id) === false) {
        return false
      }

      const hasEmptyValue = (fieldName, formValues) => {
        if (!formValues.hasOwnProperty(fieldName)) {
          return false
        } else {
          const value = formValues[fieldName]
          return (value == null || value === '' || (Array.isArray(value) && value.length === 0))
        }
      }

      if (entityField) {
        const isReadable = _get(entityField, 'value.readable', true)
        if (!isReadable) {
          return false
        }
      }

      return !(isReadOnlyForm && hasEmptyValue(transformFieldName(formDefinitionField.id), formValues))
    }

    if (shouldRenderField(formDefinitionField, entityField, formValues, isReadOnlyForm)) {
      return (
        <Field
          key={key}
          readOnlyForm={isReadOnlyForm}
          name={transformFieldName(fieldName)}
          id={getFieldId(formName, fieldName)}
          component={ReduxFormFieldAdapter}
          formDefinitionField={formDefinitionField}
          entityField={entityField}
          modelField={modelField}
          formFieldUtils={formFieldUtils}
          formFieldMapping={formFieldMapping}
          readOnlyFormFieldMapping={readOnlyFormFieldMapping}
          format={null}
        />
      )
    }

    return null
  }

  const createLayoutComponent = (field, type, key, traverser) => {
    let elements = traverser()

    if (Array.isArray(elements)) {
      elements = elements.filter(el => el)
    }

    if (!elements || (Array.isArray(elements) && elements.every(e => e == null))) {
      return null
    }

    const content = field.label
      ? <Panel.Wrapper isFramed={true} isOpen={true}>
        <Panel.Header><Typography.H4>{field.label}</Typography.H4></Panel.Header>
        <Panel.Body>{elements}</Panel.Body>
      </Panel.Wrapper>
      : elements

    if (type === layoutTypes.HORIZONTAL_BOX) {
      return <Layout.Container key={key}>{content}</Layout.Container>
    } else if (type === layoutTypes.VERTICAL_BOX) {
      return <Layout.Box key={key}>{content}</Layout.Box>
    } else {
      consoleLogger.logWarning(`Layout type "${type}" for box "${field.id}" is unknown.`)
      return
{content}

    }
  }

  return () => {
    return formTraverser(formDefinition.children)
  }
}
<commit_msg>refactor(tocco-ui): improve readability of createLayoutComponent<commit_after>
import React from 'react'
import {Field} from 'redux-form'
import _get from 'lodash/get'
import _pick from 'lodash/pick'
import {Layout, Panel, Typography} from 'tocco-ui'

import consoleLogger from '../consoleLogger'
import ReduxFormFieldAdapter from './ReduxFormFieldAdapter'
import {getFieldId} from './formDefinition'
import {transformFieldName} from './reduxForm'
import actions from '../actions'
import componentTypes from './enums/componentTypes'
import layoutTypes from './enums/layoutTypes'
import {isAction} from '../actions/actions'

export default (
  entity,
  model,
  formName,
  formDefinition,
  formValues,
  formFieldUtils,
  formFieldMapping,
  readOnlyFormFieldMapping,
  beforeRenderField,
  mode,
  componentMapping
) => {
  const isReadOnlyForm = formDefinition.readonly

  const formTraverser = children => {
    const result = []
    for (let i = 0; i < children.length; i++) {
      const child = children[i]
      if (child.componentType === componentTypes.LAYOUT) {
        const travers = () => formTraverser(child.children)
        result.push(createLayoutComponent(child, child.layoutType, i, travers))
      } else if (isAction(child.componentType)) {
        result.push(createAction(child, i))
      } else if (child.componentType === componentTypes.FIELD_SET) {
        result.push(createFieldSet(child, i))
      } else if (componentMapping && componentMapping[child.componentType]) {
        const component = componentMapping[child.componentType]
        const fieldName = child.id
        const modelField = model[fieldName]
        return component(child, modelField, i)
      }
    }

    return result
  }

  const createAction = (child, key) => {
    return <actions.Action
      definition={child}
      entity={entity.model}
      ids={[...(entity.key ? [entity.key] : [])]}
      mode={mode}
      key={'detailAction' + key}
    />
  }

  const createFieldSet = (fieldSet, key) => {
    const fieldDefinition = fieldSet.children.find(child => !isAction(child.componentType))

    if (!fieldDefinition) {
      return null
    }

    const formDefinitionField = {
      ...fieldDefinition,
      ..._pick(fieldSet, ['label', 'hidden', 'readonly', 'scopes'])

    }

    const fieldName = formDefinitionField.id
    const entityField = entity ? entity.paths[fieldName] : null
    const modelSelector = formDefinitionField.path
      ? formDefinitionField.path.split('.')[0]
      : formDefinitionField.id
    const modelField = model[modelSelector]

    const shouldRenderField = (formDefinitionField, entityField) => {
      if (mode && formDefinitionField.scopes && formDefinitionField.scopes.length > 0
        && !formDefinitionField.scopes.includes(mode)) {
        return false
      }

      if (formDefinitionField.hidden) {
        return false
      }

      if (beforeRenderField && beforeRenderField(formDefinitionField.id) === false) {
        return false
      }

      const hasEmptyValue = (fieldName, formValues) => {
        if (!formValues.hasOwnProperty(fieldName)) {
          return false
        } else {
          const value = formValues[fieldName]
          return (value == null || value === '' || (Array.isArray(value) && value.length === 0))
        }
      }

      if (entityField) {
        const isReadable = _get(entityField, 'value.readable', true)
        if (!isReadable) {
          return false
        }
      }

      return !(isReadOnlyForm && hasEmptyValue(transformFieldName(formDefinitionField.id), formValues))
    }

    if (shouldRenderField(formDefinitionField, entityField, formValues, isReadOnlyForm)) {
      return (
        <Field
          key={key}
          readOnlyForm={isReadOnlyForm}
          name={transformFieldName(fieldName)}
          id={getFieldId(formName, fieldName)}
          component={ReduxFormFieldAdapter}
          formDefinitionField={formDefinitionField}
          entityField={entityField}
          modelField={modelField}
          formFieldUtils={formFieldUtils}
          formFieldMapping={formFieldMapping}
          readOnlyFormFieldMapping={readOnlyFormFieldMapping}
          format={null}
        />
      )
    }

    return null
  }

  const createLayoutComponent = (field, type, key, traverser) => {
    let elements = traverser()

    if (Array.isArray(elements)) {
      elements = elements.filter(el => el)
    }

    if (!elements || (Array.isArray(elements) && elements.length === 0)) {
      return null
    }

    const content = field.label
      ? <Panel.Wrapper isFramed={true} isOpen={true}>
        <Panel.Header><Typography.H4>{field.label}</Typography.H4></Panel.Header>
        <Panel.Body>{elements}</Panel.Body>
      </Panel.Wrapper>
      : elements

    const layoutMap = {
      [layoutTypes.HORIZONTAL_BOX]: Layout.Container,
      [layoutTypes.VERTICAL_BOX]: Layout.Box
    }

    const LayoutComponent = layoutMap[type]

    if (LayoutComponent) {
      return <LayoutComponent key={key}>{content}</LayoutComponent>
    } else {
      consoleLogger.logWarning(`Layout type "${type}" for box "${field.id}" is unknown.`)
      return
{content}

    }
  }

  return () => {
    return formTraverser(formDefinition.children)
  }
}
<|endoftext|>


<commit_before>import React from 'react';

import Callout from '../../components/Callout';
import LinkedHeading from '../../components/LinkedHeading';
import ReactPlayground from '../../components/ReactPlayground';
import Prefixes from '../../examples/Theming/Prefixes';
import Variants from '../../examples/Theming/Variants';
import withLayout from '../../withLayout';

export default withLayout(function ThemingSection() {
  return (
    <>
      <LinkedHeading h="1" id="custom-styles">
        Theming and Customizing styles.
      </LinkedHeading>

        Generally, if you stick to the bootstrap defined classes and variants,
        there isn't anything you need to do to use a custom theme with
        ReactBootstrap, it just works. There are plently of cases tho where you
        want to color outside the lines and we try to make that easy to do.

      <LinkedHeading h="2" id="custom-styles-variants">
        New variants and sizes
      </LinkedHeading>

        Custom variants and sizes should follow the pattern of the default
        bootstrap variants, and define css classes matching:{' '}
        component-*. React bootstrap builds the component
        classNames in a consistent way that you can rely on. For
        instance this custom Button.

      <ReactPlayground codeText={Variants} />

      <LinkedHeading h="2" id="custom-styles-prefix">
        Prefixing components
      </LinkedHeading>

        In some cases you may need to change the base class "prefix" of one or
        more Components. You can control how a Component prefixes it's classes
        locally by changing the bsPrefix prop. Or globally via the{' '}
        ThemeProvider Component.

      <Callout theme="warning">
        Changing prefixes is an escape hatch and generally shouldn't be used
      </Callout>
      <ReactPlayground codeText={Prefixes} />
    </>
  );
});
<commit_msg>docs(getting-started): fixed typos (#3818)<commit_after>import React from 'react';

import Callout from '../../components/Callout';
import LinkedHeading from '../../components/LinkedHeading';
import ReactPlayground from '../../components/ReactPlayground';
import Prefixes from '../../examples/Theming/Prefixes';
import Variants from '../../examples/Theming/Variants';
import withLayout from '../../withLayout';

export default withLayout(function ThemingSection() {
  return (
    <>
      <LinkedHeading h="1" id="custom-styles">
        Theming and Customizing styles.
      </LinkedHeading>

        Generally, if you stick to the Bootstrap defined classes and variants,
        there isn't anything you need to do to use a custom theme with
        React-Bootstrap. It just works. But we also make coloring outside the
        lines easy to do.

      <LinkedHeading h="2" id="custom-styles-variants">
        New variants and sizes
      </LinkedHeading>

        Custom variants and sizes should follow the pattern of the default
        bootstrap variants, and define css classes matching:{' '}
        component-*. React bootstrap builds the component
        classNames in a consistent way that you can rely on. For
        instance this custom Button.

      <ReactPlayground codeText={Variants} />

      <LinkedHeading h="2" id="custom-styles-prefix">
        Prefixing components
      </LinkedHeading>

        In some cases you may need to change the base class "prefix" of one or
        more Components. You can control how a Component prefixes it's classes
        locally by changing the bsPrefix prop. Or globally via the{' '}
        ThemeProvider Component.

      <Callout theme="warning">
        Changing prefixes is an escape hatch and generally shouldn't be used.
      </Callout>
      <ReactPlayground codeText={Prefixes} />
    </>
  );
});
<|endoftext|>