<commit_before>// @flow

import Command, {flags} from 'cli-engine-command'
import {Updater} from '../updater'
import PluginsUpdate from './plugins/update'
import Plugins from '../plugins'
import {Hooks} from '../hooks'

const debug = require('debug')('cli-engine:update')

function brew (...args) {
  const cp = require('child_process')
  debug('brew %o', args)
  return cp.spawnSync('brew', args, {stdio: 'inherit'})
}

export default class Update extends Command<*> {
  static topic = 'update'
  static description = 'update the Heroku CLI'
  static args = [
    {name: 'channel', optional: true}
  ]
  static flags = {
    autoupdate: flags.boolean({hidden: true})
  }
  updater: Updater

  async run () {
    // on manual run, also log to file
    if (!this.flags.autoupdate) {
      this.out.stdout.logfile = this.out.autoupdatelog
      this.out.stderr.logfile = this.out.autoupdatelog
    }
    this.updater = new Updater(this.out)
    if (this.config.updateDisabled === 'Update CLI with `brew upgrade heroku`') {
      this.migrateBrew()
    } else if (this.config.updateDisabled) {
      this.out.warn(this.config.updateDisabled)
    } else {
      this.out.action.start(`${this.config.name}: Updating CLI`)
      let channel = this.argv[0] || this.config.channel
      let manifest = await this.updater.fetchManifest(channel)
      if (this.config.version === manifest.version && channel === this.config.channel) {
        this.out.action.stop(`already on latest version: ${this.config.version}`)
      } else {
        let {yellow, green} = this.out.color
        this.out.action.start(`${this.config.name}: Updating CLI from ${green(this.config.version)} to ${green(manifest.version)}${channel === 'stable' ? '' : ' (' + yellow(channel) + ')'}`)
        await this.updater.update(manifest)
        this.out.action.stop()
        try {
          await this.updater.autoupdate(true)
          this.out.exit(0)
        } catch (err) {
          this.out.warn(err, 'post-install autoupdate failed')
        }
      }
    }
    debug('fetch version')
    await this.updater.fetchVersion(true)
    debug('plugins update')
    await PluginsUpdate.run(this.config)
    debug('log chop')
    await this.logChop()
    debug('autocomplete')
    const hooks = new Hooks({config: this.config})
    await hooks.run('update')
    if (this.config.windows) {
      debug('skipping autocomplete on windows')
    } else {
      const plugins = await new Plugins(this.out).list()
      const acPlugin = plugins.find(p => p.name === 'heroku-cli-autocomplete')
      if (acPlugin) {
        let ac = await acPlugin.findCommand('autocomplete:init')
        if (ac) await ac.run(this.config)
      } else {
        debug('skipping autocomplete, not installed')
      }
    }
    debug('done')
  }

  async logChop () {
    try {
      const logChopper = require('log-chopper').default
      await logChopper.chop(this.out.errlog)
    } catch (e) { this.out.debug(e.message) }
  }

  migrateBrew () {
    try {
      debug('migrating from brew')
      const fs = require('fs-extra')
      let p = fs.realpathSync('/usr/local/bin/heroku')
      if (p.match(/\/usr\/local\/Cellar\/heroku\/\d+\.\d+\.\d+\//)) {
        // not on private tap, move to it
        this.out.action.start('Upgrading homebrew formula')
        brew('tap', 'heroku/brew')
        brew('upgrade', 'heroku/brew/heroku')
        this.out.action.stop()
      }
    } catch (err) {
      debug(err)
    }
  }
}
<commit_msg>fix plugins:update when run through update<commit_after>// @flow

import Command, {flags} from 'cli-engine-command'
import {Updater} from '../updater'
import PluginsUpdate from './plugins/update'
import Plugins from '../plugins'
import {Hooks} from '../hooks'
import {buildConfig} from 'cli-engine-config'

const debug = require('debug')('cli-engine:update')

function brew (...args) {
  const cp = require('child_process')
  debug('brew %o', args)
  return cp.spawnSync('brew', args, {stdio: 'inherit'})
}

export default class Update extends Command<*> {
  static topic = 'update'
  static description = 'update the Heroku CLI'
  static args = [
    {name: 'channel', optional: true}
  ]
  static flags = {
    autoupdate: flags.boolean({hidden: true})
  }
  updater: Updater

  async run () {
    // on manual run, also log to file
    if (!this.flags.autoupdate) {
      this.out.stdout.logfile = this.out.autoupdatelog
      this.out.stderr.logfile = this.out.autoupdatelog
    }
    this.updater = new Updater(this.out)
    if (this.config.updateDisabled === 'Update CLI with `brew upgrade heroku`') {
      this.migrateBrew()
    } else if (this.config.updateDisabled) {
      this.out.warn(this.config.updateDisabled)
    } else {
      this.out.action.start(`${this.config.name}: Updating CLI`)
      let channel = this.argv[0] || this.config.channel
      let manifest = await this.updater.fetchManifest(channel)
      if (this.config.version === manifest.version && channel === this.config.channel) {
        this.out.action.stop(`already on latest version: ${this.config.version}`)
      } else {
        let {yellow, green} = this.out.color
        this.out.action.start(`${this.config.name}: Updating CLI from ${green(this.config.version)} to ${green(manifest.version)}${channel === 'stable' ? '' : ' (' + yellow(channel) + ')'}`)
        await this.updater.update(manifest)
        this.out.action.stop()
        try {
          await this.updater.autoupdate(true)
          this.out.exit(0)
        } catch (err) {
          this.out.warn(err, 'post-install autoupdate failed')
        }
      }
    }
    debug('fetch version')
    await this.updater.fetchVersion(true)
    debug('plugins update')
    await PluginsUpdate.run({...this.config, argv: []})
    debug('log chop')
    await this.logChop()
    debug('autocomplete')
    const hooks = new Hooks({config: this.config})
    await hooks.run('update')
    if (this.config.windows) {
      debug('skipping autocomplete on windows')
    } else {
      const plugins = await new Plugins(this.out).list()
      const acPlugin = plugins.find(p => p.name === 'heroku-cli-autocomplete')
      if (acPlugin) {
        let ac = await acPlugin.findCommand('autocomplete:init')
        if (ac) await ac.run(this.config)
      } else {
        debug('skipping autocomplete, not installed')
      }
    }
    debug('done')
  }

  async logChop () {
    try {
      const logChopper = require('log-chopper').default
      await logChopper.chop(this.out.errlog)
    } catch (e) { this.out.debug(e.message) }
  }

