<commit_before>/*
 * This is an extremely simple HTTP file server
 */

var serveStatic  = require( 'serve-static' );
var http         = require( 'http' );
var finalhandler = require( 'finalhandler' );
var url          = require( 'url' );
var fs           = require( 'fs' );
var path         = require( 'path' );
var mkdirp       = require( 'mkdirp' );

var DEFAULT_PORT = 8080;
var DEFAULT_DIR  = '.';
var root_dir     = null;

var CORS_HEADERS = [ ['Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,DELETE'],
                     [ 'Access-Control-Allow-Origin', '*' ],
                     [ 'Access-Control-Allow-Headers',
                       'Origin, X-Requested-With, Content-Type, Accept' ] ];

var log = console.log.bind( console );

function assert( property, msg, resp )
{
    if( property )
        return;
    log( '[Simple File Server] Internal error', msg );
    resp.writeHead( 500 );
    resp.end();
}

function pathSanity( path, resp )
{
    assert( path.length >= 2, 'Path too short', resp );
    assert( path[0] == '', 'Text before first slash', resp )
}

function writeFile( pathname, contents, resp )
{
    var dirs = pathname.split( '/' );
    pathSanity( dirs, resp );
    var filename = dirs[ dirs.length - 1 ];
    var fdir = path.join( root_dir, dirs.slice( 1, dirs.length - 1 ).join( path.sep ) );
    mkdirp( fdir, function( err )
    {
        if( err )
        {
            log( 'Simple File Server: mkdir error', err );
            resp.writeHead( 500 );
            resp.end();
            return;
        }
        fs.writeFile( path.join( fdir, filename ), contents, function( err )
        {
            if( err )
            {
                log( 'Simple File Server: write error', err );
                resp.writeHead( 500 );
                resp.end();
                return;
            }
            log( 'Simple File Server: Wrote file', pathname );
            resp.writeHead( 200 );
            resp.end();
        } );
    } );
}

function handlePost( req, resp )
{
    log( '[Simple File Server] Post', req.url );
    var body = [];
    req.addListener( 'data', function( chunk ) { body.push( chunk ); } );
    req.addListener( 'end', function()
    {
        writeFile( url.parse( req.url ).pathname, Buffer.concat( body ), resp );
    } );
}

function handleDelete( req, resp )
{
    log( '[Simple File Server] Delete', req.url );
    var parsedUrl = url.parse( req.url );
    var file_path = parsedUrl.pathname;
    var dirs = file_path.split( '/' );
    pathSanity( dirs, resp );
    var filename = dirs[ dirs.length - 1 ];
    var fdir = path.join( root_dir, dirs.slice( 1, dirs.length - 1 ).join( path.sep ) );
    fs.unlink( path.join( fdir, filename ), function( err ) {
        if( err )
        {
            log( '[Simple File Server] Error during delete', err );
            resp.writeHead( 404 );
            resp.end();
        }
        else
        {
            log( '[Simple File Server] Deleted', path.join( fdir, filename ) );
            resp.writeHead( 200 );
            resp.end();
        }
    } );
}

function handleOptions( req, resp ) {
    if(req.headers["access-control-request-method"] == 'DELETE') {
        log( 'Accepted preflight DELETE request' );
        resp.writeHead( 200 );
        resp.end();
    }
    else if( req.headers[ 'access-control-request-method' ] == 'POST' ) {
        log( 'Accepted preflight POST request' );
        resp.writeHead( 200 );
        resp.end();
    }
    else
    {
        log( 'Mystery request', req );
        throw new Error( 'Blah' );
    }
}

function handleDynamic( req, resp )
{
    if(      req.method == 'POST' )   return handlePost( req, resp );
    else if( req.method == 'DELETE' ) return handleDelete( req, resp );
    else if ( req.method == 'OPTIONS' ) return handleOptions( req, resp );
    log( '[Simple File Server] Not POST or DELETE or OPTIONS', req.url, req.method );

    return finalhandler( req, resp )();
}

function runServer()
{
    var p = parseArgs();

    var serveFiles = serveStatic( root_dir, { 'index': [ 'index.html', 'index.htm' ] } );
    // var serveFiles = serveStatic( root_dir, { 'index': false } );

    var server = http.createServer(
        function( req, resp ) {
            for( i = 0; i < CORS_HEADERS.length; i++ )
            {
                resp.setHeader( CORS_HEADERS[i][0], CORS_HEADERS[i][1] );
            }
            serveFiles( req, resp, function() { handleDynamic( req, resp ) } );
        } );
    server.listen( p );
    log( 'Simple File Server: Serving directory', root_dir, 'on port', p );
}

function parseArgs()
{
    var p = null;
    for( i = 2; i < process.argv.length; i++ )
    {
        var x = parseInt( process.argv[i] );
        if( isNaN( x ) )
        {
            if( !root_dir )
                root_dir = process.argv[i];
        }
        else
        {
            if( !p )
                p = x;
        }
    }
    if( !root_dir )
        root_dir = DEFAULT_DIR;
    if( !p )
        p = DEFAULT_PORT;
    return p;
}

runServer();
<commit_msg>Added HTTPS support<commit_after>/*
 * This is an extremely simple HTTP file server
 */

var DEFAULT_PORT = 8080;
var DEFAULT_DIR  = '.';

var serveStatic  = require( 'serve-static' );
var http         = require( 'http' );
var https        = require( 'https' );
var finalhandler = require( 'finalhandler' );
var url          = require( 'url' );
var fs           = require( 'fs' );
var path         = require( 'path' );
var mkdirp       = require( 'mkdirp' );
var opt          = require( 'node-getopt' ).create( [
    [ 'P', 'port=PORT',      'Port to server on; default is '+DEFAULT_PORT ],
    [ 'D', 'dir=DIR',        'Root directory to serve from; default is '+DEFAULT_DIR ],
    [ 'C', 'cert=CERT_FILE', 'Certificate file; will serve over HTTP if not given' ],
    [ 'K', 'key=KEY_FILE',   'key file; will serve over HTTP if not given' ] ] )
  .bindHelp().parseSystem();

var root_dir = DEFAULT_DIR;

var CORS_HEADERS = [ ['Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,DELETE'],
                     [ 'Access-Control-Allow-Origin', '*' ],
                     [ 'Access-Control-Allow-Headers',
                       'Origin, X-Requested-With, Content-Type, Accept' ] ];

var log = console.log.bind( console );

function assert( property, msg, resp )
{
    if( property )
        return;
    log( '[Simple File Server] Internal error', msg );
    resp.writeHead( 500 );
    resp.end();
}

function pathSanity( path, resp )
{
    assert( path.length >= 2, 'Path too short', resp );
    assert( path[0] == '', 'Text before first slash', resp )
}

function writeFile( pathname, contents, resp )
{
    var dirs = pathname.split( '/' );
    pathSanity( dirs, resp );
    var filename = dirs[ dirs.length - 1 ];
    var fdir = path.join( root_dir, dirs.slice( 1, dirs.length - 1 ).join( path.sep ) );
    mkdirp( fdir, function( err )
    {
        if( err )
        {
            log( 'Simple File Server: mkdir error', err );
            resp.writeHead( 500 );
            resp.end();
            return;
        }
        fs.writeFile( path.join( fdir, filename ), contents, function( err )
        {
            if( err )
            {
                log( 'Simple File Server: write error', err );
                resp.writeHead( 500 );
                resp.end();
                return;
            }
            log( 'Simple File Server: Wrote file', pathname );
            resp.writeHead( 200 );
            resp.end();
        } );
    } );
}

function handlePost( req, resp )
{
    log( '[Simple File Server] Post', req.url );
    var body = [];
    req.addListener( 'data', function( chunk ) { body.push( chunk ); } );
    req.addListener( 'end', function()
    {
        writeFile( url.parse( req.url ).pathname, Buffer.concat( body ), resp );
    } );
}