  migrateBrew () {
    try {
      debug('migrating from brew')
      const fs = require('fs-extra')
      let p = fs.realpathSync('/usr/local/bin/heroku')
      if (p.match(/\/usr\/local\/Cellar\/heroku\/\d+\.\d+\.\d+\//)) {
        // not on private tap, move to it
        this.out.action.start('Upgrading homebrew formula')
        brew('tap', 'heroku/brew')
        brew('upgrade', 'heroku/brew/heroku')
        this.out.action.stop()
      }
    } catch (err) {
      debug(err)
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @param  {Object}  gulp    The gulp object
 * @param  {Object}  config  The configuration for gulp tasks. To get a property using `config.a.b.c` or `config.get('a.b.c')`
 * @param  {Object}  LL      Lazy required libraries and other data
 * @param  {Object}  args    The parsed arguments from comment line
 */
module.exports = function(gulp, config, LL, args) {  // eslint-disable-line no-unused-vars
    gulp.task('release:license', ['clean:release'], function() {
        var conf = config.get('tasks.release.license');
        var license = LL.license;
        var filter = LL.filter;

        var matches = conf.get('matches');
        var author = conf.get('author');
        var defaultLicense = conf.get('license');

        var stream = gulp.src(conf.get('src'), conf.get('srcOpts'));

        matches.forEach(function(matchObj) {
            var f = filter(matchObj.glob, {restore: true});
            stream = stream.pipe(f)
                .pipe(license(matchObj.license || defaultLicense, {
                    organization: matchObj.author || author,
                }))
                .pipe(f.restore);
        });

        return stream.pipe(gulp.dest(conf.get('dest')));
    });

    gulp.task('release:npm-pack', ['clean:npm-package'], function(done) {
        var conf = config.get('tasks.release.npm');
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.packageJSON;

        var src = Path.resolve(conf.get('src'));
        var dest = Path.resolve(conf.get('dest'));
        var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);
        var packageName = src.split('/').pop();

        var command = util.format('tar -czf %s -C %s %s', destFile, Path.resolve(src, '..'), packageName);

        CP.exec(command, done);
    });

    gulp.task('release:npm-publish', function(done) {
        var conf = config.get('tasks.release.npm');
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.packageJSON;

        var dest = Path.resolve(conf.get('dest'));
        var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);

        var command = util.format('npm publish --access public %s', destFile);

        CP.exec(command, done);
    });

    gulp.task('release:pre', function(done) {
        var CP = LL.CP;

        var command = '\
            git add . && \
            git stash save "stash for release" && \
            git fetch --prune && \
            git rebase origin/develop release \
        ';
        CP.exec(command, done);
    });

    gulp.task('release:changelog:touch', function(done) {
        var name = config.get('tasks.release.changelog.name');
        LL.CP.exec('touch ' + name, done);
    });

    gulp.task('release:changelog', ['release:changelog:touch'], function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var changelog = LL.changelog;
        var conf = config.get('tasks.release.changelog');
        var name = conf.get('name');

        gulp.src(name, {
            buffer: false,
        })
            .pipe(changelog({
                preset: 'angular',
            }))
            .pipe(gulp.dest('./'))
            .on('end', function() {
                var packageJSON = LL.reload('packageJSON');
                var tag = packageJSON.version;
                var command = util.format('\
                    git add %s && \
                    git commit -m "update version to %s" --no-edit \
                ', name, tag);
                CP.exec(command, done);
            })
            .on('error', done);
    });

    /**
     * gulp release:bump [options]
     *
     * options:
     *     -t --type [major, minor, patch]  Semver 2.0. default to patch
     *     -v --version VERSION  Bump to a specific version
     */
    gulp.task('release:bump', function(done) {
        var Path = LL.Path;
        var CP = LL.CP;

        var bumpOpts = {
            key: 'version',
            indent: 2,
        };

        var version = args.v || args.version;
        var type = args.t || args.type || 'patch';

        if (version) {
            bumpOpts.version = version;
        } else {
            bumpOpts.type = type;
        }

        gulp.src(Path.resolve('./package.json'))
            .pipe(LL.bump(bumpOpts))
            .pipe(gulp.dest('./'))
            .on('end', function() {
                CP.exec('git add package.json', done);
            })
            .on('error', done);
    });

    gulp.task('release:branch', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var command = util.format('\
            git fetch --prune && \
            git rebase origin/develop develop && \
            git merge --no-ff --no-edit release && \
            git rebase origin/master master && \
            git merge --no-ff --no-edit release \
        ');
        CP.exec(command, done);
    });

    gulp.task('release:tag', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.reload('packageJSON');
        var tag = packageJSON.version;
        var conf = config.get('tasks.release.git-tag');
        var commitHash = conf.get('dest');

        var command = util.format('git tag -a v%s %s -m "release version %s"', tag, commitHash, tag);
        CP.exec(command, done);
    });

    gulp.task('release:push', function(done) {
        var CP = LL.CP;
        var command = '\
            git push origin develop && \
            git push origin master && \
            git push --tags \
        ';
        CP.exec(command, done);
    });

    gulp.task('release:code', function(done) {
        LL.runSequence(
            'lint',
            'test',
            'release:pre',
            'release:bump',
            'release:changelog',
            'release:branch',
            'release:tag',
            'release:push',
            done
        );
    });

    gulp.task('release', function(done) {
        LL.runSequence(
            'release:code',
            'release:license',
            'release:npm-pack',
            'release:npm-publish',
            done
        );
    });
};
<commit_msg>gulp release push the release branch<commit_after>'use strict';

/**
 * @param  {Object}  gulp    The gulp object
 * @param  {Object}  config  The configuration for gulp tasks. To get a property using `config.a.b.c` or `config.get('a.b.c')`
 * @param  {Object}  LL      Lazy required libraries and other data
 * @param  {Object}  args    The parsed arguments from comment line
 */
module.exports = function(gulp, config, LL, args) {  // eslint-disable-line no-unused-vars
    gulp.task('release:license', ['clean:release'], function() {
        var conf = config.get('tasks.release.license');
        var license = LL.license;
        var filter = LL.filter;

        var matches = conf.get('matches');
        var author = conf.get('author');
        var defaultLicense = conf.get('license');

        var stream = gulp.src(conf.get('src'), conf.get('srcOpts'));

        matches.forEach(function(matchObj) {
            var f = filter(matchObj.glob, {restore: true});
            stream = stream.pipe(f)
                .pipe(license(matchObj.license || defaultLicense, {
                    organization: matchObj.author || author,
                }))
                .pipe(f.restore);
        });

        return stream.pipe(gulp.dest(conf.get('dest')));
    });

    gulp.task('release:npm-pack', ['clean:npm-package'], function(done) {
        var conf = config.get('tasks.release.npm');
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.packageJSON;

        var src = Path.resolve(conf.get('src'));
        var dest = Path.resolve(conf.get('dest'));
        var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);
        var packageName = src.split('/').pop();

        var command = util.format('tar -czf %s -C %s %s', destFile, Path.resolve(src, '..'), packageName);

        CP.exec(command, done);
    });

    gulp.task('release:npm-publish', function(done) {
        var conf = config.get('tasks.release.npm');
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.packageJSON;

        var dest = Path.resolve(conf.get('dest'));
        var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);

        var command = util.format('npm publish --access public %s', destFile);

        CP.exec(command, done);
    });

    gulp.task('release:pre', function(done) {
        var CP = LL.CP;

        var command = '\
            git add . && \
            git stash save "stash for release" && \
            git fetch --prune && \
            git rebase origin/develop release \
        ';
        CP.exec(command, done);
    });

    gulp.task('release:changelog:touch', function(done) {
        var name = config.get('tasks.release.changelog.name');
        LL.CP.exec('touch ' + name, done);
    });

    gulp.task('release:changelog', ['release:changelog:touch'], function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var changelog = LL.changelog;
        var conf = config.get('tasks.release.changelog');
        var name = conf.get('name');

        gulp.src(name, {
            buffer: false,
        })
            .pipe(changelog({
                preset: 'angular',
            }))
            .pipe(gulp.dest('./'))
            .on('end', function() {
                var packageJSON = LL.reload('packageJSON');
                var tag = packageJSON.version;
                var command = util.format('\
                    git add %s && \
                    git commit -m "update version to %s" --no-edit \
                ', name, tag);
                CP.exec(command, done);
            })
            .on('error', done);
    });

    /**
     * gulp release:bump [options]
     *
     * options:
     *     -t --type [major, minor, patch]  Semver 2.0. default to patch
     *     -v --version VERSION  Bump to a specific version
     */
    gulp.task('release:bump', function(done) {
        var Path = LL.Path;
        var CP = LL.CP;

        var bumpOpts = {
            key: 'version',
            indent: 2,
        };

        var version = args.v || args.version;
        var type = args.t || args.type || 'patch';

        if (version) {
            bumpOpts.version = version;
        } else {
            bumpOpts.type = type;
        }

        gulp.src(Path.resolve('./package.json'))
            .pipe(LL.bump(bumpOpts))
            .pipe(gulp.dest('./'))
            .on('end', function() {
                CP.exec('git add package.json', done);
            })
            .on('error', done);
    });

    gulp.task('release:branch', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var command = util.format('\
            git fetch --prune && \
            git rebase origin/develop develop && \
            git merge --no-ff --no-edit release && \
            git rebase origin/master master && \
            git merge --no-ff --no-edit release \
        ');
        CP.exec(command, done);
    });

    gulp.task('release:tag', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.reload('packageJSON');
        var tag = packageJSON.version;
        var conf = config.get('tasks.release.git-tag');
        var commitHash = conf.get('dest');

        var command = util.format('git tag -a v%s %s -m "release version %s"', tag, commitHash, tag);
        CP.exec(command, done);
    });

    gulp.task('release:push', function(done) {
        var CP = LL.CP;
        var command = '\
            git push origin develop && \
            git push origin master && \
            git push origin release && \
            git push --tags \
        ';
        CP.exec(command, done);
    });

    gulp.task('release:code', function(done) {
        LL.runSequence(
            'lint',
            'test',
            'release:pre',
            'release:bump',
            'release:changelog',
            'release:branch',
            'release:tag',
            'release:push',
            done
        );
    });

    gulp.task('release', function(done) {
        LL.runSequence(
            'release:code',
            'release:license',
            'release:npm-pack',
            'release:npm-publish',
            done
        );
    });
};
<|endoftext|>


<commit_before>(function () {
    var commons = angular.module('commons', []);

    commons.controller('BodyController', ["$scope", "$location", "$rootScope", "$state", BodyController]);

    function BodyController($scope, $location, $rootScope, $state) {
        if ($location.path() == '/' || $location.path() == '') {
            $location.path('accueil');
        }

        $rootScope.selectedCategory = null;
        $rootScope.search = '';

        $scope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
            console.log('Current route name: ' + $location.path());
            $rootScope.targetUrl = $location.path().split('/')[1];
            var _body = angular.element(document.getElementsByTagName("body"));
            $rootScope.previousState = from.name;
            $rootScope.currentState = to.name;
            //console.log('Previous state: ' + $rootScope.previousState);
            //console.log('Current state: ' + $rootScope.currentState);
            // Au changement de page, on scroll en haut de la page.
            if ($rootScope.previousState == 'actualites' && $rootScope.currentState == 'accueil') {
                $('html,body').stop().animate({scrollTop: $('#news_area').offset().top - 60}, 600);
            } else {
                $('html,body').stop().animate({scrollTop: 0}, 600);
            }
            _body.removeClass('page_cover');
            if ($rootScope.targetUrl === 'listeexposants' || ($rootScope.targetUrl.indexOf('exposants') !== -1)) {
                _body.addClass('exposants_page_cover');
            } else {
                _body.removeClass('exposants_page_cover');
                _body.removeClass('exposant_opened');
            }
        });

        $scope.targetPage = function (path) {
            $state.go(path, {target_area: ''}, {reload: true});
        };

        $scope.targetPageMobile = function (path) {
            $scope.targetPage(path);
            $scope.menuBtn();
        };

        /*  scrollToEffect : To animate the default scrolling to any of he main sections*/
        $scope.stickNavLinks = function (event) {
            event.preventDefault();
            var _this = $(event.currentTarget);
            var targetLinkOffset = $(_this.attr('data-href')).offset().top - 62;
            _this.addClass('active');

            /*$('html,body');*/
            $('html,body').stop().animate({scrollTop: targetLinkOffset}, 1200);
        };

        $scope.scroll_btm = function (event) {
            event.preventDefault();
            var _this = $(event.currentTarget);
            var targetLinkOffset = $(_this.attr('data-href')).offset().top - 62;
            _this.addClass('active');

            /*$('html,body');*/
            $('html,body').stop().animate({scrollTop: targetLinkOffset}, 1200);
        };
        /* End scrollToEffect */

        $scope.menuBtn = function () {
            //var _this = $(event.currentTarget);
            var menu_btn = angular.element(document.getElementsByClassName("menu_btn"));
            if (menu_btn.hasClass('is-active')) {
                menu_btn.removeClass('is-active');
            } else {
                menu_btn.addClass('is-active');
            }
        };

        $rootScope.hideArticle = function () {
            var cover = angular.element(document.getElementsByClassName("cover")).css('display', 'none');
            var newsItems = $('.news_list > li > a');
            if (newsItems.length) {
                var articleAsidePopin = angular.element(document.getElementsByClassName("article_body"));
                articleAsidePopin.removeClass('active');
                $rootScope.currentActualite = null;
            }
            $state.go('accueil', {}, {notify: false});
        };

        $rootScope.hideExposant = function () {
            var cover = angular.element(document.getElementsByClassName("cover")).css('display', 'none');
            var _body = $('body');
            var BodyScrollTop = _body.scrollTop();
            var exposantsItems = $('.exposants_liste li a');
            if (exposantsItems.length) {
                _body.removeClass('exposant_opened');
                $('html,body').stop().animate({scrollTop: BodyScrollTop}, 300);
            }
            //$state.go('listeexposants', {}, {reload: true});
            $location.path('exposants');
        };

        $rootScope.hideModals = function () {
            if ($rootScope.targetUrl == 'accueil' || $rootScope.targetUrl == 'actualites') {
                $rootScope.hideArticle();
            } else if ($rootScope.targetUrl == 'exposants' || $rootScope.targetUrl == 'listeexposants') {
                $rootScope.hideExposant();
            }
        };

        /* Load mapPlan */
        $rootScope.loadMapPlan = function () {
            var mapBlock = angular.element(document.querySelector('#map_plan'));
            if (mapBlock.length && typeof google === 'object' && typeof google.maps === 'object') {
                var myLatlng = new google.maps.LatLng(48.844559, 2.434568);
                var styleArray =
                    [
                        {
                            "featureType": "administrative.land_parcel",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "poi",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "poi.park",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "poi.sports_complex",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "road.highway",
                            "elementType": "geometry.fill",
                            "stylers": [
                                {
                                    "color": "#8e2862"
                                },
                                {
                                    "saturation": "76"
                                },
                                {
                                    "visibility": "on"
                                },
                                {
                                    "weight": "0.62"
                                }
                            ]
                        },
                        {
                            "featureType": "road.highway",
                            "elementType": "geometry.stroke",
                            "stylers": [
                                {
                                    "visibility": "off"
                                },
                                {
                                    "saturation": "0"
                                }
                            ]
                        },
                        {
                            "featureType": "road.arterial",
                            "elementType": "geometry.fill",
                            "stylers": [
                                {
                                    "color": "#f39200"
                                },
                                {
                                    "weight": "0.43"
                                }
                            ]
                        },
                        {
                            "featureType": "road.local",
                            "elementType": "geometry.fill",
                            "stylers": [
                                {
                                    "color": "#f5f5f5"
                                },
                                {
                                    "visibility": "on"
                                }
                            ]
                        },
                        {
                            "featureType": "water",
                            "elementType": "geometry.fill",
                            "stylers": [
                                {
                                    "color": "#d3d3d3"
                                }
                            ]
                        }
                    ]
                var mapOptions = {
                    zoom: 14,
                    center: myLatlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    disableDefaultUI: true,
                    styles: styleArray,
                    scrollwheel: false,
                    draggable: false
                };
                var map = new google.maps.Map(document.getElementById("map_plan"), mapOptions);

                //add a custom marker to the map
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(48.836291, 2.434390),
                    map: map,
                    visible: true,
                    icon: 'assets/img/default_marker.png',
                });
            }
        };
        /* End Load mapPlan */

    }
})
();
<commit_msg>- Remove cover when click header/footer.<commit_after>(function () {
    var commons = angular.module('commons', []);

    commons.controller('BodyController', ["$scope", "$location", "$rootScope", "$state", BodyController]);

    function BodyController($scope, $location, $rootScope, $state) {
        if ($location.path() == '/' || $location.path() == '') {
            $location.path('accueil');
        }

        $rootScope.selectedCategory = null;
        $rootScope.search = '';

        $scope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
            console.log('Current route name: ' + $location.path());
            $rootScope.targetUrl = $location.path().split('/')[1];
            var _body = angular.element(document.getElementsByTagName("body"));
            $rootScope.previousState = from.name;
            $rootScope.currentState = to.name;
            //console.log('Previous state: ' + $rootScope.previousState);
            //console.log('Current state: ' + $rootScope.currentState);
            // Au changement de page, on scroll en haut de la page.
            if ($rootScope.previousState == 'actualites' && $rootScope.currentState == 'accueil') {
                $('html,body').stop().animate({scrollTop: $('#news_area').offset().top - 60}, 600);
            } else {
                $('html,body').stop().animate({scrollTop: 0}, 600);
            }
            _body.removeClass('page_cover');
            if ($rootScope.targetUrl === 'listeexposants' || ($rootScope.targetUrl.indexOf('exposants') !== -1)) {
                _body.addClass('exposants_page_cover');
            } else {
                _body.removeClass('exposants_page_cover');
                _body.removeClass('exposant_opened');
            }
        });

        $scope.targetPage = function (path) {
            angular.element(document.getElementsByClassName("cover")).css('display', 'none');
            $state.go(path, {target_area: ''}, {reload: true});
        };

        $scope.targetPageMobile = function (path) {
            angular.element(document.getElementsByClassName("cover")).css('display', 'none');
            $scope.targetPage(path);
            $scope.menuBtn();
        };

        /*  scrollToEffect : To animate the default scrolling to any of he main sections*/
        $scope.stickNavLinks = function (event) {
            event.preventDefault();
            var _this = $(event.currentTarget);
            var targetLinkOffset = $(_this.attr('data-href')).offset().top - 62;
            _this.addClass('active');

            /*$('html,body');*/
            $('html,body').stop().animate({scrollTop: targetLinkOffset}, 1200);
        };

        $scope.scroll_btm = function (event) {
            event.preventDefault();
            var _this = $(event.currentTarget);
            var targetLinkOffset = $(_this.attr('data-href')).offset().top - 62;
            _this.addClass('active');

            /*$('html,body');*/
            $('html,body').stop().animate({scrollTop: targetLinkOffset}, 1200);
        };
        /* End scrollToEffect */

        $scope.menuBtn = function () {
            //var _this = $(event.currentTarget);
            var menu_btn = angular.element(document.getElementsByClassName("menu_btn"));
            if (menu_btn.hasClass('is-active')) {
                menu_btn.removeClass('is-active');
            } else {
                menu_btn.addClass('is-active');
            }
        };

        $rootScope.hideArticle = function () {
            var cover = angular.element(document.getElementsByClassName("cover")).css('display', 'none');
            var newsItems = $('.news_list > li > a');
            if (newsItems.length) {
                var articleAsidePopin = angular.element(document.getElementsByClassName("article_body"));
                articleAsidePopin.removeClass('active');
                $rootScope.currentActualite = null;
            }
            $state.go('accueil', {}, {notify: false});
        };

        $rootScope.hideExposant = function () {
            var cover = angular.element(document.getElementsByClassName("cover")).css('display', 'none');
            var _body = $('body');
            var BodyScrollTop = _body.scrollTop();
            var exposantsItems = $('.exposants_liste li a');
            if (exposantsItems.length) {
                _body.removeClass('exposant_opened');
                $('html,body').stop().animate({scrollTop: BodyScrollTop}, 300);
            }
            //$state.go('listeexposants', {}, {reload: true});
            $location.path('exposants');
        };

        $rootScope.hideModals = function () {
            if ($rootScope.targetUrl == 'accueil' || $rootScope.targetUrl == 'actualites') {
                $rootScope.hideArticle();
            } else if ($rootScope.targetUrl == 'exposants' || $rootScope.targetUrl == 'listeexposants') {
                $rootScope.hideExposant();
            }
        };

        /* Load mapPlan */
        $rootScope.loadMapPlan = function () {
            var mapBlock = angular.element(document.querySelector('#map_plan'));
            if (mapBlock.length && typeof google === 'object' && typeof google.maps === 'object') {
                var myLatlng = new google.maps.LatLng(48.844559, 2.434568);
                var styleArray =
                    [
                        {
                            "featureType": "administrative.land_parcel",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "poi",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "poi.park",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "poi.sports_complex",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "road.highway",
                            "elementType": "geometry.fill",
                            "stylers": [
                                {
                                    "color": "#8e2862"
                                },
                                {
                                    "saturation": "76"
                                },
                                {
                                    "visibility": "on"
                                },
                                {
                                    "weight": "0.62"
                                }
                            ]
                        },
                        {
                            "featureType": "road.highway",
                            "elementType": "geometry.stroke",
                            "stylers": [
                                {
                                    "visibility": "off"
                                },
                                {
                                    "saturation": "0"
                                }
                            ]
                        },
                        {
                            "featureType": "road.arterial",
                            "elementType": "geometry.fill",
                            "stylers": [
                                {
                                    "color": "#f39200"
                                },
                                {
                                    "weight": "0.43"
                                }
                            ]
                        },
                        {
                            "featureType": "road.local",
                            "elementType": "geometry.fill",
                            "stylers": [
                                {
                                    "color": "#f5f5f5"
                                },
                                {
                                    "visibility": "on"
                                }
                            ]
                        },
                        {
                            "featureType": "water",
                            "elementType": "geometry.fill",
                            "stylers": [
                                {
                                    "color": "#d3d3d3"
                                }
                            ]
                        }
                    ]
                var mapOptions = {
                    zoom: 14,
                    center: myLatlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    disableDefaultUI: true,
                    styles: styleArray,
                    scrollwheel: false,
                    draggable: false
                };
                var map = new google.maps.Map(document.getElementById("map_plan"), mapOptions);

                //add a custom marker to the map
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(48.836291, 2.434390),
                    map: map,
                    visible: true,
                    icon: 'assets/img/default_marker.png',
                });
            }
        };
        /* End Load mapPlan */

    }
})
();
<|endoftext|>