function handleDelete( req, resp )
{
    log( '[Simple File Server] Delete', req.url );
    var parsedUrl = url.parse( req.url );
    var file_path = parsedUrl.pathname;
    var dirs = file_path.split( '/' );
    pathSanity( dirs, resp );
    var filename = dirs[ dirs.length - 1 ];
    var fdir = path.join( root_dir, dirs.slice( 1, dirs.length - 1 ).join( path.sep ) );
    fs.unlink( path.join( fdir, filename ), function( err ) {
        if( err )
        {
            log( '[Simple File Server] Error during delete', err );
            resp.writeHead( 404 );
            resp.end();
        }
        else
        {
            log( '[Simple File Server] Deleted', path.join( fdir, filename ) );
            resp.writeHead( 200 );
            resp.end();
        }
    } );
}

function handleOptions( req, resp ) {
    if(req.headers["access-control-request-method"] == 'DELETE') {
        log( 'Accepted preflight DELETE request' );
        resp.writeHead( 200 );
        resp.end();
    }
    else if( req.headers[ 'access-control-request-method' ] == 'POST' ) {
        log( 'Accepted preflight POST request' );
        resp.writeHead( 200 );
        resp.end();
    }
    else
    {
        log( 'Mystery request', req );
        throw new Error( 'Blah' );
    }
}

function handleDynamic( req, resp )
{
    if(      req.method == 'POST' )   return handlePost( req, resp );
    else if( req.method == 'DELETE' ) return handleDelete( req, resp );
    else if ( req.method == 'OPTIONS' ) return handleOptions( req, resp );
    log( '[Simple File Server] Not POST or DELETE or OPTIONS', req.url, req.method );

    return finalhandler( req, resp )();
}

function runServer()
{
    console.log( opt.options );
    if( 'dir' in opt.options )
        root_dir = opt.options.dir;
    var port = DEFAULT_PORT;
    if( 'port' in opt.options )
    {
        var x = parseInt( opt.options.port );
        if( !isNaN( x ) )
            port = x;
    }

    var serveFiles = serveStatic( root_dir, { 'index': [ 'index.html', 'index.htm' ] } );

    function handleReq( req, resp ) {
        for( i = 0; i < CORS_HEADERS.length; i++ )
        {
            resp.setHeader( CORS_HEADERS[i][0], CORS_HEADERS[i][1] );
        }
        serveFiles( req, resp, function() { handleDynamic( req, resp ) } );
    }

    var server, protocol = 'HTTP';
    if( 'cert' in opt.options && 'key' in opt.options )
    {
        var options = {
            key:  fs.readFileSync( opt.options.key ),
            cert: fs.readFileSync( opt.options.cert )
        };
        server = https.createServer( options, handleReq );
        protocol = 'HTTPS'
    }
    else
    {
        server = http.createServer( handleReq );
    }
    server.listen( port );
    log( 'Simple File Server: Serving directory', root_dir, 'on port', port, 'with protocol', protocol );
}

runServer();
<|endoftext|>


<commit_before>import { bind } from 'decko';
import React from 'react';
import { findDOMNode } from 'react-dom';

/**
 * A modal dialog window.
 */
class Dialog extends React.Component {
  componentDidMount () {
    this.elDialog = findDOMNode(this.refs.dialog);

    document.body.addEventListener('keydown', this.onEsc);
  }

  componentWillUnmount () {
    document.body.removeEventListener('keydown', this.onEsc);
  }

  @bind
  onEsc (e) {
    e = e || window.event;
    if (e.keyCode == 27) {
      this.props.onClose();
    }
  }

  @bind
  onOverlayClick (e) {
    // Close (i.e. cancel) the dialog if the outer overlay is clicked
    if (!this.elDialog.contains(e.target)) {
      var exit = confirm("Are you sure you want to exit the editor" +
        "and lose all progress on your current CRC card?");
      if (exit == true) {
        this.props.onClose();
      }
    }
  }

  render () {
    return (

{this.props.title}

          {this.props.children}

    );
  }
}

export default Dialog;
<commit_msg>Move confirm call directly in the if statement<commit_after>import { bind } from 'decko';
import React from 'react';
import { findDOMNode } from 'react-dom';

/**
 * A modal dialog window.
 */
class Dialog extends React.Component {
  componentDidMount () {
    this.elDialog = findDOMNode(this.refs.dialog);

    document.body.addEventListener('keydown', this.onEsc);
  }

  componentWillUnmount () {
    document.body.removeEventListener('keydown', this.onEsc);
  }

  @bind
  onEsc (e) {
    e = e || window.event;
    if (e.keyCode == 27) {
      this.props.onClose();
    }
  }

  @bind
  onOverlayClick (e) {
    // Close (i.e. cancel) the dialog if the outer overlay is clicked
    if (!this.elDialog.contains(e.target) &&
      confirm("Are you sure you want to exit the editor " +
        "and lose all progress on your current CRC card?")) {
        this.props.onClose();
    }
  }

  render () {
    return (

{this.props.title}

          {this.props.children}

    );
  }
}

export default Dialog;
<|endoftext|>


<commit_before>const _get = require('lodash/get');
const _isEqual = require('lodash/isEqual');
const _isNumber = require('lodash/isNumber');
const _merge = require('lodash/merge');
const _throttle = require('lodash/throttle');
const _uniqueId = require('lodash/uniqueId');
const keycode = require('keycode');
const PropTypes = require('prop-types');
const React = require('react');
const Velocity = require('velocity-animate');
const { StyleRoot } = require('radium');

import { withTheme } from './Theme';
const Button = require('../components/Button');
const MXFocusTrap = require('../components/MXFocusTrap');

const { themeShape } = require('../constants/App');

const StyleUtils = require('../utils/Style');
const { deprecatePrimaryColor } = require('../utils/Deprecation');

class Drawer extends React.Component {
  static propTypes = {
    'aria-describedby': PropTypes.string,
    'aria-labelledby': PropTypes.string,
    animateLeftDistance: PropTypes.number,
    animateOnClose: PropTypes.bool,
    beforeClose: PropTypes.func,
    breakPoints: PropTypes.shape({
      large: PropTypes.number,
      medium: PropTypes.number
    }),
    buttonPrimaryColor: PropTypes.string,
    closeButtonAriaLabel: PropTypes.string,
    closeOnScrimClick: PropTypes.bool,
    contentStyle: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object
    ]),
    duration: PropTypes.number,
    easing: PropTypes.array,
    focusOnLoad: PropTypes.bool,
    focusTrapProps: PropTypes.object,
    headerMenu: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.func
    ]),
    headerStyle: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object
    ]),
    maxWidth: PropTypes.number,
    navConfig: PropTypes.shape({
      label: PropTypes.string.isRequired,
      onNextClick: PropTypes.func.isRequired,
      onPreviousClick: PropTypes.func.isRequired
    }),
    onClose: PropTypes.func.isRequired,
    onKeyUp: PropTypes.func,
    onOpen: PropTypes.func,
    portalTo: PropTypes.string,
    role: PropTypes.string,
    showCloseButton: PropTypes.bool,
    showScrim: PropTypes.bool,
    styles: PropTypes.object,
    theme: themeShape,
    title: PropTypes.string
  };

  static defaultProps = {
    animateOnClose: true,
    beforeClose: () => {},
    closeOnScrimClick: true,
    duration: 500,
    easing: [0.28, 0.14, 0.34, 1.04],
    focusOnLoad: true,
    focusTrapProps: {},
    maxWidth: 960,
    onOpen: () => {},
    role: 'dialog',
    showCloseButton: true,
    showScrim: true,
    title: ''
  };

  constructor (props) {
    super(props);

    const theme = StyleUtils.mergeTheme(props.theme, props.buttonPrimaryColor);
    const breakPoints = props.breakPoints || theme.BreakPoints;

    this.state = { breakPoints, theme };
  }

  componentWillMount () {
    this._resizeThrottled = _throttle(this._resize, 100);
  }

  componentDidMount () {
    deprecatePrimaryColor(this.props, 'buttonPrimaryColor');
    this.open();
    window.addEventListener('resize', this._resizeThrottled);

    if (this.props.focusOnLoad) {
      // Close button might not be present depending on showCloseButton Prop
      if (this.props.showCloseButton && this._closeButton) {
        this._closeButton.focus();
      // Fall back to focusing the component if no close button
      } else if (this._component) {
        this._component.focus();
      }
    }
  }

  componentWillReceiveProps (newProps) {
    if (!_isEqual(newProps.breakPoints, this.props.breakPoints)) {
      this.setState({
        breakPoints: this.props.breakPoints
      });
    }
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this._resizeThrottled);
  }

  _getAnimationDistance = () => {
    if (_isNumber(this.props.animateLeftDistance)) {
      return this.props.animateLeftDistance + '%';
    }

    const windowWidth = window.innerWidth;

    if (windowWidth >= this.state.breakPoints.large) {
      //Resolution - maxWidth
      return windowWidth - this.props.maxWidth;
    } else if (windowWidth <= this.state.breakPoints.medium) {
      //All the way over to the left
      return 0;
    } else {
      //20% from the left
      const newLeft = windowWidth * 0.2;

      return Math.max(newLeft, windowWidth - this.props.maxWidth);
    }
  };

  _getExposedDrawerFunctions = () => {
    return { close: this.close };
  };

  /**
   * Figure out the height of the header. This can come from either:
   *
   * this.props.headerStyle.height
   * this.props.header.height
   *
   * If neither are set, default to 50px
   */
  _getHeaderHeight = () => {
    return _get(this.props, ['headerStyle', 'height'],
                _get(this.props,
                     ['styles', 'header', 'height'],
                     '50px'));
  };

  /**
   * Animate the Drawer closed and then call the onClose callback.
   *
   * @returns {Promise} that is resolved when the animation finishes
   */
  close = () => {
    this.props.beforeClose();

    if (this.props.animateOnClose) {
      return this._animateComponent({ left: '100%' })
        .then(() => {
          this.props.onClose();
        });
    } else {
      // To keep close's api normalized we return a promise just
      // as the _animateComponent function does above.
      return Promise.resolve()
        .then(() => {
          this.props.onClose();
        });
    }
  };

  open = () => {
    return this._animateComponent({ left: this._getAnimationDistance() })
      .then(() => {
        this.props.onOpen();
      });
  };

  _animateComponent = (transition, extraOptions) => {
    const el = this._component;
    const options = Object.assign({
      duration: this.props.duration,
      easing: this.props.easing
    }, extraOptions);

    return Velocity(el, transition, options);
  };

  _handleKeyUp = e => {
    e.preventDefault();
    e.stopPropagation();

    if (keycode(e) === 'esc') this.close();
  };

  _resize = () => {
    this._animateComponent({ left: this._getAnimationDistance() }, { duration: 0 });
  };

  _renderNav = (navConfig, styles, theme) => {
    return (

        <Button
          icon='caret-left'
          onClick={navConfig.onPreviousClick}
          theme={theme}
          type='base'
        />

          {navConfig.label}

        <Button
          icon='caret-right'
          onClick={navConfig.onNextClick}
          theme={theme}
          type='base'
        />

    );
  };

  render () {
    const { theme } = this.state;
    const styles = this.styles(theme);
    const { closeButtonAriaLabel, headerMenu, focusTrapProps, navConfig } = this.props;
    const mergedFocusTrapProps = {
      focusTrapOptions: {
        clickOutsideDeactivates: true
      },
      paused: false,
      ...focusTrapProps
    };

    let menu = null;

    // If headerMenu is a function then we want to pass the Drawer's
    // exposed functions to the call.
    if (typeof headerMenu === 'function') {
      menu = headerMenu(this._getExposedDrawerFunctions());
    // If headerMenu is a normal node/element then use directly.
    } else if (headerMenu) {
      menu = headerMenu;
    // If no headerMenu and navConfig passed then use Drawer's
    // _renderNav function to generate the menu.
    } else if (navConfig) {
      menu = this._renderNav(navConfig, styles, theme);
    }
    const titleUniqueId = _uniqueId('mx-drawer-title-');

    return (


<commit_before>require.config({
    paths: {
        jquery: '/js/lib/jquery/dist/jquery',
        spin: '/js/lib/spin.js/spin',
        bootstrap: '/js/lib/bootstrap/dist/js/bootstrap',
	bootstrapAutoHiding: '/js/lib/bootstrap-autohidingnavbar/dist/jquery.bootstrap-autohidingnavbar',

        angular: '/js/lib/angular/angular',
        angularRoute: '/js/lib/angular-route/angular-route',
	angularScroll: '/js/lib/angular-scroll/angular-scroll',
        angularBootstrap: '/js/lib/angular-bootstrap/ui-bootstrap-tpls',
        angularSpinner: '/js/lib/angular-spinner/angular-spinner'
    },
    shim: {
	'bootstrapAutoHiding': {
	    deps: ['bootstrap'],
	    exports: 'bootstrapAutoHiding'
	},
	'bootstrap': {
	    deps: ['jquery'],
	    exports: 'bootstrap'
	},
	'angularScroll': {
	    deps: ['angular'],
	    exports: 'angularScroll'
	},
        'angularSpinner': {
            deps: ['angular', 'spin'],
            exports: 'angular'
        },
        'angularBootstrap': {
            deps: ['angular'],
            exports: 'angular'
        },
        'angularRoute': {
            deps: ['angular'],
            exports: 'angular'
        },
        'angular': {
            deps: ['jquery'],
            exports: 'angular'
        }
    },
    deps: ['app']
});

define('app', ["jquery", "angular", "angularBootstrap", "angularRoute", "angularScroll",
	       "angularSpinner", "bootstrap", "bootstrapAutoHiding"],
       function($, angular)
{
    var app = angular.module("FringeApp", ['ngRoute', 'ui.bootstrap', 'duScroll', 'angularSpinner']);

    app.directive('dynamic', function ($compile) {
	return {
	    restrict: 'A',
	    replace: true,
	    link: function (scope, ele, attrs) {
		scope.$watch(attrs.dynamic, function(html) {
		    ele.html(html);
		    $compile(ele.contents())(scope);
		});
	    }
	};
    });

    app.controller("sidebar", function($scope, $location) {
        $scope.$on('$locationChangeSuccess', function(event) {
            var context = $location.path()
            if (context.substring(1, 7) == "videos" || context.substring(1, 7) == "league") {
                $scope.tab = "vods"
            } else {
                $scope.tab = context
            }
        })
    })

    app.config(
        ['$routeProvider',
            function($routeProvider) {
                $routeProvider
                    .when('/about', {
                        templateUrl: 'about.html',
                        controller: 'about'
                    })
                    .when('/upcoming', {
                        templateUrl: 'listview.html',
                        controller: 'upcoming'
                    })
                    .when('/live', {
                        templateUrl: 'listview.html',
                        controller: 'live'
                    })
                    .when('/streams', {
                        templateUrl: 'streams.html',
                        controller: 'streams'
                    })
                    .when('/vods', {
                        templateUrl: 'vods.html',
                        controller: 'vods'
                    })
                    .when('/league/:param', {
                        templateUrl: 'league.html',
                        controller: 'league'
                    })
                    .when('/videos/:league/:resourceUrl*', {
                        templateUrl: 'breadcrumb.html',
                        controller: 'videos'
                    })
                    .when('/', {
                        redirectTo: "/about"
                    })
                    .otherwise({
                        redirectTo: '/'
                    })
            }
        ]
    )

    app.controller('about', function($scope, $http, usSpinnerService) {
	$http.get('/api/live').success(function(data) {
	    $scope.live = false
	    if (data.length > 0) {
		var eindex = Math.floor(Math.random() * data.length)
		$scope.event = data.live_events[eindex]
		if (typeof($scope.event.stream) == 'object') {
		    $scope.html = $scope.event.stream.embed
		    $scope.live = true
		}
	    }
	})
    })

    app.controller('upcoming', function($scope, $http, usSpinnerService) {
        $http.get('/api/upcoming').success(function(data) {
            $scope.data = data['events']
            $scope.data[0]['first'] = true
	    for (i in $scope.data) {
		if (typeof($scope.data[i].stream) == 'object') {
		    if ($scope.data[i].stream == null) {
			$scope.data[i].stream = 'Stream is unavailable'
		    } else {
			$scope.data[i].stream = $scope.data[i].stream.stream
		    }
		}
            }
            $scope.valid = true
            usSpinnerService.stop('loader')
        })
        $scope.name = 'Upcoming Events'
        $scope.oneAtATime = true;
    })

    app.controller('live', function($scope, $http, usSpinnerService) {
        $http.get('/api/live').success(function(data) {
            $scope.data = data['live_events']
            $scope.valid = ($scope.data.length > 0) ? true : false
            if ($scope.valid) {
                $scope.data[0]['first'] = true
            }
            for (i in $scope.data) {
                if (typeof($scope.data[i].stream) == 'object') {
		    if ($scope.data[i].stream == null) {
			$scope.data[i].stream = 'Stream is unavailable'
		    } else {
			$scope.data[i].stream = $scope.data[i].stream.stream
		    }
                }
            }
            usSpinnerService.stop('loader')
        })
        $scope.name = 'Live Events'
        $scope.oneAtATime = true
        $scope.valid = false
    })

    app.controller('streams', function($scope, $http, usSpinnerService) {
        $http.get('/api/streams').success(function(data) {
            $scope.data = data['starcraft2']
            $scope.data[0]['first'] = true
            for (i in $scope.data) {
                if ($scope.data[i].logo == null) {
                    $scope.data[i].logo = "http://s.jtvnw.net/jtv_user_pictures/hosted_images/GlitchIcon_purple.png"
                }
            }
            $scope.valid = true
            usSpinnerService.stop('loader')
        })
        $scope.oneAtATime = true
        $scope.valid = false
    })

    app.controller('league', function($scope, $routeParams, $http) {
        $http.get('/api/league/' + $routeParams.param + '/events').success(function(data) {
            $scope.events = data
            $scope.name = $routeParams.param
        })
    })

    app.controller('videos', function($scope, $routeParams, $http, $document, usSpinnerService) {
        var league = $routeParams['league']
        var path = $routeParams['resourceUrl'].split('/')

        var basePath = '#/videos/' + league
        $scope.breadcrumb = []
        for (var i in path) {
            var elem = path[i]
            basePath += '/' + elem
            $scope.breadcrumb.push({
                'key': elem,
                'href': basePath
            })
        }
        $scope.league = league
        $scope.event = path[0]
        $scope.basePath = basePath
        $scope.backToLeagues = "#/league/" + league

        $http.get('/api/league/' + league + '/event/' + $scope.event).success(function(data) {
            $scope.data = data

            for (var i in path) {
                var elem = path[i]
                $scope.data = $scope.data[elem]
            }

	    $scope.isEmbed = false
            $scope.isList = false
            $scope.isDir = false
            $scope.listKeys = $scope.data['_keys']
            if ($scope.data['_type'] == 'list') {
                $scope.isList = true
            } else {
                $scope.isDir = true
            }
            usSpinnerService.stop('loader')
        })

	$scope.watchVideo = function(video) {
	    usSpinnerService.spin('loader')
	    $scope.title = video.title
	    $scope.html = video.embed
	    $scope.isEmbed = true
	    $document.scrollTopAnimated(0)
	    usSpinnerService.stop('loader')
	}
	$scope.clearVideo = function() {
	    $scope.isEmbed = false
	}
    })

    app.controller('vods', function($scope, $http) {
        $http.get('/api/leagues').success(function(data) {
            var leagues = $scope.leagues = []

            $scope.addLeague = function(name) {
                $http.get('/api/league/' + name).success(function(channel) {
                    channel['_name'] = name
                    leagues.push(channel);
                })
            };

            for (var i in data['leagues']) {
                $scope.addLeague(data['leagues'][i])
            }
        })
    })

    angular.bootstrap(document, ['FringeApp']);
    $("div.navbar-fixed-top").autoHidingNavbar();

    return app;
});
<commit_msg>Specify cdnjs urls in precedence over hosting<commit_after>require.config({
    paths: {
        jquery: [
	    'https://code.jquery.com/jquery-2.1.1.min',
	    '/js/lib/jquery/dist/jquery'],

        spin: [
	    '//cdnjs.cloudflare.com/ajax/libs/spin.js/2.0.1/jquery.spin.min',
	    '/js/lib/spin.js/spin'],

        bootstrap: [
	    '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min',
	    '/js/lib/bootstrap/dist/js/bootstrap'],

	bootstrapAutoHiding: [
	    '/js/lib/bootstrap-autohidingnavbar/dist/jquery.bootstrap-autohidingnavbar'],

        angular: [
	    '//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min',
	    '/js/lib/angular/angular'],

        angularRoute: [
	    '//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min',
	    '/js/lib/angular-route/angular-route'],

	angularScroll: [
	    '/js/lib/angular-scroll/angular-scroll'],

        angularBootstrap: [
	    '//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min',
	    '/js/lib/angular-bootstrap/ui-bootstrap-tpls'],

        angularSpinner: [
	    '//cdnjs.cloudflare.com/ajax/libs/angular-spinner/0.5.1/angular-spinner.min',
	    '/js/lib/angular-spinner/angular-spinner']
    },
    shim: {
	'bootstrapAutoHiding': {
	    deps: ['bootstrap'],
	    exports: 'bootstrapAutoHiding'
	},
	'bootstrap': {
	    deps: ['jquery'],
	    exports: 'bootstrap'
	},
	'angularScroll': {
	    deps: ['angular'],
	    exports: 'angularScroll'
	},
        'angularSpinner': {
            deps: ['angular', 'spin'],
            exports: 'angular'
        },
        'angularBootstrap': {
            deps: ['angular'],
            exports: 'angular'
        },
        'angularRoute': {
            deps: ['angular'],
            exports: 'angular'
        },
        'angular': {
            deps: ['jquery'],
            exports: 'angular'
        }
    },
    deps: ['app']
});

define('app', ["jquery", "angular", "angularBootstrap", "angularRoute", "angularScroll",
	       "angularSpinner", "bootstrap", "bootstrapAutoHiding"],
       function($, angular)
{
    var app = angular.module("FringeApp", ['ngRoute', 'ui.bootstrap', 'duScroll', 'angularSpinner']);

    app.directive('dynamic', function ($compile) {
	return {
	    restrict: 'A',
	    replace: true,
	    link: function (scope, ele, attrs) {
		scope.$watch(attrs.dynamic, function(html) {
		    ele.html(html);
		    $compile(ele.contents())(scope);
		});
	    }
	};
    });

    app.controller("sidebar", function($scope, $location) {
        $scope.$on('$locationChangeSuccess', function(event) {
            var context = $location.path()
            if (context.substring(1, 7) == "videos" || context.substring(1, 7) == "league") {
                $scope.tab = "vods"
            } else {
                $scope.tab = context
            }
        })
    })

    app.config(
        ['$routeProvider',
            function($routeProvider) {
                $routeProvider
                    .when('/about', {
                        templateUrl: 'about.html',
                        controller: 'about'
                    })
                    .when('/upcoming', {
                        templateUrl: 'listview.html',
                        controller: 'upcoming'
                    })
                    .when('/live', {
                        templateUrl: 'listview.html',
                        controller: 'live'
                    })
                    .when('/streams', {
                        templateUrl: 'streams.html',
                        controller: 'streams'
                    })
                    .when('/vods', {
                        templateUrl: 'vods.html',
                        controller: 'vods'
                    })
                    .when('/league/:param', {
                        templateUrl: 'league.html',
                        controller: 'league'
                    })
                    .when('/videos/:league/:resourceUrl*', {
                        templateUrl: 'breadcrumb.html',
                        controller: 'videos'
                    })
                    .when('/', {
                        redirectTo: "/about"
                    })
                    .otherwise({
                        redirectTo: '/'
                    })
            }
        ]
    )

    app.controller('about', function($scope, $http, usSpinnerService) {
	$http.get('/api/live').success(function(data) {
	    $scope.live = false
	    if (data.length > 0) {
		var eindex = Math.floor(Math.random() * data.length)
		$scope.event = data.live_events[eindex]
		if (typeof($scope.event.stream) == 'object') {
		    $scope.html = $scope.event.stream.embed
		    $scope.live = true
		}
	    }
	})
    })

    app.controller('upcoming', function($scope, $http, usSpinnerService) {
        $http.get('/api/upcoming').success(function(data) {
            $scope.data = data['events']
            $scope.data[0]['first'] = true
	    for (i in $scope.data) {
		if (typeof($scope.data[i].stream) == 'object') {
		    if ($scope.data[i].stream == null) {
			$scope.data[i].stream = 'Stream is unavailable'
		    } else {
			$scope.data[i].stream = $scope.data[i].stream.stream
		    }
		}
            }
            $scope.valid = true
            usSpinnerService.stop('loader')
        })
        $scope.name = 'Upcoming Events'
        $scope.oneAtATime = true;
    })

    app.controller('live', function($scope, $http, usSpinnerService) {
        $http.get('/api/live').success(function(data) {
            $scope.data = data['live_events']
            $scope.valid = ($scope.data.length > 0) ? true : false
            if ($scope.valid) {
                $scope.data[0]['first'] = true
            }
            for (i in $scope.data) {
                if (typeof($scope.data[i].stream) == 'object') {
		    if ($scope.data[i].stream == null) {
			$scope.data[i].stream = 'Stream is unavailable'
		    } else {
			$scope.data[i].stream = $scope.data[i].stream.stream
		    }
                }
            }
            usSpinnerService.stop('loader')
        })
        $scope.name = 'Live Events'
        $scope.oneAtATime = true
        $scope.valid = false
    })

    app.controller('streams', function($scope, $http, usSpinnerService) {
        $http.get('/api/streams').success(function(data) {
            $scope.data = data['starcraft2']
            $scope.data[0]['first'] = true
            for (i in $scope.data) {
                if ($scope.data[i].logo == null) {
                    $scope.data[i].logo = "http://s.jtvnw.net/jtv_user_pictures/hosted_images/GlitchIcon_purple.png"
                }
            }
            $scope.valid = true
            usSpinnerService.stop('loader')
        })
        $scope.oneAtATime = true
        $scope.valid = false
    })

    app.controller('league', function($scope, $routeParams, $http) {
        $http.get('/api/league/' + $routeParams.param + '/events').success(function(data) {
            $scope.events = data
            $scope.name = $routeParams.param
        })
    })

    app.controller('videos', function($scope, $routeParams, $http, $document, usSpinnerService) {
        var league = $routeParams['league']
        var path = $routeParams['resourceUrl'].split('/')

        var basePath = '#/videos/' + league
        $scope.breadcrumb = []
        for (var i in path) {
            var elem = path[i]
            basePath += '/' + elem
            $scope.breadcrumb.push({
                'key': elem,
                'href': basePath
            })
        }
        $scope.league = league
        $scope.event = path[0]
        $scope.basePath = basePath
        $scope.backToLeagues = "#/league/" + league

        $http.get('/api/league/' + league + '/event/' + $scope.event).success(function(data) {
            $scope.data = data

            for (var i in path) {
                var elem = path[i]
                $scope.data = $scope.data[elem]
            }

	    $scope.isEmbed = false
            $scope.isList = false
            $scope.isDir = false
            $scope.listKeys = $scope.data['_keys']
            if ($scope.data['_type'] == 'list') {
                $scope.isList = true
            } else {
                $scope.isDir = true
            }
            usSpinnerService.stop('loader')
        })

	$scope.watchVideo = function(video) {
	    usSpinnerService.spin('loader')
	    $scope.title = video.title
	    $scope.html = video.embed
	    $scope.isEmbed = true
	    $document.scrollTopAnimated(0)
	    usSpinnerService.stop('loader')
	}
	$scope.clearVideo = function() {
	    $scope.isEmbed = false
	}
    })

    app.controller('vods', function($scope, $http) {
        $http.get('/api/leagues').success(function(data) {
            var leagues = $scope.leagues = []

            $scope.addLeague = function(name) {
                $http.get('/api/league/' + name).success(function(channel) {
                    channel['_name'] = name
                    leagues.push(channel);
                })
            };

            for (var i in data['leagues']) {
                $scope.addLeague(data['leagues'][i])
            }
        })
    })

    angular.bootstrap(document, ['FringeApp']);
    $("div.navbar-fixed-top").autoHidingNavbar();

    return app;
});
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
// import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { ApolloClient, ApolloProvider, createNetworkInterface } from 'react-apollo';
import { BrowserRouter as Router } from 'react-router-dom'

import App from './App';
import './index.css';

const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: 'http://localhost:9000/graphql'
  }),
  dataIdFromObject: o => o.id,
});