<commit_before>(() => {
  "use strict";

  var doc = document.currentScript.ownerDocument;

  class Modal extends HTMLElement {

    createdCallback() {
      var template = document.importNode(doc.getElementById("main").content, true);

      this._styles = [];

      this._modalBg = template.querySelector("#modal-bg");
      this.content = template.querySelector("#modal");

      var innerHTML = this.innerHTML;
      this.innerHTML = "";
      template.innerHTML = innerHTML;
      this.createShadowRoot().appendChild(template);

      this.attributeChangedCallback("width", null, this.getAttribute("width"));
      this.attributeChangedCallback("height", null, this.getAttribute("height"));
      this.attributeChangedCallback("visible", null, this.getAttribute("visible"));

      this._stopCb = e => e.stopPropagation();

      this._width = 400;
      this._height = 300;
      this._relative = false;
      this._top = 0;
      this._left = 0;
      this._right = 0;
      this._bottom = 0;

      this.refreshSize();
    }

    attributeChangedCallback(attrName, oldVal, newVal) {
      if (attrName === "visible") {
        if (newVal !== null) {
          this._modalBg.classList.remove("hidden");
          this.addEventListener("mousemove", this._stopCb, true);
        } else {
          this._modalBg.classList.add("hidden");
          this.removeEventListener("mousemove", this._stopCb, true);
        }
      }
    }

    appendStyle(style) {
      var s;
      if (typeof style === "string") {
        s = document.createElement("style");
        s.textContent = style;
      } else {
        s = style;
      }

      this._styles.push(s);
      this.shadowRoot.insertBefore(s, this._modalBg);
    }

    emptyStyle() {
      this._styles.forEach(s => {
        this.shadowRoot.removeChild(s);
      }, this);
      this._styles = [];
    }

    appendContent(content) {
      if (typeof content === "string")
        this.content.innerHTML += content;
      else
        this.content.appendChild(content);
    }

    emptyContent() {
      this.content.innerHTML = "";
    }

    use(name, content, listener1, listener2) {
      if (name === "main") return;
      var template = doc.querySelector("template#" + name);
      if (!template) return;
      var root = document.importNode(template.content, true);

      this.width = parseInt(template.dataset.width);
      this.height = parseInt(template.dataset.height);

      if (name !== "loading")
        root.querySelector(".modal-content").innerHTML = content;
      if (name === "yesno") {
        root.querySelector("#modal-btn-no").addEventListener(
          "click", listener1 || (() => this.hide()).bind(this));
        root.querySelector("#modal-btn-yes").addEventListener(
          "click", listener2 || (() => this.hide()).bind(this));
      } else if (name === "alert") {
        root.querySelector("#modal-btn-ok").addEventListener(
          "click", listener1 || (() => this.hide()).bind(this));
      }

      this.emptyStyle();
      this.emptyContent();
      this.appendContent(root);
      this.refreshSize();
    }

    show() {
      this.refreshSize();
      this.setAttribute("visible", "visible");
    }

    hide() {
      this.removeAttribute("visible");
    }

    get width() {
      return this._width;
    }

    set width(value) {
      this._width = Math.floor(value);
    }

    get height() {
      return this._height;
    }

    set height(value) {
      this._height = Math.floor(value);
    }

    get relative() {
      return this._relative;
    }

    set relative(value) {
      this._relative = !!value;
    }

    get top() {
      return this._top;
    }

    set top(value) {
      this._top = value;
    }

    get left() {
      return this._left;
    }

    set left(value) {
      this._left = value;
    }

    get right() {
      return this._right;
    }

    set right(value) {
      this._right = value;
    }

    get bottom() {
      return this._bottom;
    }

    set bottom(value) {
      this._bottom = value;
    }

    refreshSize() {
      function style(v) {
        return typeof v === "number" ? Math.floor(v) + "px" : v;
      }

      if (this._relative) {
        this.content.style.width = null;
        this.content.style.height = null;
        this.content.style.top = style(this._top);
        this.content.style.left = style(this._left);
        this.content.style.right = style(this._right);
        this.content.style.bottom = style(this._bottom);
        this.content.style.marginLeft = null;
        this.content.style.marginTop = null;
      } else {
        this.content.style.top = "50%";
        this.content.style.left = "50%";
        this.content.style.right = null;
        this.content.style.bottom = null;
        this.content.style.width = this._width + "px";
        this.content.style.height = this._height + "px";
        this.content.style.marginLeft = (-this._width / 2) + "px";
        this.content.style.marginTop = (-this._height / 2) + "px";
      }
    }

  }

  window.jikkyo.Modal = document.registerElement("jikkyo-modal", {
    prototype: Modal.prototype
  });

})();
<commit_msg>Fix modal layout bug<commit_after>(() => {
  "use strict";

  var doc = document.currentScript.ownerDocument;

  class Modal extends HTMLElement {

    createdCallback() {
      var template = document.importNode(doc.getElementById("main").content, true);

      this._styles = [];

      this._modalBg = template.querySelector("#modal-bg");
      this.content = template.querySelector("#modal");

      var innerHTML = this.innerHTML;
      this.innerHTML = "";
      template.innerHTML = innerHTML;
      this.createShadowRoot().appendChild(template);

      this.attributeChangedCallback("width", null, this.getAttribute("width"));
      this.attributeChangedCallback("height", null, this.getAttribute("height"));
      this.attributeChangedCallback("visible", null, this.getAttribute("visible"));

      this._stopCb = e => e.stopPropagation();

      this._width = 400;
      this._height = 300;
      this._relative = false;
      this._top = 0;
      this._left = 0;
      this._right = 0;
      this._bottom = 0;

      this.refreshSize();
    }

    attributeChangedCallback(attrName, oldVal, newVal) {
      if (attrName === "visible") {
        if (newVal !== null) {
          this._modalBg.classList.remove("hidden");
          this.addEventListener("mousemove", this._stopCb, true);
        } else {
          this._modalBg.classList.add("hidden");
          this.removeEventListener("mousemove", this._stopCb, true);
        }
      }
    }

    appendStyle(style) {
      var s;
      if (typeof style === "string") {
        s = document.createElement("style");
        s.textContent = style;
      } else {
        s = style;
      }

      this._styles.push(s);
      this.shadowRoot.insertBefore(s, this._modalBg);
    }

    emptyStyle() {
      this._styles.forEach(s => {
        this.shadowRoot.removeChild(s);
      }, this);
      this._styles = [];
    }

    appendContent(content) {
      if (typeof content === "string")
        this.content.innerHTML += content;
      else
        this.content.appendChild(content);
    }

    emptyContent() {
      this.content.innerHTML = "";
    }

    use(name, content, listener1, listener2) {
      if (name === "main") return;
      var template = doc.querySelector("template#" + name);
      if (!template) return;
      var root = document.importNode(template.content, true);

      this.relative = false;
      this.width = parseInt(template.dataset.width);
      this.height = parseInt(template.dataset.height);

      if (name !== "loading")
        root.querySelector(".modal-content").innerHTML = content;
      if (name === "yesno") {
        root.querySelector("#modal-btn-no").addEventListener(
          "click", listener1 || (() => this.hide()).bind(this));
        root.querySelector("#modal-btn-yes").addEventListener(
          "click", listener2 || (() => this.hide()).bind(this));
      } else if (name === "alert") {
        root.querySelector("#modal-btn-ok").addEventListener(
          "click", listener1 || (() => this.hide()).bind(this));
      }

      this.emptyStyle();
      this.emptyContent();
      this.appendContent(root);
      this.refreshSize();
    }

    show() {
      this.refreshSize();
      this.setAttribute("visible", "visible");
    }

    hide() {
      this.removeAttribute("visible");
    }

    get width() {
      return this._width;
    }

    set width(value) {
      this._width = Math.floor(value);
    }

    get height() {
      return this._height;
    }

    set height(value) {
      this._height = Math.floor(value);
    }

    get relative() {
      return this._relative;
    }

    set relative(value) {
      this._relative = !!value;
    }

    get top() {
      return this._top;
    }

    set top(value) {
      this._top = value;
    }

    get left() {
      return this._left;
    }

    set left(value) {
      this._left = value;
    }

    get right() {
      return this._right;
    }

    set right(value) {
      this._right = value;
    }

    get bottom() {
      return this._bottom;
    }

    set bottom(value) {
      this._bottom = value;
    }

    refreshSize() {
      function style(v) {
        return typeof v === "number" ? Math.floor(v) + "px" : v;
      }

      if (this._relative) {
        this.content.style.width = null;
        this.content.style.height = null;
        this.content.style.top = style(this._top);
        this.content.style.left = style(this._left);
        this.content.style.right = style(this._right);
        this.content.style.bottom = style(this._bottom);
        this.content.style.marginLeft = null;
        this.content.style.marginTop = null;
      } else {
        this.content.style.top = "50%";
        this.content.style.left = "50%";
        this.content.style.right = null;
        this.content.style.bottom = null;
        this.content.style.width = this._width + "px";
        this.content.style.height = this._height + "px";
        this.content.style.marginLeft = (-this._width / 2) + "px";
        this.content.style.marginTop = (-this._height / 2) + "px";
      }
    }

  }

  window.jikkyo.Modal = document.registerElement("jikkyo-modal", {
    prototype: Modal.prototype
  });

})();
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import isEqual from 'lodash/isEqual'
import {Container, Draggable} from 'react-smooth-dnd'
import uuidv1 from 'uuid/v1'

import Loader from './Loader'
import Card from './Card'
import NewCard from './NewCard'
import {AddCardLink, LaneFooter, LaneHeader, RightContent, ScrollableLane, Section, Title} from '../styles/Base'

import * as laneActions from '../actions/LaneActions'
import {CollapseBtn, ExpandBtn} from '../styles/Elements'

class Lane extends Component {
  state = {
    loading: false,
    currentPage: this.props.currentPage,
    addCardMode: false,
    collapsed: false,
    isDraggingOver: false
  }

  handleScroll = evt => {
    const node = evt.target
    const elemScrolPosition = node.scrollHeight - node.scrollTop - node.clientHeight
    const {onLaneScroll} = this.props
    if (elemScrolPosition <= 0 && onLaneScroll && !this.state.loading) {
      const {currentPage} = this.state
      this.setState({loading: true})
      const nextPage = currentPage + 1
      onLaneScroll(nextPage, this.props.id).then(moreCards => {
        if (!moreCards || moreCards.length === 0) {
          // if no cards present, stop retrying until user action
          node.scrollTop = node.scrollTop - 100
        } else {
          this.props.actions.paginateLane({
            laneId: this.props.id,
            newCards: moreCards,
            nextPage: nextPage
          })
        }
        this.setState({loading: false})
      })
    }
  }