// const store = createStore(
//   combineReducers({
//     apollo: client.reducer()
//   }),
//   {},
//   compose(
//     applyMiddleware(client.middleware()),
//       // If you are using the devToolsExtension, you can add it here also
//       (typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined')
//         ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
//   )
// );

ReactDOM.render(
  <ApolloProvider client={client}>
    <Router>
      <App />
    </Router>
  </ApolloProvider>,
  document.getElementById('root')
);
<commit_msg>Comment out for presentation reasons<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
// import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { ApolloClient, ApolloProvider, createNetworkInterface } from 'react-apollo';
import { BrowserRouter as Router } from 'react-router-dom'

import App from './App';
import './index.css';

const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: 'http://localhost:9000/graphql'
  }),
  // dataIdFromObject: o => o.id,
});

// const store = createStore(
//   combineReducers({
//     apollo: client.reducer()
//   }),
//   {},
//   compose(
//     applyMiddleware(client.middleware()),
//       // If you are using the devToolsExtension, you can add it here also
//       (typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined')
//         ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
//   )
// );

ReactDOM.render(
  <ApolloProvider client={client}>
    <Router>
      <App />
    </Router>
  </ApolloProvider>,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>var NAMESPACE = 'company-send-contact';

var Hapi = require('hapi'),
    userValidate = require('npm-user-validate'),
    nodemailer = require('nodemailer'),
    crypto = require('crypto'),
    log = require('bole')(NAMESPACE),
    uuid = require('node-uuid'),
    metrics = require('newww-metrics')();

var transport, mailer;

module.exports = function (options) {
  return function (request, reply) {
    // var timer = { start: Date.now() };

    var showError = request.server.methods.errors.showError(reply);

    var opts = {
      user: request.auth.credentials,
      namespace: NAMESPACE
    };

    var from = options.emailFrom;
    var data = request.payload;

    var mail = {
      to: data.inquire === "support" ? "support <support@npmjs.com>" : "npm <npm@npmjs.com>",
      from: '"' + data.name + '" <' + data.email + '>',
      subject: data.subject,
      text: data.message
    };

    if (process.env.NODE_ENV === 'dev') {

      return reply(mail);

    } else {
      var mailSettings = options;

      if (!mailSettings.mailTransportModule ||
          !mailSettings.mailTransportSettings) {
        return showError(null, 500, 'Mail settings are missing!', opts);
      }

      var transport = require(mailSettings.mailTransportModule);
      var mailer = nodemailer.createTransport( transport(mailSettings.mailTransportSettings) );

      mailer.sendMail(mail, function (er, result) {
        if (er) {
          return showError(er, 500, "Unable to send verification email", opts);
        }

        opts.sent = true;
        return reply.view('company/contact', opts);
      });
    }
  }
}<commit_msg>changes from email to support@npmjs.com because lolz<commit_after>var NAMESPACE = 'company-send-contact';

var Hapi = require('hapi'),
    userValidate = require('npm-user-validate'),
    nodemailer = require('nodemailer'),
    crypto = require('crypto'),
    log = require('bole')(NAMESPACE),
    uuid = require('node-uuid'),
    metrics = require('newww-metrics')();

var transport, mailer;

module.exports = function (options) {
  return function (request, reply) {
    // var timer = { start: Date.now() };

    var showError = request.server.methods.errors.showError(reply);

    var opts = {
      user: request.auth.credentials,
      namespace: NAMESPACE
    };

    var from = options.emailFrom;
    var data = request.payload;

    var mail = {
      to: data.inquire === "support" ? "support <support@npmjs.com>" : "npm <npm@npmjs.com>",
      from: "Support Contact Form <support@npmjs.com>",
      subject: data.subject + " - FROM: " + '"' + data.name + '" <' + data.email + '>',
      text: data.message
    };

    if (process.env.NODE_ENV === 'dev') {

      return reply(mail);

    } else {
      var mailSettings = options;

      if (!mailSettings.mailTransportModule ||
          !mailSettings.mailTransportSettings) {
        return showError(null, 500, 'Mail settings are missing!', opts);
      }

      var transport = require(mailSettings.mailTransportModule);
      var mailer = nodemailer.createTransport( transport(mailSettings.mailTransportSettings) );

      mailer.sendMail(mail, function (er, result) {
        if (er) {
          return showError(er, 500, "Unable to send verification email", opts);
        }

        opts.sent = true;
        return reply.view('company/contact', opts);
      });
    }
  }
}<|endoftext|>


<commit_before>odoo.define('web_diagram.DiagramView', function (require) {
/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/
"use strict";

var core = require('web.core');
var data = require('web.data');
var form_common = require('web.form_common');
var Pager = require('web.Pager');
var View = require('web.View');
var ajax = require('web.ajax');

var _t = core._t;
var _lt = core._lt;
var QWeb = core.qweb;

var DiagramView = View.extend({
    display_name: _lt('Diagram'),
    icon: 'fa-code-fork',
    multi_record: false,
    searchable: false,

    init: function() {
        this._super.apply(this, arguments);
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
        if (this.ids && this.ids.length) {
            this.id = this.ids[this.dataset.index || 0];
        }
        this.fields = this.fields_view.fields;
        this.nodes = this.fields_view.arch.children[0];
        this.connectors = this.fields_view.arch.children[1];
        this.node = this.nodes.attrs.object;
        this.connector = this.connectors.attrs.object;
        this.labels = _.filter(this.fields_view.arch.children, function(label) {
            return label.tag === "label";
        });
    },

    willStart: function() {
        if (window.Raphael) {
            return $.when();
        }
        return $.when(
            ajax.loadJS('/web_diagram/static/lib/js/jquery.mousewheel.js'),
            ajax.loadJS('/web_diagram/static/lib/js/raphael.js')
        );
    },
    start: function() {
        var self = this;
        this.$el.html(QWeb.render("DiagramView", {'widget': this}));
        this.$el.addClass('o_diagram_view').addClass(this.fields_view.arch.attrs.class);

        _.each(this.labels,function(label){
            self.$('.o_diagram_header').append($('<span>').html(label.attrs.string));
        });

        var diagram_info;
        if(this.id) {
            diagram_info = this.get_diagram_info();
        }
        return $.when(this._super(), diagram_info);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible === '1')
                params.invisible_nodes.push(child.attrs.name);
            else {
                params.visible_nodes.push(child.attrs.name);
                params.node_fields.push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params.connectors_fields.push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params.connectors.push(conn.attrs.name);
        });
        return this.rpc(
            '/web_diagram/diagram/get_diagram_info',params).done(function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        // title is displayed in breadcrumbs
        this.set({ 'title' : record.id ? record.name : _t("New") });

        var id_record = record['id'];
        if (id_record) {
            this.id = id_record;
            this.get_diagram_info();
            this.do_push_state({id: id_record});
        } else {
            this.do_push_state({});
        }
    },

    do_load_state: function(state, warm) {
        if (state && state.id) {
            if (!this.dataset.get_id_index(state.id)) {
                this.dataset.ids.push(state.id);
            }
            this.dataset.select_id(state.id);
            if (warm) {
                this.do_show();
            }
        }
     },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$('.o_diagram').empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new data.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label: ''};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new data.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new form_common.FormViewDialog(self, {
            res_model: self.node,
            res_id: node_id,
            context: self.context || self.dataset.context,
            title: _t("Open: ") + title
        }).open();

        pop.on('write_completed', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).then(self.on_diagram_loaded);
        });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

        form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.$input.prop('disabled', true);
                field.$dropdown.unbind();
            });
        });
    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new form_common.FormViewDialog(self, {
            res_model: self.node,
            domain: self.domain,
            context: self.context || self.dataset.context,
            title: _t("Create:") + title,
            disable_multiple_selection: true,
            on_selected: function(element_ids) {
                self.dataset.read_index(_.keys(self.fields_view.fields)).then(self.on_diagram_loaded);
            }
        }).open();

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.set_value(self.id);
                field.dirty = true;
            });
        });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new form_common.FormViewDialog(self, {
            res_model: self.connector,
            res_id: parseInt(connector_id, 10),      //FIXME Isn't connector_id supposed to be an int ?
            context: self.context || self.dataset.context,
            title: _t("Open: ") + title
        }).open();
        pop.on('write_completed', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).then(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new form_common.FormViewDialog(self, {
            res_model: self.connector,
            domain: this.domain,
            context: this.context || this.dataset.context,
            title: _t("Create:") + title,
            disable_multiple_selection: true,
            on_selected: function(element_ids) {
                self.dataset.read_index(_.keys(self.fields_view.fields)).then(self.on_diagram_loaded);
            }
        }).open();

        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$el.parents('.modal').on('hidden.bs.modal', function (e){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;
        form_controller.on("load_record", self, function(){
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
        });
    },

    /**
     * Render the buttons according to the DiagramView.buttons template and add listeners on it.
     * Set this.$buttons with the produced jQuery element
     * @param {jQuery} [$node] a jQuery node where the rendered buttons should be inserted
     * $node may be undefined, in which case they are inserted into this.options.$buttons
     */
    render_buttons: function($node) {
        var self = this;

        this.$buttons = $(QWeb.render("DiagramView.buttons", {'widget': this}));
        this.$buttons.on('click', '.o_diagram_new_button', function() {
            self.add_node();
        });

        this.$buttons.appendTo($node);
    },

    /**
     * Instantiate and render the pager and add listeners on it.
     * Set this.pager
     * @param {jQuery} [$node] a jQuery node where the pager should be inserted
     * $node may be undefined, in which case the FormView inserts the pager into this.options.$pager
     */
    render_pager: function($node) {
        var self = this;

        this.pager = new Pager(this, this.dataset.ids.length, this.dataset.index + 1, 1);
        this.pager.appendTo($node || this.options.$pager);

        this.pager.on('pager_changed', this, function (new_state) {
            this.pager.disable();
            this.dataset.index = new_state.current_min - 1;
            $.when(this.reload()).then(function () {
                self.pager.enable();
            });
        });
    },

    update_pager: function() {
        if (this.pager) {
            this.pager.update_state({
                size: this.dataset.ids.length,
                current_min: this.dataset.index + 1,
            });
        }
    },

    reload: function() {
        return this.dataset.read_index(_.keys(this.fields_view.fields))
                .then(this.on_diagram_loaded)
                .then(this.proxy('update_pager'));
    },

    do_show: function() {
        this.do_push_state({});
        return $.when(this._super(), this.reload());
    }
});

core.view_registry.add('diagram', DiagramView);

return DiagramView;

});
<commit_msg>[FIX] web_diagram: wait for dialog's form view to be ready<commit_after>odoo.define('web_diagram.DiagramView', function (require) {
/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/
"use strict";

var core = require('web.core');
var data = require('web.data');
var form_common = require('web.form_common');
var Pager = require('web.Pager');
var View = require('web.View');
var ajax = require('web.ajax');

var _t = core._t;
var _lt = core._lt;
var QWeb = core.qweb;

var DiagramView = View.extend({
    display_name: _lt('Diagram'),
    icon: 'fa-code-fork',
    multi_record: false,
    searchable: false,

    init: function() {
        this._super.apply(this, arguments);
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
        if (this.ids && this.ids.length) {
            this.id = this.ids[this.dataset.index || 0];
        }
        this.fields = this.fields_view.fields;
        this.nodes = this.fields_view.arch.children[0];
        this.connectors = this.fields_view.arch.children[1];
        this.node = this.nodes.attrs.object;
        this.connector = this.connectors.attrs.object;
        this.labels = _.filter(this.fields_view.arch.children, function(label) {
            return label.tag === "label";
        });
    },

    willStart: function() {
        if (window.Raphael) {
            return $.when();
        }
        return $.when(
            ajax.loadJS('/web_diagram/static/lib/js/jquery.mousewheel.js'),
            ajax.loadJS('/web_diagram/static/lib/js/raphael.js')
        );
    },
    start: function() {
        var self = this;
        this.$el.html(QWeb.render("DiagramView", {'widget': this}));
        this.$el.addClass('o_diagram_view').addClass(this.fields_view.arch.attrs.class);

        _.each(this.labels,function(label){
            self.$('.o_diagram_header').append($('<span>').html(label.attrs.string));
        });

        var diagram_info;
        if(this.id) {
            diagram_info = this.get_diagram_info();
        }
        return $.when(this._super(), diagram_info);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible === '1')
                params.invisible_nodes.push(child.attrs.name);
            else {
                params.visible_nodes.push(child.attrs.name);
                params.node_fields.push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params.connectors_fields.push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params.connectors.push(conn.attrs.name);
        });
        return this.rpc(
            '/web_diagram/diagram/get_diagram_info',params).done(function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        // title is displayed in breadcrumbs
        this.set({ 'title' : record.id ? record.name : _t("New") });

        var id_record = record['id'];
        if (id_record) {
            this.id = id_record;
            this.get_diagram_info();
            this.do_push_state({id: id_record});
        } else {
            this.do_push_state({});
        }
    },

    do_load_state: function(state, warm) {
        if (state && state.id) {
            if (!this.dataset.get_id_index(state.id)) {
                this.dataset.ids.push(state.id);
            }
            this.dataset.select_id(state.id);
            if (warm) {
                this.do_show();
            }
        }
     },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$('.o_diagram').empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new data.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label: ''};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new data.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new form_common.FormViewDialog(self, {
            res_model: self.node,
            res_id: node_id,
            context: self.context || self.dataset.context,
            title: _t("Open: ") + title
        }).open();

        pop.on('write_completed', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).then(self.on_diagram_loaded);
        });

        pop.opened().then(function(){
            var form_controller = pop.view_form;
            var field = form_controller.fields[self.parent_field];
            if (field) {
                field.$input.prop('disabled', true);
                field.$dropdown.unbind();
            }
        });
    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new form_common.FormViewDialog(self, {
            res_model: self.node,
            domain: self.domain,
            context: self.context || self.dataset.context,
            title: _t("Create:") + title,
            disable_multiple_selection: true,
            on_selected: function(element_ids) {
                self.dataset.read_index(_.keys(self.fields_view.fields)).then(self.on_diagram_loaded);
            }
        }).open();

        pop.opened().then(function(){
            var form_controller = pop.view_form;
            var field = form_controller.fields[self.parent_field];
            if (field) {
                field.set_value(self.id);
                field.dirty = true;
            }
        });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new form_common.FormViewDialog(self, {
            res_model: self.connector,
            res_id: parseInt(connector_id, 10),      //FIXME Isn't connector_id supposed to be an int ?
            context: self.context || self.dataset.context,
            title: _t("Open: ") + title
        }).open();
        pop.on('write_completed', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).then(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new form_common.FormViewDialog(self, {
            res_model: self.connector,
            domain: this.domain,
            context: this.context || this.dataset.context,
            title: _t("Create:") + title,
            disable_multiple_selection: true,
            on_selected: function(element_ids) {
                self.dataset.read_index(_.keys(self.fields_view.fields)).then(self.on_diagram_loaded);
            }
        }).open();

        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$el.parents('.modal').on('hidden.bs.modal', function (e){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        pop.opened().then(function(){
            var form_controller = pop.view_form;
            var source_field = form_controller.fields[self.connectors.attrs.source];
            var destination_field = form_controller.fields[self.connectors.attrs.destination];
            source_field.set_value(node_source_id);
            source_field.dirty = true;
            destination_field.set_value(node_dest_id);
            destination_field.dirty = true;
        });
    },

    /**
     * Render the buttons according to the DiagramView.buttons template and add listeners on it.
     * Set this.$buttons with the produced jQuery element
     * @param {jQuery} [$node] a jQuery node where the rendered buttons should be inserted
     * $node may be undefined, in which case they are inserted into this.options.$buttons
     */
    render_buttons: function($node) {
        var self = this;

        this.$buttons = $(QWeb.render("DiagramView.buttons", {'widget': this}));
        this.$buttons.on('click', '.o_diagram_new_button', function() {
            self.add_node();
        });

        this.$buttons.appendTo($node);
    },

    /**
     * Instantiate and render the pager and add listeners on it.
     * Set this.pager
     * @param {jQuery} [$node] a jQuery node where the pager should be inserted
     * $node may be undefined, in which case the FormView inserts the pager into this.options.$pager
     */
    render_pager: function($node) {
        var self = this;

        this.pager = new Pager(this, this.dataset.ids.length, this.dataset.index + 1, 1);
        this.pager.appendTo($node || this.options.$pager);

        this.pager.on('pager_changed', this, function (new_state) {
            this.pager.disable();
            this.dataset.index = new_state.current_min - 1;
            $.when(this.reload()).then(function () {
                self.pager.enable();
            });
        });
    },

    update_pager: function() {
        if (this.pager) {
            this.pager.update_state({
                size: this.dataset.ids.length,
                current_min: this.dataset.index + 1,
            });
        }
    },

    reload: function() {
        return this.dataset.read_index(_.keys(this.fields_view.fields))
                .then(this.on_diagram_loaded)
                .then(this.proxy('update_pager'));
    },

    do_show: function() {
        this.do_push_state({});
        return $.when(this._super(), this.reload());
    }
});