  sortCards(cards, sortFunction) {
    if (!cards) return []
    if (!sortFunction) return cards
    return cards.concat().sort(function(card1, card2) {
      return sortFunction(card1, card2)
    })
  }

  laneDidMount = node => {
    if (node) {
      node.addEventListener('scroll', this.handleScroll)
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!isEqual(this.props.cards, nextProps.cards)) {
      this.setState({
        currentPage: nextProps.currentPage
      })
    }
  }

  removeCard = (laneId, cardId) => {
    this.props.actions.removeCard({laneId: laneId, cardId: cardId})
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !isEqual(this.props.cards, nextProps.cards) || nextState !== this.state
  }

  handleCardClick = (e, card) => {
    const {onCardClick} = this.props
    onCardClick && onCardClick(card.id, card.metadata, card.laneId)
    e.stopPropagation()
    e.preventDefault()
  }

  showEditableCard = () => {
    this.setState({addCardMode: true})
  }

  hideEditableCard = () => {
    this.setState({addCardMode: false})
  }

  addNewCard = params => {
    const laneId = this.props.id
    const id = uuidv1()
    this.hideEditableCard()
    let card = {...params, id}
    this.props.actions.addCard({laneId, card})
    this.props.onCardAdd(card, laneId)
  }

  renderAddCardLink = () => {
    const {addCardLink} = this.props
    if (addCardLink) {
      return {addCardLink}
    } else {
      return <AddCardLink onClick={this.showEditableCard}>Add Card</AddCardLink>
    }
  }

  renderNewCard = () => {
    const {newCardTemplate} = this.props
    if (newCardTemplate) {
      const newCardWithProps = React.cloneElement(newCardTemplate, {
        onCancel: this.hideEditableCard,
        onAdd: this.addNewCard
      })
      return {newCardWithProps}
    } else {
      return <NewCard onCancel={this.hideEditableCard} onAdd={this.addNewCard} />
    }
  }

  onDragStart = (index, payload) => {
    const {handleDragStart} = this.props
    handleDragStart && handleDragStart(payload.id, payload.laneId)
  }

  shouldAcceptDrop = (sourceContainerOptions) => {
    return this.props.droppable && sourceContainerOptions.groupName === 'TrelloLane'
  }

  onDragEnd = (laneId, result) => {
    const {handleDragEnd} = this.props
    const {addedIndex, payload} = result
    if (addedIndex != null) {
      this.props.actions.moveCardAcrossLanes({
        fromLaneId: payload.laneId,
        toLaneId: laneId,
        cardId: payload.id,
        index: addedIndex
      })
      handleDragEnd && handleDragEnd(payload.id, payload.laneId, laneId, addedIndex)
    }
  }

  renderDragContainer = isDraggingOver => {
    const {
      laneSortFunction,
      editable,
      hideCardDeleteIcon,
      tagStyle,
      cardStyle,
      draggable,
      cards,
      id
    } = this.props
    const {addCardMode, collapsed} = this.state

    const showableCards = collapsed ? [] : cards

    const cardList = this.sortCards(showableCards, laneSortFunction).map((card, idx) => {
      const cardToRender = (
        <Card
          key={card.id}
          index={idx}
          customCardLayout={this.props.customCardLayout}
          customCard={this.props.children}
          tagStyle={tagStyle}
          cardStyle={cardStyle}
          removeCard={this.removeCard}
          onClick={e => this.handleCardClick(e, card)}
          onDelete={this.props.onCardDelete}
          editable={editable}
          hideCardDeleteIcon={hideCardDeleteIcon}
          {...card}
        />
      )
      return draggable ? <Draggable key={card.id}>{cardToRender}</Draggable> : {cardToRender}
    })

    return (
      <ScrollableLane innerRef={this.laneDidMount} isDraggingOver={isDraggingOver}>
        <Container
          orientation="vertical"
          groupName="TrelloLane"
          onDragStart={this.onDragStart}
          onDrop={e => this.onDragEnd(id, e)}
          onDragEnter={() => this.setState({isDraggingOver: true})}
          onDragLeave={() => this.setState({isDraggingOver: false})}
          shouldAcceptDrop={this.shouldAcceptDrop}
          getChildPayload={index => this.props.getCardDetails(id, index)}>
          {cardList}
        </Container>
        {editable && !addCardMode && this.renderAddCardLink()}
        {addCardMode && this.renderNewCard()}
      </ScrollableLane>
    )
  }

  renderHeader = () => {
    const {customLaneHeader} = this.props
    if (customLaneHeader) {
      const customLaneElement = React.cloneElement(customLaneHeader, {...this.props})
      return {customLaneElement}
    } else {
      const {title, label, titleStyle, labelStyle} = this.props
      return (
        <LaneHeader onDoubleClick={this.toggleLaneCollapsed}>
          <Title style={titleStyle}>{title}</Title>
          {label && (
            <RightContent>
              {label}
            </RightContent>
          )}
        </LaneHeader>
      )
    }
  }

  renderFooter = () => {
    const {collapsibleLanes, cards} = this.props
    const {collapsed} = this.state
    if (collapsibleLanes && cards.length > 0) {
      return <LaneFooter onClick={this.toggleLaneCollapsed}>{collapsed ? <ExpandBtn /> : <CollapseBtn />}</LaneFooter>
    }
  }

  toggleLaneCollapsed = () => {
    this.props.collapsibleLanes && this.setState(state => ({collapsed: !state.collapsed}))
  }

  render() {
    const {loading, isDraggingOver} = this.state
    const {id, onLaneClick, ...otherProps} = this.props
    return (

 onLaneClick && onLaneClick(id)} draggable={false}>
        {this.renderHeader()}
        {this.renderDragContainer(isDraggingOver)}
        {loading && <Loader />}
        {this.renderFooter()}

    )
  }
}

Lane.propTypes = {
  actions: PropTypes.object,
  children: PropTypes.node,
  id: PropTypes.string.isRequired,
  title: PropTypes.node,
  index: PropTypes.number,
  laneSortFunction: PropTypes.func,
  style: PropTypes.object,
  cardStyle: PropTypes.object,
  tagStyle: PropTypes.object,
  titleStyle: PropTypes.object,
  labelStyle: PropTypes.object,
  customLaneHeader: PropTypes.element,
  customCardLayout: PropTypes.bool,
  cards: PropTypes.array,
  label: PropTypes.string,
  currentPage: PropTypes.number,
  draggable: PropTypes.bool,
  collapsibleLanes: PropTypes.bool,
  droppable: PropTypes.bool,
  onLaneScroll: PropTypes.func,
  onCardClick: PropTypes.func,
  onCardDelete: PropTypes.func,
  onCardAdd: PropTypes.func,
  onLaneClick: PropTypes.func,
  newCardTemplate: PropTypes.node,
  addCardLink: PropTypes.node,
  editable: PropTypes.bool
}

Lane.defaultProps = {
  style: {},
  titleStyle: {},
  labelStyle: {},
  label: undefined,
  editable: false,
  onCardAdd: () => {}
}

const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(laneActions, dispatch)
})

export default connect(null, mapDispatchToProps)(Lane)
<commit_msg>fix: Get rid of shouldComponentUpdate lifecycle method in Lane<commit_after>import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import isEqual from 'lodash/isEqual'
import {Container, Draggable} from 'react-smooth-dnd'
import uuidv1 from 'uuid/v1'

import Loader from './Loader'
import Card from './Card'
import NewCard from './NewCard'
import {AddCardLink, LaneFooter, LaneHeader, RightContent, ScrollableLane, Section, Title} from '../styles/Base'

import * as laneActions from '../actions/LaneActions'
import {CollapseBtn, ExpandBtn} from '../styles/Elements'

class Lane extends Component {
  state = {
    loading: false,
    currentPage: this.props.currentPage,
    addCardMode: false,
    collapsed: false,
    isDraggingOver: false
  }