core.view_registry.add('diagram', DiagramView);

return DiagramView;

});
<|endoftext|>


<commit_before>const _get = require('lodash/get');
const _isEqual = require('lodash/isEqual');
const _isNumber = require('lodash/isNumber');
const _merge = require('lodash/merge');
const _throttle = require('lodash/throttle');
const _uniqueId = require('lodash/uniqueId');
const keycode = require('keycode');
const PropTypes = require('prop-types');
const React = require('react');
const Velocity = require('velocity-animate');
const { StyleRoot } = require('radium');

import { withTheme } from './Theme';
const Button = require('../components/Button');
const MXFocusTrap = require('../components/MXFocusTrap');

const { themeShape } = require('../constants/App');

const StyleUtils = require('../utils/Style');
const { deprecatePrimaryColor } = require('../utils/Deprecation');

class Drawer extends React.Component {
  static propTypes = {
    'aria-describedby': PropTypes.string,
    'aria-labelledby': PropTypes.string,
    animateLeftDistance: PropTypes.number,
    beforeClose: PropTypes.func,
    breakPoints: PropTypes.shape({
      large: PropTypes.number,
      medium: PropTypes.number
    }),
    buttonPrimaryColor: PropTypes.string,
    closeOnScrimClick: PropTypes.bool,
    contentStyle: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object
    ]),
    duration: PropTypes.number,
    easing: PropTypes.array,
    focusOnLoad: PropTypes.bool,
    focusTrapProps: PropTypes.object,
    headerMenu: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.func
    ]),
    headerStyle: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object
    ]),
    maxWidth: PropTypes.number,
    navConfig: PropTypes.shape({
      label: PropTypes.string.isRequired,
      onNextClick: PropTypes.func.isRequired,
      onPreviousClick: PropTypes.func.isRequired
    }),
    onClose: PropTypes.func.isRequired,
    onKeyUp: PropTypes.func,
    onOpen: PropTypes.func,
    role: PropTypes.string,
    showCloseButton: PropTypes.bool,
    showScrim: PropTypes.bool,
    styles: PropTypes.object,
    theme: themeShape,
    title: PropTypes.string
  };

  static defaultProps = {
    beforeClose: () => {},
    closeOnScrimClick: true,
    duration: 500,
    easing: [0.28, 0.14, 0.34, 1.04],
    focusOnLoad: true,
    focusTrapProps: {},
    maxWidth: 960,
    onOpen: () => {},
    role: 'dialog',
    showCloseButton: true,
    showScrim: true,
    title: ''
  };

  constructor (props) {
    super(props);

    const theme = StyleUtils.mergeTheme(props.theme, props.buttonPrimaryColor);
    const breakPoints = props.breakPoints || theme.BreakPoints;

    this.state = { breakPoints, theme };
  }

  componentWillMount () {
    this._resizeThrottled = _throttle(this._resize, 100);
  }

  componentDidMount () {
    deprecatePrimaryColor(this.props, 'buttonPrimaryColor');
    this.open();
    window.addEventListener('resize', this._resizeThrottled);

    if (this.props.focusOnLoad) {
      // Close button might not be present depending on showCloseButton Prop
      if (this.props.showCloseButton && this._closeButton) {
        this._closeButton.focus();
      // Fall back to focusing the component if no close button
      } else if (this._component) {
        this._component.focus();
      }
    }
  }

  componentWillReceiveProps (newProps) {
    if (!_isEqual(newProps.breakPoints, this.props.breakPoints)) {
      this.setState({
        breakPoints: this.props.breakPoints
      });
    }
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this._resizeThrottled);
  }

  _getAnimationDistance = () => {
    if (_isNumber(this.props.animateLeftDistance)) {
      return this.props.animateLeftDistance + '%';
    }

    const windowWidth = window.innerWidth;

    if (windowWidth >= this.state.breakPoints.large) {
      //Resolution - maxWidth
      return windowWidth - this.props.maxWidth;
    } else if (windowWidth <= this.state.breakPoints.medium) {
      //All the way over to the left
      return 0;
    } else {
      //20% from the left
      const newLeft = windowWidth * 0.2;

      return Math.max(newLeft, windowWidth - this.props.maxWidth);
    }
  };

  _getExposedDrawerFunctions = () => {
    return { close: this.close };
  };

  /**
   * Figure out the height of the header. This can come from either:
   *
   * this.props.headerStyle.height
   * this.props.header.height
   *
   * If neither are set, default to 50px
   */
  _getHeaderHeight = () => {
    return _get(this.props, ['headerStyle', 'height'],
                _get(this.props,
                     ['styles', 'header', 'height'],
                     '50px'));
  };

  /**
   * Animate the Drawer closed and then call the onClose callback.
   *
   * @returns {Promise} that is resolved when the animation finishes
   */
  close = () => {
    this.props.beforeClose();
    return this._animateComponent({ left: '100%' })
      .then(() => {
        this.props.onClose();
      });
  };

  open = () => {
    return this._animateComponent({ left: this._getAnimationDistance() })
      .then(() => {
        this.props.onOpen();
      });
  };

  _animateComponent = (transition, extraOptions) => {
    const el = this._component;
    const options = Object.assign({
      duration: this.props.duration,
      easing: this.props.easing
    }, extraOptions);

    return Velocity(el, transition, options);
  };

  _handleKeyUp = e => {
    e.preventDefault();
    e.stopPropagation();

    if (keycode(e) === 'esc') this.close();
  };

  _resize = () => {
    this._animateComponent({ left: this._getAnimationDistance() }, { duration: 0 });
  };

  _renderNav = (navConfig, styles, theme) => {
    return (

        <Button
          icon='caret-left'
          onClick={navConfig.onPreviousClick}
          theme={theme}
          type='base'
        />

          {navConfig.label}

        <Button
          icon='caret-right'
          onClick={navConfig.onNextClick}
          theme={theme}
          type='base'
        />

    );
  };

  render () {
    const { theme } = this.state;
    const styles = this.styles(theme);
    const { headerMenu, focusTrapProps, navConfig } = this.props;
    const mergedFocusTrapProps = {
      focusTrapOptions: {
        clickOutsideDeactivates: true
      },
      paused: false,
      ...focusTrapProps
    };

    let menu = null;

    // If headerMenu is a function then we want to pass the Drawer's
    // exposed functions to the call.
    if (typeof headerMenu === 'function') {
      menu = headerMenu(this._getExposedDrawerFunctions());
    // If headerMenu is a normal node/element then use directly.
    } else if (headerMenu) {
      menu = headerMenu;
    // If no headerMenu and navConfig passed then use Drawer's
    // _renderNav function to generate the menu.
    } else if (navConfig) {
      menu = this._renderNav(navConfig, styles, theme);
    }
    const titleUniqueId = _uniqueId('mx-drawer-title-');

    return (


<commit_before>/*
 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
 For licensing, see LICENSE.html or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function( config )
{
  // Define changes to default configuration here. For example:
  //config.language = 'nb';
  // config.uiColor = '#AADC6E';

  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  config.allowedContent = true;

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });

  // Toolbar groups configuration.
  config.toolbar = [
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source'] },
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
    // { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
    // { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
    { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar' ] },
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
    '/',
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }
  ];

  config.toolbar_mini = [
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
    { name: 'styles', items: [ 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
    { name: 'insert', items: [ 'Image', 'Table', 'HorizontalRule', 'SpecialChar' ] }
  ];
};
<commit_msg>Set norwegian as default in config.js<commit_after>/*
 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
 For licensing, see LICENSE.html or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function( config )
{
  // Define changes to default configuration here. For example:
  config.language = 'nb';
  // config.uiColor = '#AADC6E';

  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  config.allowedContent = true;

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });

  // Toolbar groups configuration.
  config.toolbar = [
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source'] },
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
    // { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
    // { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
    { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar' ] },
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
    '/',
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }
  ];

  config.toolbar_mini = [
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
    { name: 'styles', items: [ 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
    { name: 'insert', items: [ 'Image', 'Table', 'HorizontalRule', 'SpecialChar' ] }
  ];
};
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin');
var env = process.env.WEBPACK_BUILD || 'development';

var CleanWebpackPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpackDevConfig = require('./webpack.base.config')('development');
var webpackProdConfig = require('./webpack.base.config')('production');

var paths = [
  '/',
  '/components/',
  '/components/blockui/',
  '/components/reduxblockui/',
  '/404.html',
];

var basepath = env === 'production' ? '/react-block-ui/' : '/';

var config = [{
  devtool: 'source-map',
  devServer: {
    contentBase: './build',
    stats: {
      chunks: false,
    },
  },
  entry: {
    main: './docs/lib/app.js',
  },
  node: {
    fs: 'empty',
  },
  output: {
    filename: 'bundle.js',
    publicPath: basepath,
    path: './build',
    libraryTarget: 'umd',
  },
  plugins: [
    new CleanWebpackPlugin(['build']),
    new CopyWebpackPlugin([{ from: './docs/static', to: 'assets' }]),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env),
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new StaticSiteGeneratorPlugin('main', paths, {basename: basepath}),
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin('/assets/style.css'),
  ],
  module: {
    loaders: [
      {
        test: /\.(json)$/,
        loaders: [
          'json-loader?cacheDirectory',
        ],
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: [
          'babel-loader?cacheDirectory',
        ],
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader'),
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.json'],
    alias: {
      'bootstrap-css': path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.css'),
      'react-block-ui': path.resolve('./src'),
    },
  },
}];

if (env === 'development') {
  config.push(webpackDevConfig);
  config.push(webpackProdConfig);
} else {
  config[0].plugins.push(new webpack.optimize.UglifyJsPlugin(
    {
      minimize: true,
      compress: {
        warnings: false,
      },
      mangle: true,
    }
  ));
}

module.exports = config;
<commit_msg>fix(docs): fix generating docs for gh-pages<commit_after>var path = require('path');
var webpack = require('webpack');
var StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin');
var env = process.env.NODE_ENV || 'development';

var CleanWebpackPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpackDevConfig = require('./webpack.base.config')('development');
var webpackProdConfig = require('./webpack.base.config')('production');

var paths = [
  '/',
  '/components/',
  '/components/blockui/',
  '/components/reduxblockui/',
  '/404.html',
];

var basepath = env === 'production' ? '/react-block-ui/' : '/';

var config = [{
  devtool: 'source-map',
  devServer: {
    contentBase: './build',
    stats: {
      chunks: false,
    },
  },
  entry: {
    main: './docs/lib/app.js',
  },
  node: {
    fs: 'empty',
  },
  output: {
    filename: 'bundle.js',
    publicPath: basepath,
    path: './build',
    libraryTarget: 'umd',
  },
  plugins: [
    new CleanWebpackPlugin(['build']),
    new CopyWebpackPlugin([{ from: './docs/static', to: 'assets' }]),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env),
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new StaticSiteGeneratorPlugin('main', paths, {basename: basepath}),
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin('/assets/style.css'),
  ],
  module: {
    loaders: [
      {
        test: /\.(json)$/,
        loaders: [
          'json-loader?cacheDirectory',
        ],
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: [
          'babel-loader?cacheDirectory',
        ],
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader'),
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.json'],
    alias: {
      'bootstrap-css': path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.css'),
      'react-block-ui': path.resolve('./src'),
    },
  },
}];

if (env === 'development') {
  config.push(webpackDevConfig);
  config.push(webpackProdConfig);
} else {
  config[0].plugins.push(new webpack.optimize.UglifyJsPlugin(
    {
      minimize: true,
      compress: {
        warnings: false,
      },
      mangle: true,
    }
  ));
}

module.exports = config;
<|endoftext|>