  handleScroll = evt => {
    const node = evt.target
    const elemScrolPosition = node.scrollHeight - node.scrollTop - node.clientHeight
    const {onLaneScroll} = this.props
    if (elemScrolPosition <= 0 && onLaneScroll && !this.state.loading) {
      const {currentPage} = this.state
      this.setState({loading: true})
      const nextPage = currentPage + 1
      onLaneScroll(nextPage, this.props.id).then(moreCards => {
        if (!moreCards || moreCards.length === 0) {
          // if no cards present, stop retrying until user action
          node.scrollTop = node.scrollTop - 100
        } else {
          this.props.actions.paginateLane({
            laneId: this.props.id,
            newCards: moreCards,
            nextPage: nextPage
          })
        }
        this.setState({loading: false})
      })
    }
  }

  sortCards(cards, sortFunction) {
    if (!cards) return []
    if (!sortFunction) return cards
    return cards.concat().sort(function(card1, card2) {
      return sortFunction(card1, card2)
    })
  }

  laneDidMount = node => {
    if (node) {
      node.addEventListener('scroll', this.handleScroll)
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!isEqual(this.props.cards, nextProps.cards)) {
      this.setState({
        currentPage: nextProps.currentPage
      })
    }
  }

  removeCard = (laneId, cardId) => {
    this.props.actions.removeCard({laneId: laneId, cardId: cardId})
  }

  handleCardClick = (e, card) => {
    const {onCardClick} = this.props
    onCardClick && onCardClick(card.id, card.metadata, card.laneId)
    e.stopPropagation()
    e.preventDefault()
  }

  showEditableCard = () => {
    this.setState({addCardMode: true})
  }

  hideEditableCard = () => {
    this.setState({addCardMode: false})
  }

  addNewCard = params => {
    const laneId = this.props.id
    const id = uuidv1()
    this.hideEditableCard()
    let card = {...params, id}
    this.props.actions.addCard({laneId, card})
    this.props.onCardAdd(card, laneId)
  }

  renderAddCardLink = () => {
    const {addCardLink} = this.props
    if (addCardLink) {
      return {addCardLink}
    } else {
      return <AddCardLink onClick={this.showEditableCard}>Add Card</AddCardLink>
    }
  }

  renderNewCard = () => {
    const {newCardTemplate} = this.props
    if (newCardTemplate) {
      const newCardWithProps = React.cloneElement(newCardTemplate, {
        onCancel: this.hideEditableCard,
        onAdd: this.addNewCard
      })
      return {newCardWithProps}
    } else {
      return <NewCard onCancel={this.hideEditableCard} onAdd={this.addNewCard} />
    }
  }

  onDragStart = (index, payload) => {
    const {handleDragStart} = this.props
    handleDragStart && handleDragStart(payload.id, payload.laneId)
  }

  shouldAcceptDrop = (sourceContainerOptions) => {
    return this.props.droppable && sourceContainerOptions.groupName === 'TrelloLane'
  }

  onDragEnd = (laneId, result) => {
    const {handleDragEnd} = this.props
    const {addedIndex, payload} = result
    if (addedIndex != null) {
      this.props.actions.moveCardAcrossLanes({
        fromLaneId: payload.laneId,
        toLaneId: laneId,
        cardId: payload.id,
        index: addedIndex
      })
      handleDragEnd && handleDragEnd(payload.id, payload.laneId, laneId, addedIndex)
    }
  }

  renderDragContainer = isDraggingOver => {
    const {
      laneSortFunction,
      editable,
      hideCardDeleteIcon,
      tagStyle,
      cardStyle,
      draggable,
      cards,
      id
    } = this.props
    const {addCardMode, collapsed} = this.state

    const showableCards = collapsed ? [] : cards

    const cardList = this.sortCards(showableCards, laneSortFunction).map((card, idx) => {
      const cardToRender = (
        <Card
          key={card.id}
          index={idx}
          customCardLayout={this.props.customCardLayout}
          customCard={this.props.children}
          tagStyle={tagStyle}
          cardStyle={cardStyle}
          removeCard={this.removeCard}
          onClick={e => this.handleCardClick(e, card)}
          onDelete={this.props.onCardDelete}
          editable={editable}
          hideCardDeleteIcon={hideCardDeleteIcon}
          {...card}
        />
      )
      return draggable ? <Draggable key={card.id}>{cardToRender}</Draggable> : {cardToRender}
    })

    return (
      <ScrollableLane innerRef={this.laneDidMount} isDraggingOver={isDraggingOver}>
        <Container
          orientation="vertical"
          groupName="TrelloLane"
          onDragStart={this.onDragStart}
          onDrop={e => this.onDragEnd(id, e)}
          onDragEnter={() => this.setState({isDraggingOver: true})}
          onDragLeave={() => this.setState({isDraggingOver: false})}
          shouldAcceptDrop={this.shouldAcceptDrop}
          getChildPayload={index => this.props.getCardDetails(id, index)}>
          {cardList}
        </Container>
        {editable && !addCardMode && this.renderAddCardLink()}
        {addCardMode && this.renderNewCard()}
      </ScrollableLane>
    )
  }

  renderHeader = () => {
    const {customLaneHeader} = this.props
    if (customLaneHeader) {
      const customLaneElement = React.cloneElement(customLaneHeader, {...this.props})
      return {customLaneElement}
    } else {
      const {title, label, titleStyle, labelStyle} = this.props
      return (
        <LaneHeader onDoubleClick={this.toggleLaneCollapsed}>
          <Title style={titleStyle}>{title}</Title>
          {label && (
            <RightContent>
              {label}
            </RightContent>
          )}
        </LaneHeader>
      )
    }
  }

  renderFooter = () => {
    const {collapsibleLanes, cards} = this.props
    const {collapsed} = this.state
    if (collapsibleLanes && cards.length > 0) {
      return <LaneFooter onClick={this.toggleLaneCollapsed}>{collapsed ? <ExpandBtn /> : <CollapseBtn />}</LaneFooter>
    }
  }

  toggleLaneCollapsed = () => {
    this.props.collapsibleLanes && this.setState(state => ({collapsed: !state.collapsed}))
  }

  render() {
    const {loading, isDraggingOver} = this.state
    const {id, onLaneClick, ...otherProps} = this.props
    return (

 onLaneClick && onLaneClick(id)} draggable={false}>
        {this.renderHeader()}
        {this.renderDragContainer(isDraggingOver)}
        {loading && <Loader />}
        {this.renderFooter()}

    )
  }
}

Lane.propTypes = {
  actions: PropTypes.object,
  children: PropTypes.node,
  id: PropTypes.string.isRequired,
  title: PropTypes.node,
  index: PropTypes.number,
  laneSortFunction: PropTypes.func,
  style: PropTypes.object,
  cardStyle: PropTypes.object,
  tagStyle: PropTypes.object,
  titleStyle: PropTypes.object,
  labelStyle: PropTypes.object,
  customLaneHeader: PropTypes.element,
  customCardLayout: PropTypes.bool,
  cards: PropTypes.array,
  label: PropTypes.string,
  currentPage: PropTypes.number,
  draggable: PropTypes.bool,
  collapsibleLanes: PropTypes.bool,
  droppable: PropTypes.bool,
  onLaneScroll: PropTypes.func,
  onCardClick: PropTypes.func,
  onCardDelete: PropTypes.func,
  onCardAdd: PropTypes.func,
  onLaneClick: PropTypes.func,
  newCardTemplate: PropTypes.node,
  addCardLink: PropTypes.node,
  editable: PropTypes.bool
}

Lane.defaultProps = {
  style: {},
  titleStyle: {},
  labelStyle: {},
  label: undefined,
  editable: false,
  onCardAdd: () => {}
}

const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(laneActions, dispatch)
})

export default connect(null, mapDispatchToProps)(Lane)
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import styled from 'styled-components';

import icons from '../img/icons';
import {colors, sizes, zIndex} from '../constants';

const Wrapper = styled.div`
  width: 100%;
  height: 100%;
  background-color: ${colors.black};
  color: ${colors.white};
  z-index: ${zIndex.list};
  flex-basis: ${sizes.list.height};
  flex-grow: 0;
  display: flex;
  flex-direction: column;
  border: 1px solid ${colors.black};
`;

const Container = styled.div`
  overflow: hidden;
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: ${props => props.direction};
`;

const Item = styled.div`
  flex-grow: 1;
  max-width: 50vw;
  display: flex;
  flex-direction: column;

  &:nth-of-type(even) {
    background-color: ${colors.lightGrey};
  }

  &:nth-of-type(odd) {
    background-color: ${colors.darkGrey};
  }
`;

const Heading = styled.div`
  text-transform: uppercase;
  text-align: right;
  font-size: .8em;
  padding: .4rem;
  background-color: ${colors.black};
`;

const Info = styled.div`
  padding: .4rem;
  flex-grow: 1;
  display: flex;
  align-items: center;
`;

const Text = styled.span`
  margin: .4rem;
`;

export default class List extends Component {
  renderInbound() {
    const {inbound} = this.props.queries;

    return inbound.map((query,index) => (
      <Item key={index}>
        <Heading>{query.destination.name}</Heading>
        <Info>

          <Text>{query.origin.name}</Text>
        </Info>
      </Item>
    ));
  }

  renderOutbound() {
    const {outbound} = this.props.queries;

    return outbound.map((query,index) => (
      <Item key={index}>
        <Heading>{query.origin.name}</Heading>
        <Info>

          <Text>{query.destination.name}</Text>
        </Info>
      </Item>
    ));
  }

  render() {
    return (
      <Wrapper>
        <Container direction="row">
          {this.renderInbound()}
        </Container>
        <Container direction="row-reverse">
          {this.renderOutbound()}
        </Container>
      </Wrapper>
    );
  }
}
<commit_msg>add icon for info<commit_after>import React, {Component} from 'react';
import styled from 'styled-components';

import icons from '../img/icons';
import {colors, sizes, zIndex} from '../constants';

const Wrapper = styled.div`
  width: 100%;
  height: 100%;
  background-color: ${colors.black};
  color: ${colors.white};
  z-index: ${zIndex.list};
  flex-basis: ${sizes.list.height};
  flex-grow: 0;
  display: flex;
  flex-direction: column;
  border: 1px solid ${colors.black};
`;

const Container = styled.div`
  overflow: hidden;
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: ${props => props.direction};
`;

const Item = styled.div`
  flex-grow: 1;
  max-width: 50vw;
  display: flex;
  flex-direction: column;

  &:nth-of-type(even) {
    background-color: ${colors.lightGrey};
  }

  &:nth-of-type(odd) {
    background-color: ${colors.darkGrey};
  }
`;

const Heading = styled.div`
  text-transform: uppercase;
  text-align: right;
  font-size: .8em;
  padding: .4rem;
  color: ${colors.darkGrey};
`;

const Info = styled.div`
  padding: .4rem;
  flex-grow: 1;
  display: flex;
  align-items: center;
`;

const Text = styled.span`
  margin: .4rem;
`;

export default class List extends Component {
  renderInbound() {
    const {inbound} = this.props.queries;

    return inbound.map((query,index) => (
      <Item key={index}>
        <Heading>{query.destination.name}</Heading>
        <Info>

          <Text>{query.origin.name}</Text>
        </Info>
      </Item>
    ));
  }

  renderOutbound() {
    const {outbound} = this.props.queries;

    return outbound.map((query,index) => (
      <Item key={index}>
        <Heading>{query.origin.name}</Heading>
        <Info>

          <Text>{query.destination.name}</Text>
        </Info>
      </Item>
    ));
  }

  render() {
    return (
      <Wrapper>
        <Container direction="row">
          <Item>
            <Text>Outbound</Text>
          </Item>
          {this.renderOutbound()}
        </Container>
        <Container direction="row-reverse">
          <Item>
            <Text>Inbound</Text>
          </Item>
          {this.renderInbound()}
        </Container>
      </Wrapper>
    );
  }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {
	StyleSheet,
	View,
	Text,
	Image,
} from 'react-native';

import logoImg from '../images/lollipop.png';

export default class Logo extends Component {
	render() {
		return (
			<View style={styles.container}>
				<Image source={logoImg} style={styles.image} />
				<Text style={styles.titleText}>POPSWAP</Text>
				<Text style={styles.subText}>keep in touch.</Text>
			</View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		alignItems: 'center',
		justifyContent: 'center',
	},
	image: {
		width: 80,
		height: 80,
	},
	titleText: {
		color: 'white',
		fontWeight: 'bold',
		fontSize: 50,
		backgroundColor: 'transparent',
		marginTop: 30,
	},
	subText: {
		color: 'white',
		fontStyle: 'italic',
	//	fontWeight: 'bold',
		fontSize: 20,
		backgroundColor: 'transparent',
		marginTop: 2,
	}
});
<commit_msg>Delete Logo.js<commit_after><|endoftext|>


<commit_before>var React = require('react');

var HelloWorld = React.createClass({
  render: function () {
    return (

        {this.props.children}

    )
  }
})

module.exports = HelloWorld;
<commit_msg>changed home file component name, set bg<commit_after>var React = require('react');
var styles = require('../styles/baseStyle');
require('../styles/main.css');

var Main = React.createClass({
    componentDidMount: function() {
        console.log(styles.background)
    },
  render: function () {
    return (

            {this.props.children}

    )
  }
})

module.exports = Main;
<|endoftext|>


<commit_before>require('normalize.css');
require('styles/App.css');

import React from 'react';

let yeomanImage = require('../images/yeoman.png');

class AppComponent extends React.Component {
  render() {
    return (

Please edit src/components/Main.js to get started!

    );
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;
<commit_msg>change doublo quotes to single<commit_after>require('normalize.css');
require('styles/App.css');

import React from 'react';

let yeomanImage = require('../images/yeoman.png');

class AppComponent extends React.Component {
  render() {
    return (

Please edit src/components/Main.js to get started!

    );
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;
<|endoftext|>


<commit_before>const path = require("path");
const webpack = require("webpack");

const KG_SAVEGAME = process.env.KG_SAVEGAME ?? "./fixtures/lategame";
const KS_SETTINGS = process.env.KS_SETTINGS ?? "./fixtures/localstorage.json";

module.exports = {
  devtool: "inline-source-map",
  entry: path.resolve(__dirname, "source", "index.ts"),
  mode: "development",
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: require.resolve("ts-loader"),
      },
    ],
  },
  output: {
    path: path.resolve(__dirname, "output"),
    filename: "kitten-scientists.inject.js",
  },
  plugins: [
    new webpack.NormalModuleReplacementPlugin(/.\/fixtures\/savegame/, KG_SAVEGAME),
    new webpack.NormalModuleReplacementPlugin(/.\/fixtures\/settings/, KS_SETTINGS),
  ],
  resolve: {
    extensions: [".ts", ".js"],
  },
};
<commit_msg>fix: Don't inject unless instructed<commit_after>const path = require("path");
const webpack = require("webpack");

const KG_SAVEGAME = process.env.KG_SAVEGAME ?? "./fixtures/lategame";
const KS_SETTINGS = process.env.KS_SETTINGS ?? "./fixtures/localstorage.json";

module.exports = {
  devtool: "inline-source-map",
  entry: path.resolve(__dirname, "source", "index.ts"),
  mode: "development",
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: require.resolve("ts-loader"),
      },
    ],
  },
  output: {
    path: path.resolve(__dirname, "output"),
    filename: "kitten-scientists.inject.js",
  },
  plugins: process.env.KG_INJECT
    ? [
        new webpack.NormalModuleReplacementPlugin(/.\/fixtures\/savegame/, KG_SAVEGAME),
        new webpack.NormalModuleReplacementPlugin(/.\/fixtures\/settings/, KS_SETTINGS),
      ]
    : [],
  resolve: {
    extensions: [".ts", ".js"],
  },
};
<|endoftext|>