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

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/
var shell = require('shelljs'),
    child_process = require('child_process'),
    Q     = require('q'),
    path  = require('path'),
    fs    = require('fs'),
    check_reqs = require('./check_reqs'),
    ROOT    = path.join(__dirname, '..', '..');

// Returns a promise.
function exec(command, opt_cwd) {
    var d = Q.defer();
    console.log('Running: ' + command);
    child_process.exec(command, { cwd: opt_cwd }, function(err, stdout, stderr) {
        stdout && console.log(stdout);
        stderr && console.error(stderr);
        if (err) d.reject(err);
        else d.resolve(stdout);
    });
    return d.promise;
}

function setShellFatal(value, func) {
    var oldVal = shell.config.fatal;
    shell.config.fatal = value;
    func();
    shell.config.fatal = oldVal;
}

function getFrameworkDir(projectPath, shared) {
    return shared ? path.join(ROOT, 'framework') : path.join(projectPath, 'CordovaLib');
}

function copyJsAndLibrary(projectPath, shared, projectName) {
    var nestedCordovaLibPath = getFrameworkDir(projectPath, false);
    shell.cp('-f', path.join(ROOT, 'framework', 'assets', 'www', 'cordova.js'), path.join(projectPath, 'assets', 'www', 'cordova.js'));
    // Don't fail if there are no old jars.
    setShellFatal(false, function() {
        shell.ls(path.join(projectPath, 'libs', 'cordova-*.jar')).forEach(function(oldJar) {
            console.log("Deleting " + oldJar);
            shell.rm('-f', oldJar);
        });
        // Delete old library project if it existed.
        if (shared) {
            shell.rm('-rf', nestedCordovaLibPath);
        } else {
            // Delete only the src, since eclipse can't handle its .project file being deleted.
            shell.rm('-rf', path.join(nestedCordovaLibPath, 'src'));
        }
    });
    if (!shared) {
        shell.mkdir('-p', nestedCordovaLibPath);
        shell.cp('-f', path.join(ROOT, 'framework', 'AndroidManifest.xml'), nestedCordovaLibPath);
        shell.cp('-f', path.join(ROOT, 'framework', 'project.properties'), nestedCordovaLibPath);
        shell.cp('-r', path.join(ROOT, 'framework', 'src'), nestedCordovaLibPath);
        // Create an eclipse project file and set the name of it to something unique.
        // Without this, you can't import multiple CordovaLib projects into the same workspace.
        var eclipseProjectFilePath = path.join(nestedCordovaLibPath, '.project');
        if (!fs.existsSync(eclipseProjectFilePath)) {
            var data = '<?xml version="1.0" encoding="UTF-8"?><projectDescription><name>' + projectName + '-' + 'CordovaLib</name></projectDescription>';
            fs.writeFileSync(eclipseProjectFilePath, data, 'utf8');
        }
    }
}

function runAndroidUpdate(projectPath, target_api, shared) {
    var targetFrameworkDir = getFrameworkDir(projectPath, shared);
    return exec('android update project --subprojects --path "' + projectPath + '" --target ' + target_api + ' --library "' + path.relative(projectPath, targetFrameworkDir) + '"');
}

function copyAntRules(projectPath) {
    var srcDir = path.join(ROOT, 'bin', 'templates', 'project');
    shell.cp('-f', path.join(srcDir, 'custom_rules.xml'), projectPath);
}

function copyScripts(projectPath) {
    var srcScriptsDir = path.join(ROOT, 'bin', 'templates', 'cordova');
    var destScriptsDir = path.join(projectPath, 'cordova');
    // Delete old scripts directory if this is an update.
    shell.rm('-rf', destScriptsDir);
    // Copy in the new ones.
    shell.cp('-r', srcScriptsDir, projectPath);
    shell.cp('-r', path.join(ROOT, 'bin', 'node_modules'), destScriptsDir);
    shell.cp(path.join(ROOT, 'bin', 'check_reqs'), path.join(destScriptsDir, 'check_reqs'));
    shell.cp(path.join(ROOT, 'bin', 'lib', 'check_reqs.js'), path.join(projectPath, 'cordova', 'lib', 'check_reqs.js'));
    shell.cp(path.join(ROOT, 'bin', 'android_sdk_version'), path.join(destScriptsDir, 'android_sdk_version'));
    shell.cp(path.join(ROOT, 'bin', 'lib', 'android_sdk_version.js'), path.join(projectPath, 'cordova', 'lib', 'android_sdk_version.js'));
}

/**
 * $ create [options]
 *
 * Creates an android application with the given options.
 *
 * Options:
 *
 *   - `project_path` 	{String} Path to the new Cordova android project.
 *   - `package_name`{String} Package name, following reverse-domain style convention.
 *   - `project_name` 	{String} Project name.
 *   - 'project_template_dir' {String} Path to project template (override).
 *
 * Returns a promise.
 */

exports.createProject = function(project_path, package_name, project_name, project_template_dir, use_shared_project, use_cli_template) {
    var VERSION = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();

    // Set default values for path, package and name
    project_path = typeof project_path !== 'undefined' ? project_path : "CordovaExample";
    project_path = path.relative(process.cwd(), project_path);
    package_name = typeof package_name !== 'undefined' ? package_name : 'my.cordova.project';
    project_name = typeof project_name !== 'undefined' ? project_name : 'CordovaExample';
    project_template_dir = typeof project_template_dir !== 'undefined' ?
                           project_template_dir :
                           path.join(ROOT, 'bin', 'templates', 'project');

    var safe_activity_name = project_name.replace(/\W/g, '');
    var package_as_path = package_name.replace(/\./g, path.sep);
    var activity_dir    = path.join(project_path, 'src', package_as_path);
    var activity_path   = path.join(activity_dir, safe_activity_name + '.java');
    var target_api      = check_reqs.get_target();
    var manifest_path   = path.join(project_path, 'AndroidManifest.xml');

    // Check if project already exists
    if(fs.existsSync(project_path)) {
        return Q.reject('Project already exists! Delete and recreate');
    }

    if (!/[a-zA-Z0-9_]+\.[a-zA-Z0-9_](.[a-zA-Z0-9_])*/.test(package_name)) {
        return Q.reject('Package name must look like: com.company.Name');
    }

    // Check that requirements are met and proper targets are installed
    return check_reqs.run()
    .then(function() {
        // Log the given values for the project
        console.log('Creating Cordova project for the Android platform:');
        console.log('\tPath: ' + project_path);
        console.log('\tPackage: ' + package_name);
        console.log('\tName: ' + project_name);
        console.log('\tAndroid target: ' + target_api);

        console.log('Copying template files...');

        setShellFatal(true, function() {
            // copy project template
            shell.cp('-r', path.join(project_template_dir, 'assets'), project_path);
            shell.cp('-r', path.join(project_template_dir, 'res'), project_path);
            shell.cp('-r', path.join(ROOT, 'framework', 'res', 'xml'), path.join(project_path, 'res'));

            // Manually create directories that would be empty within the template (since git doesn't track directories).
            shell.mkdir(path.join(project_path, 'libs'));

            // Add in the proper eclipse project file.
            if (use_cli_template) {
                var note = 'To show `assets/www` or `res/xml/config.xml`, go to:\n' +
                           '    Project -> Properties -> Resource -> Resource Filters\n' +
                           'And delete the exclusion filter.\n';
                shell.cp(path.join(project_template_dir, 'eclipse-project-CLI'), path.join(project_path, '.project'));
                fs.writeFileSync(path.join(project_path, 'assets', '_where-is-www.txt'), note);
            } else {
                shell.cp(path.join(project_template_dir, 'eclipse-project'), path.join(project_path, '.project'));
            }

            // copy cordova.js, cordova.jar
            copyJsAndLibrary(project_path, use_shared_project, safe_activity_name);

            // interpolate the activity name and package
            shell.mkdir('-p', activity_dir);
            shell.cp('-f', path.join(project_template_dir, 'Activity.java'), activity_path);
            shell.sed('-i', /__ACTIVITY__/, safe_activity_name, activity_path);
            shell.sed('-i', /__NAME__/, project_name, path.join(project_path, 'res', 'values', 'strings.xml'));
            shell.sed('-i', /__NAME__/, project_name, path.join(project_path, '.project'));
            shell.sed('-i', /__ID__/, package_name, activity_path);

            shell.cp('-f', path.join(project_template_dir, 'AndroidManifest.xml'), manifest_path);
            shell.sed('-i', /__ACTIVITY__/, safe_activity_name, manifest_path);
            shell.sed('-i', /__PACKAGE__/, package_name, manifest_path);
            shell.sed('-i', /__APILEVEL__/, target_api.split('-')[1], manifest_path);
            copyScripts(project_path);
            copyAntRules(project_path);
        });
        // Link it to local android install.
        return runAndroidUpdate(project_path, target_api, use_shared_project);
    }).then(function() {
        console.log('Project successfully created.');
    });
}

// Attribute removed in Cordova 4.4 (CB-5447).
function removeDebuggableFromManifest(projectPath) {
    var manifestPath = path.join(projectPath, 'AndroidManifest.xml');
    shell.sed('-i', /\s*android:debuggable="true"/, '', manifestPath);
}

function extractProjectNameFromManifest(projectPath) {
    var manifestPath = path.join(projectPath, 'AndroidManifest.xml');
    var manifestData = fs.readFileSync(manifestPath, 'utf8');
    var m = /<activity[\s\S]*?android:name\s*=\s*"(.*?)"/i.exec(manifestData);
    if (!m) {
      throw new Error('Could not find activity name in ' + manifestPath);
    }
    return m[1];
}

// Returns a promise.
exports.updateProject = function(projectPath) {
    var version = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();
    // Check that requirements are met and proper targets are installed
    return check_reqs.run()
    .then(function() {
        var projectName = extractProjectNameFromManifest(projectPath);
        var target_api = check_reqs.get_target();
        copyJsAndLibrary(projectPath, false, projectName);
        copyScripts(projectPath);
        copyAntRules(projectPath);
        removeDebuggableFromManifest(projectPath);
        return runAndroidUpdate(projectPath, target_api, false)
        .then(function() {
            console.log('Android project is now at version ' + version);
            console.log('If you updated from a pre-3.2.0 version and use an IDE, we now require that you import the "CordovaLib" library project.');
        });
    });
};

<commit_msg>CB-4984 Don't create on CordovaActivity name<commit_after>#!/usr/bin/env node

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/
var shell = require('shelljs'),
    child_process = require('child_process'),
    Q     = require('q'),
    path  = require('path'),
    fs    = require('fs'),
    check_reqs = require('./check_reqs'),
    ROOT    = path.join(__dirname, '..', '..');

// Returns a promise.
function exec(command, opt_cwd) {
    var d = Q.defer();
    console.log('Running: ' + command);
    child_process.exec(command, { cwd: opt_cwd }, function(err, stdout, stderr) {
        stdout && console.log(stdout);
        stderr && console.error(stderr);
        if (err) d.reject(err);
        else d.resolve(stdout);
    });
    return d.promise;
}

function setShellFatal(value, func) {
    var oldVal = shell.config.fatal;
    shell.config.fatal = value;
    func();
    shell.config.fatal = oldVal;
}

function getFrameworkDir(projectPath, shared) {
    return shared ? path.join(ROOT, 'framework') : path.join(projectPath, 'CordovaLib');
}

function copyJsAndLibrary(projectPath, shared, projectName) {
    var nestedCordovaLibPath = getFrameworkDir(projectPath, false);
    shell.cp('-f', path.join(ROOT, 'framework', 'assets', 'www', 'cordova.js'), path.join(projectPath, 'assets', 'www', 'cordova.js'));
    // Don't fail if there are no old jars.
    setShellFatal(false, function() {
        shell.ls(path.join(projectPath, 'libs', 'cordova-*.jar')).forEach(function(oldJar) {
            console.log("Deleting " + oldJar);
            shell.rm('-f', oldJar);
        });
        // Delete old library project if it existed.
        if (shared) {
            shell.rm('-rf', nestedCordovaLibPath);
        } else {
            // Delete only the src, since eclipse can't handle its .project file being deleted.
            shell.rm('-rf', path.join(nestedCordovaLibPath, 'src'));
        }
    });
    if (!shared) {
        shell.mkdir('-p', nestedCordovaLibPath);
        shell.cp('-f', path.join(ROOT, 'framework', 'AndroidManifest.xml'), nestedCordovaLibPath);
        shell.cp('-f', path.join(ROOT, 'framework', 'project.properties'), nestedCordovaLibPath);
        shell.cp('-r', path.join(ROOT, 'framework', 'src'), nestedCordovaLibPath);
        // Create an eclipse project file and set the name of it to something unique.
        // Without this, you can't import multiple CordovaLib projects into the same workspace.
        var eclipseProjectFilePath = path.join(nestedCordovaLibPath, '.project');
        if (!fs.existsSync(eclipseProjectFilePath)) {
            var data = '<?xml version="1.0" encoding="UTF-8"?><projectDescription><name>' + projectName + '-' + 'CordovaLib</name></projectDescription>';
            fs.writeFileSync(eclipseProjectFilePath, data, 'utf8');
        }
    }
}

function runAndroidUpdate(projectPath, target_api, shared) {
    var targetFrameworkDir = getFrameworkDir(projectPath, shared);
    return exec('android update project --subprojects --path "' + projectPath + '" --target ' + target_api + ' --library "' + path.relative(projectPath, targetFrameworkDir) + '"');
}

function copyAntRules(projectPath) {
    var srcDir = path.join(ROOT, 'bin', 'templates', 'project');
    shell.cp('-f', path.join(srcDir, 'custom_rules.xml'), projectPath);
}

function copyScripts(projectPath) {
    var srcScriptsDir = path.join(ROOT, 'bin', 'templates', 'cordova');
    var destScriptsDir = path.join(projectPath, 'cordova');
    // Delete old scripts directory if this is an update.
    shell.rm('-rf', destScriptsDir);
    // Copy in the new ones.
    shell.cp('-r', srcScriptsDir, projectPath);
    shell.cp('-r', path.join(ROOT, 'bin', 'node_modules'), destScriptsDir);
    shell.cp(path.join(ROOT, 'bin', 'check_reqs'), path.join(destScriptsDir, 'check_reqs'));
    shell.cp(path.join(ROOT, 'bin', 'lib', 'check_reqs.js'), path.join(projectPath, 'cordova', 'lib', 'check_reqs.js'));
    shell.cp(path.join(ROOT, 'bin', 'android_sdk_version'), path.join(destScriptsDir, 'android_sdk_version'));
    shell.cp(path.join(ROOT, 'bin', 'lib', 'android_sdk_version.js'), path.join(projectPath, 'cordova', 'lib', 'android_sdk_version.js'));
}

/**
 * $ create [options]
 *
 * Creates an android application with the given options.
 *
 * Options:
 *
 *   - `project_path` 	{String} Path to the new Cordova android project.
 *   - `package_name`{String} Package name, following reverse-domain style convention.
 *   - `project_name` 	{String} Project name.
 *   - 'project_template_dir' {String} Path to project template (override).
 *
 * Returns a promise.
 */

exports.createProject = function(project_path, package_name, project_name, project_template_dir, use_shared_project, use_cli_template) {
    var VERSION = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();

    // Set default values for path, package and name
    project_path = typeof project_path !== 'undefined' ? project_path : "CordovaExample";
    project_path = path.relative(process.cwd(), project_path);
    package_name = typeof package_name !== 'undefined' ? package_name : 'my.cordova.project';
    project_name = typeof project_name !== 'undefined' ? project_name : 'CordovaExample';
    project_template_dir = typeof project_template_dir !== 'undefined' ?
                           project_template_dir :
                           path.join(ROOT, 'bin', 'templates', 'project');

    var safe_activity_name = project_name.replace(/\W/g, '');
    var package_as_path = package_name.replace(/\./g, path.sep);
    var activity_dir    = path.join(project_path, 'src', package_as_path);
    var activity_path   = path.join(activity_dir, safe_activity_name + '.java');
    var target_api      = check_reqs.get_target();
    var manifest_path   = path.join(project_path, 'AndroidManifest.xml');

    // Check if project already exists
    if(fs.existsSync(project_path)) {
        return Q.reject('Project already exists! Delete and recreate');
    }

    if (!/[a-zA-Z0-9_]+\.[a-zA-Z0-9_](.[a-zA-Z0-9_])*/.test(package_name)) {
        return Q.reject('Package name must look like: com.company.Name');
    }

    if (project_name === 'CordovaActivity') {
        return Q.reject('Project name cannot be CordovaActivity');
    }

    // Check that requirements are met and proper targets are installed
    return check_reqs.run()
    .then(function() {
        // Log the given values for the project
        console.log('Creating Cordova project for the Android platform:');
        console.log('\tPath: ' + project_path);
        console.log('\tPackage: ' + package_name);
        console.log('\tName: ' + project_name);
        console.log('\tAndroid target: ' + target_api);

        console.log('Copying template files...');

        setShellFatal(true, function() {
            // copy project template
            shell.cp('-r', path.join(project_template_dir, 'assets'), project_path);
            shell.cp('-r', path.join(project_template_dir, 'res'), project_path);
            shell.cp('-r', path.join(ROOT, 'framework', 'res', 'xml'), path.join(project_path, 'res'));

            // Manually create directories that would be empty within the template (since git doesn't track directories).
            shell.mkdir(path.join(project_path, 'libs'));

            // Add in the proper eclipse project file.
            if (use_cli_template) {
                var note = 'To show `assets/www` or `res/xml/config.xml`, go to:\n' +
                           '    Project -> Properties -> Resource -> Resource Filters\n' +
                           'And delete the exclusion filter.\n';
                shell.cp(path.join(project_template_dir, 'eclipse-project-CLI'), path.join(project_path, '.project'));
                fs.writeFileSync(path.join(project_path, 'assets', '_where-is-www.txt'), note);
            } else {
                shell.cp(path.join(project_template_dir, 'eclipse-project'), path.join(project_path, '.project'));
            }

            // copy cordova.js, cordova.jar
            copyJsAndLibrary(project_path, use_shared_project, safe_activity_name);

            // interpolate the activity name and package
            shell.mkdir('-p', activity_dir);
            shell.cp('-f', path.join(project_template_dir, 'Activity.java'), activity_path);
            shell.sed('-i', /__ACTIVITY__/, safe_activity_name, activity_path);
            shell.sed('-i', /__NAME__/, project_name, path.join(project_path, 'res', 'values', 'strings.xml'));
            shell.sed('-i', /__NAME__/, project_name, path.join(project_path, '.project'));
            shell.sed('-i', /__ID__/, package_name, activity_path);

            shell.cp('-f', path.join(project_template_dir, 'AndroidManifest.xml'), manifest_path);
            shell.sed('-i', /__ACTIVITY__/, safe_activity_name, manifest_path);
            shell.sed('-i', /__PACKAGE__/, package_name, manifest_path);
            shell.sed('-i', /__APILEVEL__/, target_api.split('-')[1], manifest_path);
            copyScripts(project_path);
            copyAntRules(project_path);
        });
        // Link it to local android install.
        return runAndroidUpdate(project_path, target_api, use_shared_project);
    }).then(function() {
        console.log('Project successfully created.');
    });
}

// Attribute removed in Cordova 4.4 (CB-5447).
function removeDebuggableFromManifest(projectPath) {
    var manifestPath = path.join(projectPath, 'AndroidManifest.xml');
    shell.sed('-i', /\s*android:debuggable="true"/, '', manifestPath);
}

function extractProjectNameFromManifest(projectPath) {
    var manifestPath = path.join(projectPath, 'AndroidManifest.xml');
    var manifestData = fs.readFileSync(manifestPath, 'utf8');
    var m = /<activity[\s\S]*?android:name\s*=\s*"(.*?)"/i.exec(manifestData);
    if (!m) {
      throw new Error('Could not find activity name in ' + manifestPath);
    }
    return m[1];
}

// Returns a promise.
exports.updateProject = function(projectPath) {
    var version = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();
    // Check that requirements are met and proper targets are installed
    return check_reqs.run()
    .then(function() {
        var projectName = extractProjectNameFromManifest(projectPath);
        var target_api = check_reqs.get_target();
        copyJsAndLibrary(projectPath, false, projectName);
        copyScripts(projectPath);
        copyAntRules(projectPath);
        removeDebuggableFromManifest(projectPath);
        return runAndroidUpdate(projectPath, target_api, false)
        .then(function() {
            console.log('Android project is now at version ' + version);
            console.log('If you updated from a pre-3.2.0 version and use an IDE, we now require that you import the "CordovaLib" library project.');
        });
    });
};

<|endoftext|>


<commit_before>import axios from 'axios';

const apiURL = process.env.NODE_ENV === 'development'
  ? 'http://localhost:3000'
  : window.location.origin;

const axiosInstance = axios.create({
  baseURL: apiURL,
});

export default axiosInstance;
<commit_msg>set exios<commit_after>import axios from 'axios';

// const apiURL = process.env.NODE_ENV === 'development'
//   ? 'http://localhost:3000'
//   : window.location.origin;

// const axiosInstance = axios.create({
//   baseURL: apiURL,
// });

export default axios;
<|endoftext|>


<commit_before>import React from 'react';
import Nav from './nav.js'
import { connect } from 'react-redux';
import styled from 'styled-components';
import { Link } from 'react-router';

const ProjectLink = styled(Link)`
  cursor: pointer;
  li;
  background: ghostwhite;
  padding: 5px;
  border-radius: 5px;
  display: inline-block;
  margin-bottom: 1em;
  margin-right: 1em;
  color: #8a6d3b;
  &:hover,
  &:focus,
  &:active {
    border: 1px solid #8a6d3b;
    color: #8a6d3b;
  }
`

const SubmissionComponent = ( {submission} ) => {
  return (

Submission projects

        {submission.projects &&

            {submission.projects.map((project) => {console.log(project); return
<ProjectLink to={'/'+project} key={project}>{project}</ProjectLink>
})}

        }

  )

}

const mapStateToProps = (state) => {
  return {
    'submission': state.submission
  }
}

const mapDispatchToProps = (dispatch) => {
  return {};
}

let Submission = connect(mapStateToProps, mapDispatchToProps)(SubmissionComponent);
export default Submission;
<commit_msg>chore(style): change project list to inline<commit_after>import React from 'react';
import Nav from './nav.js'
import { connect } from 'react-redux';
import styled from 'styled-components';
import { Link } from 'react-router';

const ProjectLink = styled(Link)`
  cursor: pointer;
  li;
  background: ghostwhite;
  padding: 5px;
  border-radius: 5px;
  display: inline-block;
  margin-bottom: 1em;
  margin-right: 1em;
  color: #8a6d3b;
  &:hover,
  &:focus,
  &:active {
    border: 1px solid #8a6d3b;
    color: #8a6d3b;
  }
`

const SubmissionComponent = ( {submission} ) => {
  return (

Submission projects

        {submission.projects &&

           {submission.projects.map((project) => {console.log(project); return <ProjectLink to={'/'+project} key={project}>{project}</ProjectLink>})}

        }

  )

}

const mapStateToProps = (state) => {
  return {
    'submission': state.submission
  }
}

const mapDispatchToProps = (dispatch) => {
  return {};
}

let Submission = connect(mapStateToProps, mapDispatchToProps)(SubmissionComponent);
export default Submission;
<|endoftext|>


<commit_before>gimport React, { PropTypes } from 'react';
import { View, StyleSheet, Platform, Image } from 'react-native';
import fonts from '../config/fonts';
import colors from '../config/colors';
import Text from '../text/Text';
import Divider from '../divider/Divider';
import normalize from '../helpers/normalizeText';

const Card = props => {
  const {
    children,
    flexDirection,
    containerStyle,
    wrapperStyle,
    imageWrapperStyle,
    title,
    titleStyle,
    featuredTitle,
    featuredTitleStyle,
    featuredSubtitle,
    featuredSubtitleStyle,
    dividerStyle,
    image,
    imageStyle,
    fontFamily,
    ...attributes,
  } = props;

  return (
    <View style={[
      styles.container,
      image && {padding: 0},
      containerStyle && containerStyle]}
      {...attributes}
    >
      <View style={[styles.wrapper, wrapperStyle && wrapperStyle, flexDirection && {flexDirection}]}>
        {
          title && (
            <View>
              <Text style={[
                styles.cardTitle,
                image && styles.imageCardTitle,
                titleStyle && titleStyle,
                fontFamily && {fontFamily}
              ]}>{title}</Text>
              { !image && <Divider style={[styles.divider, dividerStyle && dividerStyle]} />}
            </View>
          )
        }
        {
          image && (
            <View style={imageWrapperStyle && imageWrapperStyle}>
              <Image
                resizeMode='cover'
                style={[{width: null, height: 150}, imageStyle && imageStyle]}
                source={image}>
                <View style={styles.overlayContainer}>
                  {featuredTitle && <Text style={[styles.featuredTitle, featuredTitleStyle && featuredTitleStyle]}>{featuredTitle}</Text>}
                  {featuredSubtitle && <Text style={[styles.featuredSubtitle, featuredSubtitleStyle && featuredSubtitleStyle]}>{featuredSubtitle}</Text>}
                </View>
              </Image>
              <View
                style={[{padding: 10}, wrapperStyle && wrapperStyle]}>
                {children}
              </View>
            </View>
          )
        }
        { !image && children}
      </View>
    </View>
  );
};

Card.propTypes = {
  children: PropTypes.any,
  flexDirection: PropTypes.string,
  containerStyle: View.propTypes.style,
  wrapperStyle: View.propTypes.style,
  title: PropTypes.string,
  titleStyle: Text.propTypes.style,
  featuredTitle: PropTypes.string,
  featuredTitleStyle: Text.propTypes.style,
  featuredSubtitle: PropTypes.string,
  featuredSubtitleStyle: Text.propTypes.style,
  dividerStyle: View.propTypes.style,
  image: Image.propTypes.source,
  imageStyle: View.propTypes.style,
  imageWrapperStyle: View.propTypes.style,
  fontFamily: PropTypes.string,
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    borderColor: colors.grey5,
    borderWidth: 1,
    padding: 15,
    margin: 15,
    marginBottom: 0,
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .2)',
        shadowOffset: {height: 0, width: 0},
        shadowOpacity: 1,
        shadowRadius: 1
      },
      android: {
        elevation: 1
      }
    })
  },
  featuredTitle: {
    fontSize: normalize(18),
    marginBottom: 8,
    color: 'white',
    ...Platform.select({
      ios: {
        fontWeight: '800'
      },
      android: {
        ...fonts.android.black
      }
    })
  },
  featuredSubtitle: {
    fontSize: normalize(13),
    marginBottom: 8,
    color: 'white',
    ...Platform.select({
      ios: {
        fontWeight: '400'
      },
      android: {
        ...fonts.android.black
      }
    })
  },
  wrapper: {
    backgroundColor: 'transparent'
  },
  divider: {
    marginBottom: 15
  },
  cardTitle: {
    fontSize: normalize(14),
    ...Platform.select({
      ios: {
        fontWeight: 'bold'
      },
      android: {
        ...fonts.android.black
      }
    }),
    textAlign: 'center',
    marginBottom: 15,
    color: colors.grey1
  },
  imageCardTitle: {
    marginTop: 15,
  },
  overlayContainer: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
    alignSelf: 'stretch',
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
});

export default Card;
<commit_msg>removed accidentally typed character<commit_after>import React, { PropTypes } from 'react';
import { View, StyleSheet, Platform, Image } from 'react-native';
import fonts from '../config/fonts';
import colors from '../config/colors';
import Text from '../text/Text';
import Divider from '../divider/Divider';
import normalize from '../helpers/normalizeText';

const Card = props => {
  const {
    children,
    flexDirection,
    containerStyle,
    wrapperStyle,
    imageWrapperStyle,
    title,
    titleStyle,
    featuredTitle,
    featuredTitleStyle,
    featuredSubtitle,
    featuredSubtitleStyle,
    dividerStyle,
    image,
    imageStyle,
    fontFamily,
    ...attributes,
  } = props;

  return (
    <View style={[
      styles.container,
      image && {padding: 0},
      containerStyle && containerStyle]}
      {...attributes}
    >
      <View style={[styles.wrapper, wrapperStyle && wrapperStyle, flexDirection && {flexDirection}]}>
        {
          title && (
            <View>
              <Text style={[
                styles.cardTitle,
                image && styles.imageCardTitle,
                titleStyle && titleStyle,
                fontFamily && {fontFamily}
              ]}>{title}</Text>
              { !image && <Divider style={[styles.divider, dividerStyle && dividerStyle]} />}
            </View>
          )
        }
        {
          image && (
            <View style={imageWrapperStyle && imageWrapperStyle}>
              <Image
                resizeMode='cover'
                style={[{width: null, height: 150}, imageStyle && imageStyle]}
                source={image}>
                <View style={styles.overlayContainer}>
                  {featuredTitle && <Text style={[styles.featuredTitle, featuredTitleStyle && featuredTitleStyle]}>{featuredTitle}</Text>}
                  {featuredSubtitle && <Text style={[styles.featuredSubtitle, featuredSubtitleStyle && featuredSubtitleStyle]}>{featuredSubtitle}</Text>}
                </View>
              </Image>
              <View
                style={[{padding: 10}, wrapperStyle && wrapperStyle]}>
                {children}
              </View>
            </View>
          )
        }
        { !image && children}
      </View>
    </View>
  );
};

Card.propTypes = {
  children: PropTypes.any,
  flexDirection: PropTypes.string,
  containerStyle: View.propTypes.style,
  wrapperStyle: View.propTypes.style,
  title: PropTypes.string,
  titleStyle: Text.propTypes.style,
  featuredTitle: PropTypes.string,
  featuredTitleStyle: Text.propTypes.style,
  featuredSubtitle: PropTypes.string,
  featuredSubtitleStyle: Text.propTypes.style,
  dividerStyle: View.propTypes.style,
  image: Image.propTypes.source,
  imageStyle: View.propTypes.style,
  imageWrapperStyle: View.propTypes.style,
  fontFamily: PropTypes.string,
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    borderColor: colors.grey5,
    borderWidth: 1,
    padding: 15,
    margin: 15,
    marginBottom: 0,
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .2)',
        shadowOffset: {height: 0, width: 0},
        shadowOpacity: 1,
        shadowRadius: 1
      },
      android: {
        elevation: 1
      }
    })
  },
  featuredTitle: {
    fontSize: normalize(18),
    marginBottom: 8,
    color: 'white',
    ...Platform.select({
      ios: {
        fontWeight: '800'
      },
      android: {
        ...fonts.android.black
      }
    })
  },
  featuredSubtitle: {
    fontSize: normalize(13),
    marginBottom: 8,
    color: 'white',
    ...Platform.select({
      ios: {
        fontWeight: '400'
      },
      android: {
        ...fonts.android.black
      }
    })
  },
  wrapper: {
    backgroundColor: 'transparent'
  },
  divider: {
    marginBottom: 15
  },
  cardTitle: {
    fontSize: normalize(14),
    ...Platform.select({
      ios: {
        fontWeight: 'bold'
      },
      android: {
        ...fonts.android.black
      }
    }),
    textAlign: 'center',
    marginBottom: 15,
    color: colors.grey1
  },
  imageCardTitle: {
    marginTop: 15,
  },
  overlayContainer: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
    alignSelf: 'stretch',
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
});

export default Card;
<|endoftext|>


<commit_before>const Discord = require('discord.js')
const isStr = str => str && typeof str === 'string'

// objectEmbed.message => embed.description

module.exports = (embeds, article) => {
  const richEmbeds = []
  for (var e = 0; e < embeds.length; ++e) {
    const richEmbed = new Discord.RichEmbed()
    const objectEmbed = embeds[e]

    if (isStr(objectEmbed.title)) {
      const t = article.convertKeywords(objectEmbed.title)
      richEmbed.setTitle(t.length > 256 ? t.slice(0, 250) + '...' : t)
    }

    if (isStr(objectEmbed.description)) richEmbed.setDescription(article.convertKeywords(objectEmbed.description))
    if (isStr(objectEmbed.url)) richEmbed.setURL(article.convertKeywords(objectEmbed.url))

    if (objectEmbed.color !== null && objectEmbed.color !== undefined && !isNaN(objectEmbed.color) && objectEmbed.color <= 16777215 && objectEmbed.color >= 0) richEmbed.setColor(parseInt(objectEmbed.color, 10))
    else if (isStr(objectEmbed.color) && objectEmbed.color.startsWith('#') && objectEmbed.color.length === 7) richEmbed.setColor(objectEmbed.color)

    if (isStr(objectEmbed['footer_text'])) richEmbed.setFooter(article.convertKeywords(objectEmbed['footer_text']), isStr(objectEmbed['footer_icon_url']) ? article.convertKeywords(objectEmbed['footer_icon_url']) : undefined)
    if (isStr(objectEmbed['footerText'])) richEmbed.setFooter(article.convertKeywords(objectEmbed['footerText']), isStr(objectEmbed['footerIconUrl']) ? article.convertKeywords(objectEmbed['footerIconUrl']) : undefined)

    if (isStr(objectEmbed['author_name'])) richEmbed.setAuthor(article.convertKeywords(objectEmbed['author_name']), isStr(objectEmbed['author_icon_url']) ? article.convertKeywords(objectEmbed['author_icon_url']) : undefined, isStr(objectEmbed['author_url']) ? article.convertKeywords(objectEmbed['author_url']) : undefined)
    if (isStr(objectEmbed['authorName'])) richEmbed.setAuthor(article.convertKeywords(objectEmbed['authorName']), isStr(objectEmbed['authorIconUrl']) ? article.convertKeywords(objectEmbed['authorIconUrl']) : undefined, isStr(objectEmbed['authorUrl']) ? article.convertKeywords(objectEmbed['authorUrl']) : undefined)

    if (isStr(objectEmbed['thumbnail_url'])) richEmbed.setThumbnail(article.convertKeywords(objectEmbed['thumbnail_url']))
    if (isStr(objectEmbed['thumbnailUrl'])) richEmbed.setThumbnail(article.convertKeywords(objectEmbed['thumbnailUrl']))

    if (isStr(objectEmbed['image_url'])) richEmbed.setImage(article.convertKeywords(objectEmbed['image_url']))
    if (isStr(objectEmbed['imageUrl'])) richEmbed.setImage(article.convertKeywords(objectEmbed['imageUrl']))

    if (isStr(objectEmbed.timestamp)) {
      const setting = objectEmbed.timestamp
      richEmbed.setTimestamp(setting === 'article' ? new Date(article.rawDate) : setting === 'now' ? new Date() : new Date(setting)) // No need to check for invalid date since discord.js does it
    }
    console.log(richEmbed)

    const fields = objectEmbed.fields
    if (Array.isArray(fields)) {
      for (var x = 0; x < fields.length; ++x) {
        const field = fields[x]
        const inline = field.inline === true

        let title = article.convertKeywords(field.title)
        title = title.length > 256 ? title.slice(0, 250) + '...' : title

        let value = article.convertKeywords(field.value ? field.value : '')
        value = value.length > 1024 ? value.slice(0, 1020) + '...' : value.length > 0 ? value : '\u200b'

        if (typeof title === 'string' && !title) richEmbed.addBlankField(inline)
        else if (richEmbed.fields.length < 10) richEmbed.addField(title, value, inline)
      }
    }
    richEmbeds.push(richEmbed)
  }

  return richEmbeds
}
<commit_msg>Remove console log<commit_after>const Discord = require('discord.js')
const isStr = str => str && typeof str === 'string'

// objectEmbed.message => embed.description

module.exports = (embeds, article) => {
  const richEmbeds = []
  for (var e = 0; e < embeds.length; ++e) {
    const richEmbed = new Discord.RichEmbed()
    const objectEmbed = embeds[e]

    if (isStr(objectEmbed.title)) {
      const t = article.convertKeywords(objectEmbed.title)
      richEmbed.setTitle(t.length > 256 ? t.slice(0, 250) + '...' : t)
    }

    if (isStr(objectEmbed.description)) richEmbed.setDescription(article.convertKeywords(objectEmbed.description))
    if (isStr(objectEmbed.url)) richEmbed.setURL(article.convertKeywords(objectEmbed.url))

    if (objectEmbed.color !== null && objectEmbed.color !== undefined && !isNaN(objectEmbed.color) && objectEmbed.color <= 16777215 && objectEmbed.color >= 0) richEmbed.setColor(parseInt(objectEmbed.color, 10))
    else if (isStr(objectEmbed.color) && objectEmbed.color.startsWith('#') && objectEmbed.color.length === 7) richEmbed.setColor(objectEmbed.color)

    if (isStr(objectEmbed['footer_text'])) richEmbed.setFooter(article.convertKeywords(objectEmbed['footer_text']), isStr(objectEmbed['footer_icon_url']) ? article.convertKeywords(objectEmbed['footer_icon_url']) : undefined)
    if (isStr(objectEmbed['footerText'])) richEmbed.setFooter(article.convertKeywords(objectEmbed['footerText']), isStr(objectEmbed['footerIconUrl']) ? article.convertKeywords(objectEmbed['footerIconUrl']) : undefined)

    if (isStr(objectEmbed['author_name'])) richEmbed.setAuthor(article.convertKeywords(objectEmbed['author_name']), isStr(objectEmbed['author_icon_url']) ? article.convertKeywords(objectEmbed['author_icon_url']) : undefined, isStr(objectEmbed['author_url']) ? article.convertKeywords(objectEmbed['author_url']) : undefined)
    if (isStr(objectEmbed['authorName'])) richEmbed.setAuthor(article.convertKeywords(objectEmbed['authorName']), isStr(objectEmbed['authorIconUrl']) ? article.convertKeywords(objectEmbed['authorIconUrl']) : undefined, isStr(objectEmbed['authorUrl']) ? article.convertKeywords(objectEmbed['authorUrl']) : undefined)

    if (isStr(objectEmbed['thumbnail_url'])) richEmbed.setThumbnail(article.convertKeywords(objectEmbed['thumbnail_url']))
    if (isStr(objectEmbed['thumbnailUrl'])) richEmbed.setThumbnail(article.convertKeywords(objectEmbed['thumbnailUrl']))

    if (isStr(objectEmbed['image_url'])) richEmbed.setImage(article.convertKeywords(objectEmbed['image_url']))
    if (isStr(objectEmbed['imageUrl'])) richEmbed.setImage(article.convertKeywords(objectEmbed['imageUrl']))

    if (isStr(objectEmbed.timestamp)) {
      const setting = objectEmbed.timestamp
      richEmbed.setTimestamp(setting === 'article' ? new Date(article.rawDate) : setting === 'now' ? new Date() : new Date(setting)) // No need to check for invalid date since discord.js does it
    }

    const fields = objectEmbed.fields
    if (Array.isArray(fields)) {
      for (var x = 0; x < fields.length; ++x) {
        const field = fields[x]
        const inline = field.inline === true

        let title = article.convertKeywords(field.title)
        title = title.length > 256 ? title.slice(0, 250) + '...' : title

        let value = article.convertKeywords(field.value ? field.value : '')
        value = value.length > 1024 ? value.slice(0, 1020) + '...' : value.length > 0 ? value : '\u200b'

        if (typeof title === 'string' && !title) richEmbed.addBlankField(inline)
        else if (richEmbed.fields.length < 10) richEmbed.addField(title, value, inline)
      }
    }
    richEmbeds.push(richEmbed)
  }

  return richEmbeds
}
<|endoftext|>


<commit_before>/**
 * Created by rinesnow on 16/3/31.
 */
//未登录
   var OAuth = require('wechat-oauth');
   var client = new OAuth('wx75d11b4f981b1ded', '7a915c525f39451f3af19407012459ad');
// function getOpenid(req,res){
//     var query = require('url').parse(req.url,true).query;
//     client.getAccessToken(code, function (err, result) {
//       var accessToken = result.data.access_token;
//       var openid = result.data.openid;
//       console.log(accessToken);
//       console.log(openid);
//             console.log(err);

//       return openid;
//     });
// }

function ifAuthorized(req,res,next){

    // var url = client.getAuthorizeURL('www.coderwitkey.com', 'STATE', 'snsapi_userinfo');

    var query = require('url').parse(req.url,true).query;
          console.log(query);

    var code = query.code;
          console.log(code);

    client.getUserByCode(code,function (err, result) {
      // var accessToken = result.data.access_token;
      var openid = result.openid;
      console.log(result);
      // console.log(accessToken);

      console.log("这是openid"+openid);

      // client.getUser(openid, function (err, result) {
      //     var userInfo = result;
      //     console.log(userInfo);
      //  });

       User.findOne({openid:openid},function(err,user){
           if(err){
               console.log(err);
           }
            if(user){//有这个user 那么直接跳转
                return res.redirect('/');
            }
            // //对密码进行md5加密
            // var md5 = crypto.createHash('md5'),
            //     md5newopenid = md5.update(openid).digest('hex');
            //新建user对象用于保存数据
            var newUser = new User({
                openid:openid//openid 作为key存入，以后再用用户信息就用openid调。
            });

            newUser.save(function(err,doc){
                if(err){
                    console.log("保存用户信息失败！"+err);
                }
                console.log('保存用户信息成功!');//怎么实现弹出框!!!!??????
                return res.redirect('/');
            });
        });

    });

    // if(!req.session.user){
    //     console.log('抱歉,您还没有登录!');
    //     return res.redirect('/login');//返回登录页面
    // }
    next();
}

function noReLogin(req,res,next){

    if(req.session.user){
        console.log('您已登录,不能再登录或注册!');
        return res.redirect('/');//返回首页
    }
    next();
}
exports.ifAuthorized = ifAuthorized;
exports.noReLogin= noReLogin;
// exports.getOpenid= getOpenid;<commit_msg>yonghu id<commit_after>/**
 * Created by rinesnow on 16/3/31.
 */
//未登录
   var OAuth = require('wechat-oauth');
   var client = new OAuth('wx75d11b4f981b1ded', '7a915c525f39451f3af19407012459ad');
// function getOpenid(req,res){
//     var query = require('url').parse(req.url,true).query;
//     client.getAccessToken(code, function (err, result) {
//       var accessToken = result.data.access_token;
//       var openid = result.data.openid;
//       console.log(accessToken);
//       console.log(openid);
//             console.log(err);

//       return openid;
//     });
// }

function ifAuthorized(req,res,next){

    // var url = client.getAuthorizeURL('www.coderwitkey.com', 'STATE', 'snsapi_userinfo');

    var query = require('url').parse(req.url,true).query;
          console.log(query);

    var code = query.code;
          console.log(code);

    client.getUserByCode(code,function (err, result) {
      // var accessToken = result.data.access_token;
      console.log(result);
      var openid = result.openid;

      // console.log(accessToken);

      console.log("这是openid"+openid);

      // client.getUser(openid, function (err, result) {
      //     var userInfo = result;
      //     console.log(userInfo);
      //  });

       User.findOne({openid:openid},function(err,user){
           if(err){
               console.log(err);
           }
            if(user){//有这个user 那么直接跳转
                return res.redirect('/');
            }
            // //对密码进行md5加密
            // var md5 = crypto.createHash('md5'),
            //     md5newopenid = md5.update(openid).digest('hex');
            //新建user对象用于保存数据
            var newUser = new User({
                openid:openid//openid 作为key存入，以后再用用户信息就用openid调。
            });

            newUser.save(function(err,doc){
                if(err){
                    console.log("保存用户信息失败！"+err);
                }
                console.log('保存用户信息成功!');//怎么实现弹出框!!!!??????
                return res.redirect('/');
            });
        });

    });

    // if(!req.session.user){
    //     console.log('抱歉,您还没有登录!');
    //     return res.redirect('/login');//返回登录页面
    // }
    next();
}

function noReLogin(req,res,next){

    if(req.session.user){
        console.log('您已登录,不能再登录或注册!');
        return res.redirect('/');//返回首页
    }
    next();
}
exports.ifAuthorized = ifAuthorized;
exports.noReLogin= noReLogin;
// exports.getOpenid= getOpenid;<|endoftext|>


<commit_before>// @flow

import { Project, ProjectSettings, ProjectUtils } from 'xdl';

import bunyan from 'bunyan';
import chalk from 'chalk';

function installExitHooks(projectDir) {
  if (process.platform === 'win32') {
    require('readline')
      .createInterface({
        input: process.stdin,
        output: process.stdout,
      })
      .on('SIGINT', () => {
        process.emit('SIGINT');
      });
  }

  process.on('SIGINT', () => {
    console.log(chalk.blue('\nStopping packager...'));
    cleanUpPackager(projectDir).then(() => {
      console.log(chalk.green('Packager stopped.'));
      process.exit();
    });
  });
}

async function cleanUpPackager(projectDir) {
  const result = await Promise.race([
    Project.stopAsync(projectDir),
    new Promise((resolve, reject) => setTimeout(resolve, 1000, 'stopFailed')),
  ]);

  if (result === 'stopFailed') {
    // find RN packager pid, attempt to kill manually
    try {
      const { packagerPid } = await ProjectSettings.readPackagerInfoAsync(projectDir);
      process.kill(packagerPid);
    } catch (e) {
      process.exit(1);
    }
  }
}

function run(onReady: () => ?any, options: Object = {}) {
  // TODO check to see if packager is running already and run onready if it is

  let packagerReady = false;
  let logBuffer = '';
  const projectDir = process.cwd();
  ProjectUtils.attachLoggerStream(projectDir, {
    stream: {
      write: chunk => {
        // don't show the initial packager setup, so that we can display a nice getting started message
        // note: it's possible for the RN packager to log its setup before the express server is done
        // this is a potential race condition but it'll work for now
        if (chunk.msg.indexOf('Loading dependency graph, done.') >= 0) {
          packagerReady = true;
          onReady();
          return;
        }

        if (packagerReady) {
          const message = `${new Date().toLocaleString()}: ${chunk.msg}`;
          if (chunk.level <= bunyan.INFO) {
            console.log(message);
          } else if (chunk.level === bunyan.WARN) {
            console.log(chalk.yellow(message));
          } else {
            console.log(chalk.red(message));
          }
        } else {
          if (chunk.level >= bunyan.ERROR) {
            console.log(chalk.yellow('***ERROR STARTING PACKAGER***'));
            console.log(logBuffer);
            console.log(chalk.red(chunk.msg));
            logBuffer = '';
          } else {
            logBuffer += chunk.msg + '\n';
          }
        }
      },
    },
    type: 'raw',
  });

  installExitHooks(projectDir);
  console.log(chalk.blue('Starting packager...'));

  Project.startAsync(projectDir, options).then(
    () => {},
    reason => {
      console.log(chalk.red(`Error starting packager: ${reason.stack}`));
      process.exit(1);
    }
  );
}

export default { run };
<commit_msg>Clean up timestamp output, remove manifest logging, and prep for having syntax that's nice enough to clear the console.<commit_after>// @flow

import { Project, ProjectSettings, ProjectUtils } from 'xdl';

import bunyan from 'bunyan';
import chalk from 'chalk';

// TODO get babel output that's nice enough to let it take over the console
function clearConsole() {
  process.stdout.write(
    process.platform === 'win32' ? '\x1Bc' : '\x1B[2J\x1B[3J\x1B[H'
  );
}

function installExitHooks(projectDir) {
  if (process.platform === 'win32') {
    require('readline')
      .createInterface({
        input: process.stdin,
        output: process.stdout,
      })
      .on('SIGINT', () => {
        process.emit('SIGINT');
      });
  }

  process.on('SIGINT', () => {
    console.log(chalk.blue('\nStopping packager...'));
    cleanUpPackager(projectDir).then(() => {
      console.log(chalk.green('Packager stopped.'));
      process.exit();
    });
  });
}

async function cleanUpPackager(projectDir) {
  const result = await Promise.race([
    Project.stopAsync(projectDir),
    new Promise((resolve, reject) => setTimeout(resolve, 1000, 'stopFailed')),
  ]);

  if (result === 'stopFailed') {
    // find RN packager pid, attempt to kill manually
    try {
      const { packagerPid } = await ProjectSettings.readPackagerInfoAsync(projectDir);
      process.kill(packagerPid);
    } catch (e) {
      process.exit(1);
    }
  }
}

function run(onReady: () => ?any, options: Object = {}) {
  let packagerReady = false;
  let needsClear = false;
  let logBuffer = '';
  const projectDir = process.cwd();
  ProjectUtils.attachLoggerStream(projectDir, {
    stream: {
      write: chunk => {
        // don't show the initial packager setup, so that we can display a nice getting started message
        // note: it's possible for the RN packager to log its setup before the express server is done
        // this is a potential race condition but it'll work for now
        if (chunk.msg.indexOf('Loading dependency graph, done.') >= 0) {
          packagerReady = true;
          // TODO clearConsole();
          onReady();
          return;
        }

        const messagePrefix = chalk.dim(new Date().toLocaleTimeString()) + ':';

        // we don't need to print the entire manifest when loading the app
        if (chunk.msg.indexOf(' with appParams: ') >= 0) {
          if (needsClear) {
            // this is set when we previously encountered an error
            // TODO clearConsole();
          }
          console.log(`${messagePrefix} Loading your app...\n`);
          return;
        }

        if (packagerReady) {
          const message = `${messagePrefix} ${chunk.msg}\n`;
          if (chunk.level <= bunyan.INFO) {
            console.log(message);
          } else if (chunk.level === bunyan.WARN) {
            console.log(chalk.yellow(message));
          } else {
            console.log(chalk.red(message));

            // if you run into a syntax error then we should clear log output on reload
            needsClear = message.indexOf('SyntaxError') >= 0;
          }
        } else {
          if (chunk.level >= bunyan.ERROR) {
            console.log(chalk.yellow('***ERROR STARTING PACKAGER***'));
            console.log(logBuffer);
            console.log(chalk.red(chunk.msg));
            logBuffer = '';
          } else {
            logBuffer += chunk.msg + '\n';
          }
        }
      },
    },
    type: 'raw',
  });

  installExitHooks(projectDir);
  console.log(chalk.blue('Starting packager...'));

  Project.startAsync(projectDir, options).then(
    () => {},
    reason => {
      console.log(chalk.red(`Error starting packager: ${reason.stack}`));
      process.exit(1);
    }
  );
}

export default { run };
<|endoftext|>


<commit_before>import {
  fromGlobalId,
  connectionFromArray,
  nodeDefinitions,
  connectionDefinitions,
  connectionArgs
} from 'graphql-relay';

import {
  GraphQLList,
  GraphQLEnumType
} from 'graphql';

import {
  base64,
  unbase64,
} from './base64.js';

import _ from 'lodash';
import resolver from './resolver';

class NodeTypeMapper {

  constructor( sequelize ) {
    this.models = Object.keys(sequelize.models);
    this.models.forEach(model => {
      this[model] = null;
    });
  }

  mapTypes( types ) {
    Object.keys(types).forEach(type => {
      this[type] = types[type];
    });
  }
}

export function idFetcher(sequelize, nodeTypeMapper) {
  return globalId => {
    let {type, id} = fromGlobalId(globalId);
    const models = Object.keys(sequelize.models);
    if (models.some(model => model === type)) {
      return sequelize.models[type].findById(id);
    }
    if (nodeTypeMapper[type]) {
      return nodeTypeMapper[type];
    }
    return null;
  };
}

export function isConnection(type) {
  return typeof type.name !== 'undefined' && type.name.endsWith('Connection');
}

export function handleConnection(values, args) {
  return connectionFromArray(values, args);
}

export function sequelizeNodeInterface(sequelize) {
  let nodeTypeMapper = new NodeTypeMapper(sequelize);
  const nodeObjects = nodeDefinitions(idFetcher(sequelize, nodeTypeMapper), obj => {
    var name = obj.Model
            ? obj.Model.options.name.singular
            : obj.name;
    return nodeTypeMapper[name];
  });
  return {
    nodeTypeMapper,
    ...nodeObjects
  };
}

export function nodeAST(connectionAST) {
  return connectionAST.fields.edges.fields.node;
}

export function nodeType(connectionType) {
  return connectionType._fields.edges.type.ofType._fields.node.type;
}

export function sequelizeConnection({name, nodeType, target, orderBy: orderByEnum}) {
  const {
    edgeType,
    connectionType
  } = connectionDefinitions({name: name, nodeType: nodeType});

  const model = target.target ? target.target : target;
  const SEPERATOR = '$';
  const PREFIX = 'arrayconnection' + SEPERATOR;

  if (orderByEnum === undefined) {
    orderByEnum = new GraphQLEnumType({
      name: name + 'ConnectionOrder',
      values: {
        ID: {value: [model.primaryKeyAttribute, 'ASC']}
      }
    });
  }

  let $connectionArgs = {
    ...connectionArgs,
    orderBy: {
      type: new GraphQLList(orderByEnum)
    }
  };

  let orderByAttribute = function (orderBy) {
    return orderBy[0][0];
  };

  let toCursor = function (value, orderBy) {
    let id = value.get(model.primaryKeyAttribute);
    let orderValue = value.get(orderByAttribute(orderBy));
    return base64(PREFIX + id + SEPERATOR + orderValue);
  };

  let fromCursor = function (cursor) {
    cursor = unbase64(cursor);
    cursor = cursor.substring(PREFIX.length, cursor.length);
    let [id, orderValue] = cursor.split(SEPERATOR);

    return {
      id,
      orderValue
    };
  };

  return {
    connectionType,
    edgeType,
    nodeType,
    connectionArgs: $connectionArgs,
    resolve: resolver(target, {
      handleConnection: false,
      include: true,
      before: function (options, args) {
        if (args.first || args.last) {
          options.limit = parseInt(args.first || args.last, 10);
        }

        if (!args.orderBy) {
          args.orderBy = [orderByEnum._values[0].value];
        } else if (typeof args.orderBy === 'string') {
          args.orderBy = [orderByEnum._nameLookup[args.orderBy].value];
        }

        let orderBy = args.orderBy;
        let orderAttribute = orderByAttribute(orderBy);
        let orderDirection = args.orderBy[0][1];

        if (args.last) {
          orderDirection = orderDirection === 'ASC' ? 'DESC' : 'ASC';
        }

        options.order = [
          [orderAttribute, orderDirection]
        ];

        if (orderAttribute !== model.primaryKeyAttribute) {
          options.order.push([model.primaryKeyAttribute, 'ASC']);
        }

        options.attributes.push(orderAttribute);

        if (model.sequelize.dialect.name === 'postgres' && options.limit) {
          options.attributes.push([
            model.sequelize.literal('COUNT(*) OVER()'),
            'full_count'
          ]);
        }

        if (args.after || args.before) {
          let cursor = fromCursor(args.after || args.before);
          let orderValue = cursor.orderValue;

          if (model.rawAttributes[orderAttribute].type instanceof model.sequelize.constructor.DATE) {
            orderValue = new Date(orderValue);
          }

          options.where = options.where || {};

          let where = {
            $or: [
              {
                [orderAttribute]: {
                  [orderDirection === 'ASC' ? '$gt' : '$lt']: orderValue
                }
              },
              {
                [orderAttribute]: {
                  $eq: orderValue
                },
                [model.primaryKeyAttribute]: {
                  [orderDirection === 'ASC' ? '$gt' : '$lt']: cursor.id
                }
              }
            ]
          };

          // TODO, do a proper merge that won't kill another $or
          _.assign(options.where, where);
        }

        return options;
      },
      after: function (values, args) {
        if (!args.orderBy) {
          args.orderBy = [orderByEnum._values[0].value];
        }

        let edges = values.map((value) => {
          return {
            cursor: toCursor(value, args.orderBy),
            node: value
          };
        });

        let firstEdge = edges[0];
        let lastEdge = edges[edges.length - 1];
        let fullCount = values[0] && values[0].dataValues.full_count &&
                        parseInt(values[0].dataValues.full_count, 10) || 0;

        return {
          edges,
          pageInfo: {
            startCursor: firstEdge ? firstEdge.cursor : null,
            endCursor: lastEdge ? lastEdge.cursor : null,
            hasPreviousPage: args.last != null ? fullCount > parseInt(args.last, 10) : false,
            hasNextPage: args.first != null ? fullCount > parseInt(args.first, 10) : false,
          }
        };
      }
    })
  };
}
<commit_msg>primary key matching will always be  since order direction is always ASC<commit_after>import {
  fromGlobalId,
  connectionFromArray,
  nodeDefinitions,
  connectionDefinitions,
  connectionArgs
} from 'graphql-relay';

import {
  GraphQLList,
  GraphQLEnumType
} from 'graphql';

import {
  base64,
  unbase64,
} from './base64.js';

import _ from 'lodash';
import resolver from './resolver';

class NodeTypeMapper {

  constructor( sequelize ) {
    this.models = Object.keys(sequelize.models);
    this.models.forEach(model => {
      this[model] = null;
    });
  }

  mapTypes( types ) {
    Object.keys(types).forEach(type => {
      this[type] = types[type];
    });
  }
}

export function idFetcher(sequelize, nodeTypeMapper) {
  return globalId => {
    let {type, id} = fromGlobalId(globalId);
    const models = Object.keys(sequelize.models);
    if (models.some(model => model === type)) {
      return sequelize.models[type].findById(id);
    }
    if (nodeTypeMapper[type]) {
      return nodeTypeMapper[type];
    }
    return null;
  };
}

export function isConnection(type) {
  return typeof type.name !== 'undefined' && type.name.endsWith('Connection');
}

export function handleConnection(values, args) {
  return connectionFromArray(values, args);
}

export function sequelizeNodeInterface(sequelize) {
  let nodeTypeMapper = new NodeTypeMapper(sequelize);
  const nodeObjects = nodeDefinitions(idFetcher(sequelize, nodeTypeMapper), obj => {
    var name = obj.Model
            ? obj.Model.options.name.singular
            : obj.name;
    return nodeTypeMapper[name];
  });
  return {
    nodeTypeMapper,
    ...nodeObjects
  };
}

export function nodeAST(connectionAST) {
  return connectionAST.fields.edges.fields.node;
}

export function nodeType(connectionType) {
  return connectionType._fields.edges.type.ofType._fields.node.type;
}

export function sequelizeConnection({name, nodeType, target, orderBy: orderByEnum}) {
  const {
    edgeType,
    connectionType
  } = connectionDefinitions({name: name, nodeType: nodeType});

  const model = target.target ? target.target : target;
  const SEPERATOR = '$';
  const PREFIX = 'arrayconnection' + SEPERATOR;

  if (orderByEnum === undefined) {
    orderByEnum = new GraphQLEnumType({
      name: name + 'ConnectionOrder',
      values: {
        ID: {value: [model.primaryKeyAttribute, 'ASC']}
      }
    });
  }

  let $connectionArgs = {
    ...connectionArgs,
    orderBy: {
      type: new GraphQLList(orderByEnum)
    }
  };

  let orderByAttribute = function (orderBy) {
    return orderBy[0][0];
  };

  let toCursor = function (value, orderBy) {
    let id = value.get(model.primaryKeyAttribute);
    let orderValue = value.get(orderByAttribute(orderBy));
    return base64(PREFIX + id + SEPERATOR + orderValue);
  };

  let fromCursor = function (cursor) {
    cursor = unbase64(cursor);
    cursor = cursor.substring(PREFIX.length, cursor.length);
    let [id, orderValue] = cursor.split(SEPERATOR);

    return {
      id,
      orderValue
    };
  };

  return {
    connectionType,
    edgeType,
    nodeType,
    connectionArgs: $connectionArgs,
    resolve: resolver(target, {
      handleConnection: false,
      include: true,
      before: function (options, args) {
        if (args.first || args.last) {
          options.limit = parseInt(args.first || args.last, 10);
        }

        if (!args.orderBy) {
          args.orderBy = [orderByEnum._values[0].value];
        } else if (typeof args.orderBy === 'string') {
          args.orderBy = [orderByEnum._nameLookup[args.orderBy].value];
        }

        let orderBy = args.orderBy;
        let orderAttribute = orderByAttribute(orderBy);
        let orderDirection = args.orderBy[0][1];

        if (args.last) {
          orderDirection = orderDirection === 'ASC' ? 'DESC' : 'ASC';
        }

        options.order = [
          [orderAttribute, orderDirection]
        ];

        if (orderAttribute !== model.primaryKeyAttribute) {
          options.order.push([model.primaryKeyAttribute, 'ASC']);
        }

        options.attributes.push(orderAttribute);

        if (model.sequelize.dialect.name === 'postgres' && options.limit) {
          options.attributes.push([
            model.sequelize.literal('COUNT(*) OVER()'),
            'full_count'
          ]);
        }

        if (args.after || args.before) {
          let cursor = fromCursor(args.after || args.before);
          let orderValue = cursor.orderValue;

          if (model.rawAttributes[orderAttribute].type instanceof model.sequelize.constructor.DATE) {
            orderValue = new Date(orderValue);
          }

          options.where = options.where || {};

          let where = {
            $or: [
              {
                [orderAttribute]: {
                  [orderDirection === 'ASC' ? '$gt' : '$lt']: orderValue
                }
              },
              {
                [orderAttribute]: {
                  $eq: orderValue
                },
                [model.primaryKeyAttribute]: {
                  $gt: cursor.id
                }
              }
            ]
          };

          // TODO, do a proper merge that won't kill another $or
          _.assign(options.where, where);
        }

        return options;
      },
      after: function (values, args) {
        if (!args.orderBy) {
          args.orderBy = [orderByEnum._values[0].value];
        }

        let edges = values.map((value) => {
          return {
            cursor: toCursor(value, args.orderBy),
            node: value
          };
        });

        let firstEdge = edges[0];
        let lastEdge = edges[edges.length - 1];
        let fullCount = values[0] && values[0].dataValues.full_count &&
                        parseInt(values[0].dataValues.full_count, 10) || 0;

        return {
          edges,
          pageInfo: {
            startCursor: firstEdge ? firstEdge.cursor : null,
            endCursor: lastEdge ? lastEdge.cursor : null,
            hasPreviousPage: args.last != null ? fullCount > parseInt(args.last, 10) : false,
            hasNextPage: args.first != null ? fullCount > parseInt(args.first, 10) : false,
          }
        };
      }
    })
  };
}
<|endoftext|>


<commit_before>/*jshint regexp:false*/

/**
 * Controller abstract class.
 */
define([
    './Joint',
    'services/state',
    'mout/string/startsWith',
    'mout/object/size',
    'mout/object/pick',
    'mout/object/mixIn',
    'mout/array/find',
    'has'
], function (Joint, stateRegistry, startsWith, size, pick, mixIn, find, has) {

    'use strict';

    /**
     * Constructor.
     */
    function Controller() {
        Joint.call(this);

        this._parseStates();
    }

    Controller.extend = Joint.extend;
    Controller.prototype = Object.create(Joint.prototype);
    Controller.prototype.constructor = Controller;

    /**
     * Get the current state or null if none is set.
     *
     * @return {State} The state
     */
    Controller.prototype.getState = function () {
        return this._currentState;
    };

    /**
     * Generates an URL for a state.
     *
     * @param {String} name     The state name
     * @param {Object} [params] The state params
     *
     * @return {String} The generated URL
     */
    Controller.prototype.generateUrl = function (name, params) {
        var state;

        // Resolve the state
        state = this._resolveFullState(name);
        mixIn(state.params, params);

        return stateRegistry.generateUrl(state.fullName, state.params);
    };

    /**
     * Sets the current state.
     * If the state is the same, nothing happens.
     *
     * @param {String} [name]    The state name
     * @param {Object} [params]  The state params
     * @param {Object} [options] The options
     *
     * @return {Controller} The instance itself to allow chaining
     */
    Controller.prototype.setState = function (name, params, options) {
        var state;

        // Resolve the state
        state = this._resolveFullState(name);
        mixIn(state.params, params);

        // If the state is global, simply set it on the state registry
        if (state.name == null) {
            stateRegistry.setCurrent(state.fullName, state.params, options);
            return this;
        }

        // At this point the state is local
        // Check if the state is globally registered
        if (stateRegistry.isRegistered(state.fullName)) {
            // If so attempt to change the global state, aborting if it succeeded
            if (stateRegistry.setCurrent(state.fullName, state.params, options)) {
                return this;
            }
        // Otherwise, the state is meant to be used only by this controller
        } else {
            state = stateRegistry._createStateInstance(state.name, state.params);
        }

        return this.delegateState(state);
    };

    /**
     * Delegates a state to be handled by the controller.
     *
     * @param {Object|State} state The state parameter bag or a state instance
     *
     * @return {Controller} The instance itself to allow chaining
     */
    Controller.prototype.delegateState = function (state) {
        var name,
            params;

        // Assume app state if not passed
        if (!state) {
            state = stateRegistry.getCurrent();
        }

        state = state && (state.$info ? state.$info.newState : state);
        name = state && state.getName() || this._defaultState;
        params = state.getParams();

        // If still has no name it means there's no default state defined
        if (!name) {
            if (has('debug') && this._nrStates) {
                console.warn('No default state defined in "' + this.$name + '".');
            }

            return;
        }

        // Check if state exists
        if (!this._states[name]) {
            if (has('debug')) {
                console.warn('Unknown state "' + name + '" on controller "' + this.$name + '".');
            }

            return;
        }

        // If the current state is not the same, transition to it
        if (!this._isSameState(state)) {
            this._performStateChange(state);
        // Otherwise propagate it to child controllers
        } else {
            this._propagateState(state);
        }

        // Sync up the full state name with the application one
        // This is needed because default states might have been translated down the chain
        if (stateRegistry.getCurrent() === state) {
            this._currentState.setFullName(state.getFullName());
        }

        return this;
    };

    //////////////////////////////////////////////////////////////////

    /**
     * Parses the controller states.
     */
    Controller.prototype._parseStates = function () {
        var key,
            func,
            matches,
            regExp = this.constructor._stateParamsRegExp || Controller._stateParamsRegExp,
            states = this._states;

        this._states = {};
        this._nrStates = size(this._states);

        // Process the states object
        for (key in states) {
            func = states[key];

            // Process the params specified in the parentheses
            matches = key.match(regExp);
            if (matches) {
                key = key.substr(0, key.indexOf('('));
                this._states[key] = {};

                // If user specified state(*), then the state changes every time
                // even if the params haven't changed
                if (matches[1] === '*') {
                    this._states[key].wildcard = true;
                } else {
                    this._states[key].params = matches[1].split(/\s*,\s*/);
                }
            } else {
                this._states[key] = {};
                this._states[key].params = [];
            }

            if (has('debug')) {
                if (!stateRegistry.isValid(key)) {
                    throw new Error('State name "' + key + '" of "' + this.$name + '" has an invalid format.');
                }
                if (key.indexOf('.') !== -1) {
                    throw new Error('State name "' + key + '" of "' + this.$name + '" must be local (cannot contain dots).');
                }
            }

            // Check if it is a string or already a function
            if (typeof func === 'string') {
                func = this[func];
                this._states[key].fn = func;
            }

            if (has('debug') && typeof func !== 'function') {
                throw new Error('State handler "' + key + '" of "' + this.$name + '" references a nonexistent function.');
            }

            this._states[key].fn = func;
        }

        // Process the default state
        if (has('debug') && this._defaultState && !this._states[this._defaultState]) {
            throw new Error('The default state of "' + this.$name + '" points to an nonexistent state.');
        }
    };

    /**
     * Resolves a full state name.
     *
     * If name starts with a / then state is absolute.
     * If name starts with ../ then state is relative.
     * If empty will try to map to the default state.
     * Otherwise the full state name will be resolved from the local name.
     *
     * @param {String} [name] The state name
     *
     * @return {Object} The full state name and params
     */
    Controller.prototype._resolveFullState = function (name) {
        var state,
            ancestor,
            ancestorState;

        name = name || '';

        // Absolute
        if (name.charAt(0) === '/') {
            return {
                fullName: name.substr(1),
                params: {}
            };
        }

        // Relative
        if (startsWith(name, '../')) {
            if (has('debug') && (!this._uplink || !(this._uplink instanceof Controller))) {
                throw new Error('Cannot resolve relative state "' + name + '" in "' + this.$name + '".');
            }

            state = this._uplink._resolveFullState(name.substr(3));
            delete state.name;  // Remove name because state is not local

            return state;
        }

        state = {
            name: name,
            fullName: name,
            params: {}
        };

        // Local
        ancestor = this._uplink;
        while (ancestor && ancestor instanceof Controller) {
            ancestorState = ancestor.getState();
            if (!ancestorState) {
                // Break here, the ancestor is not in any state
                break;
            }

            // Concatenate name & mix in relevant params
            state.fullName = ancestorState.getName() + (state.fullName ? '.' + state.fullName : '');
            mixIn(state.params, ancestor._currentStateParams);

            ancestor = ancestor._uplink;
        }

        // Ensure names
        state.name = state.name || this._defaultState || '';
        state.fullName = state.fullName || this._defaultState || '';

        return state;
    };

    /**
     * Checks if a given state is the same as the current controller state.
     *
     * @param {State} state The state
     *
     * @return {Boolean} True if the same, false otherwise
     */
    Controller.prototype._isSameState = function (state) {
        var stateMeta;

        if (!this._currentState) {
            return false;
        }

        // Translate to default state if name is empty
        if (!state.getName()) {
            state = state.clone();
            state.setFullName(state.getFullName() + '.' + this._defaultState);
        }

        stateMeta = this._states[state.getName()];

        // Check if state is a wildcard
        if (stateMeta.wildcard) {
            return false;
        }

        // Check if equal
        return this._currentState.isEqual(state, stateMeta.params);
    };

    /**
     * Sets the current state based on the passed in state.
     * Updates all the necessary properties used internally.
     *
     * @param {State} state The state
     */
    Controller.prototype._setCurrentState = function (state) {
        var name,
            fullName,
            params,
            stateMeta;

        // Update current state
        this._currentState = state.clone();
        params = this._currentState.getParams();

        // Resolve to default state always
        if (!state.getName() && this._defaultState) {
            fullName = state.getFullName() ? state.getFullName() + '.' + this._defaultState : this._defaultState;
            this._currentState.setFullName(fullName);

            // Update also the state registry one
            if (state === stateRegistry.getCurrent()) {
                state.setFullName(fullName);
            }
        }

        name = this._currentState.getName();
        stateMeta = this._states[name];

        // Update state params being used by this controller
        this._currentStateParams = pick(params, stateMeta.params);
    };

    /**
     * Performs the state change, calling the state handler if any.
     *
     * @param {State} state The state
     */
    Controller.prototype._performStateChange = function (state) {
        var stateMeta;

        // Update internal state
        this._setCurrentState(state);

        // Advance pointer
        state.next();

        // Execute handler
        stateMeta = this._states[this._currentState.getName()];
        stateMeta.fn.call(this, state.getParams());
    };

    /**
     * Attempts to propagate the state to one of the downlinks.
     *
     * @param {State} state The state
     */
    Controller.prototype._propagateState = function (state) {
        var name,
            curr,
            length,
            x;

        // Update internal state
        this._setCurrentState(state);

        // Advance pointer
        state.next();

        // Find suitable child controller to handle the state
        name = state.getName();
        length = this._downlinks.length;

        for (x = 0; x < length; x += 1) {
            curr = this._downlinks[x];

            if (curr instanceof Controller) {
                if (curr._states[name] || (!name && curr._defaultState)) {
                    curr.delegateState(state);
                    return;
                }
            }
        }

        if (name && has('debug')) {
            console.warn('No child controller of "' + this.$name + '" declared the "' + name + '" state.');
        }
    };

    ////////////////////////////////////////////////////////////////

    Controller._stateParamsRegExp = /\((.+?)\)/;

    return Controller;
});
<commit_msg>Simplify.<commit_after>/*jshint regexp:false*/

/**
 * Controller abstract class.
 */
define([
    './Joint',
    'services/state',
    'mout/string/startsWith',
    'mout/object/size',
    'mout/object/pick',
    'mout/object/mixIn',
    'mout/array/find',
    'has'
], function (Joint, stateRegistry, startsWith, size, pick, mixIn, find, has) {

    'use strict';

    /**
     * Constructor.
     */
    function Controller() {
        Joint.call(this);

        this._parseStates();
    }

    Controller.extend = Joint.extend;
    Controller.prototype = Object.create(Joint.prototype);
    Controller.prototype.constructor = Controller;

    /**
     * Get the current state or null if none is set.
     *
     * @return {State} The state
     */
    Controller.prototype.getState = function () {
        return this._currentState;
    };

    /**
     * Generates an URL for a state.
     *
     * @param {String} name     The state name
     * @param {Object} [params] The state params
     *
     * @return {String} The generated URL
     */
    Controller.prototype.generateUrl = function (name, params) {
        var state;

        // Resolve the state
        state = this._resolveFullState(name);
        mixIn(state.params, params);

        return stateRegistry.generateUrl(state.fullName, state.params);
    };

    /**
     * Sets the current state.
     * If the state is the same, nothing happens.
     *
     * @param {String} [name]    The state name
     * @param {Object} [params]  The state params
     * @param {Object} [options] The options
     *
     * @return {Controller} The instance itself to allow chaining
     */
    Controller.prototype.setState = function (name, params, options) {
        var state;

        // Resolve the state
        state = this._resolveFullState(name);
        mixIn(state.params, params);

        // If the state is global, simply set it on the state registry
        if (state.name == null) {
            stateRegistry.setCurrent(state.fullName, state.params, options);
            return this;
        }

        // At this point the state is local
        // Check if the state is globally registered
        if (stateRegistry.isRegistered(state.fullName)) {
            // If so attempt to change the global state, aborting if it succeeded
            if (stateRegistry.setCurrent(state.fullName, state.params, options)) {
                return this;
            }
        // Otherwise, the state is meant to be used only by this controller
        } else {
            state = stateRegistry._createStateInstance(state.name, state.params);
        }

        return this.delegateState(state);
    };

    /**
     * Delegates a state to be handled by the controller.
     *
     * @param {Object|State} state The state parameter bag or a state instance
     *
     * @return {Controller} The instance itself to allow chaining
     */
    Controller.prototype.delegateState = function (state) {
        var name;

        // Assume app state if not passed
        if (!state) {
            state = stateRegistry.getCurrent();
        }

        state = state && (state.$info ? state.$info.newState : state);
        name = state && state.getName() || this._defaultState;

        // If still has no name it means there's no default state defined
        if (!name) {
            if (has('debug') && this._nrStates) {
                console.warn('No default state defined in "' + this.$name + '".');
            }

            return;
        }

        // Check if state exists
        if (!this._states[name]) {
            if (has('debug')) {
                console.warn('Unknown state "' + name + '" on controller "' + this.$name + '".');
            }

            return;
        }

        // If the current state is not the same, transition to it
        if (!this._isSameState(state)) {
            this._performStateChange(state);
        // Otherwise propagate it to child controllers
        } else {
            this._propagateState(state);
        }

        // Sync up the full state name with the application one
        // This is needed because default states might have been translated down the chain
        if (stateRegistry.getCurrent() === state) {
            this._currentState.setFullName(state.getFullName());
        }

        return this;
    };

    //////////////////////////////////////////////////////////////////

    /**
     * Parses the controller states.
     */
    Controller.prototype._parseStates = function () {
        var key,
            func,
            matches,
            regExp = this.constructor._stateParamsRegExp || Controller._stateParamsRegExp,
            states = this._states;

        this._states = {};
        this._nrStates = size(this._states);

        // Process the states object
        for (key in states) {
            func = states[key];

            // Process the params specified in the parentheses
            matches = key.match(regExp);
            if (matches) {
                key = key.substr(0, key.indexOf('('));
                this._states[key] = {};

                // If user specified state(*), then the state changes every time
                // even if the params haven't changed
                if (matches[1] === '*') {
                    this._states[key].wildcard = true;
                } else {
                    this._states[key].params = matches[1].split(/\s*,\s*/);
                }
            } else {
                this._states[key] = {};
                this._states[key].params = [];
            }

            if (has('debug')) {
                if (!stateRegistry.isValid(key)) {
                    throw new Error('State name "' + key + '" of "' + this.$name + '" has an invalid format.');
                }
                if (key.indexOf('.') !== -1) {
                    throw new Error('State name "' + key + '" of "' + this.$name + '" must be local (cannot contain dots).');
                }
            }

            // Check if it is a string or already a function
            if (typeof func === 'string') {
                func = this[func];
                this._states[key].fn = func;
            }

            if (has('debug') && typeof func !== 'function') {
                throw new Error('State handler "' + key + '" of "' + this.$name + '" references a nonexistent function.');
            }

            this._states[key].fn = func;
        }

        // Process the default state
        if (has('debug') && this._defaultState && !this._states[this._defaultState]) {
            throw new Error('The default state of "' + this.$name + '" points to an nonexistent state.');
        }
    };

    /**
     * Resolves a full state name.
     *
     * If name starts with a / then state is absolute.
     * If name starts with ../ then state is relative.
     * If empty will try to map to the default state.
     * Otherwise the full state name will be resolved from the local name.
     *
     * @param {String} [name] The state name
     *
     * @return {Object} The full state name and params
     */
    Controller.prototype._resolveFullState = function (name) {
        var state,
            ancestor,
            ancestorState;

        name = name || '';

        // Absolute
        if (name.charAt(0) === '/') {
            return {
                fullName: name.substr(1),
                params: {}
            };
        }

        // Relative
        if (startsWith(name, '../')) {
            if (has('debug') && (!this._uplink || !(this._uplink instanceof Controller))) {
                throw new Error('Cannot resolve relative state "' + name + '" in "' + this.$name + '".');
            }

            state = this._uplink._resolveFullState(name.substr(3));
            delete state.name;  // Remove name because state is not local

            return state;
        }

        state = {
            name: name,
            fullName: name,
            params: {}
        };

        // Local
        ancestor = this._uplink;
        while (ancestor && ancestor instanceof Controller) {
            ancestorState = ancestor.getState();
            if (!ancestorState) {
                // Break here, the ancestor is not in any state
                break;
            }

            // Concatenate name & mix in relevant params
            state.fullName = ancestorState.getName() + (state.fullName ? '.' + state.fullName : '');
            mixIn(state.params, ancestor._currentStateParams);

            ancestor = ancestor._uplink;
        }

        // Ensure names
        state.name = state.name || this._defaultState || '';
        state.fullName = state.fullName || this._defaultState || '';

        return state;
    };

    /**
     * Checks if a given state is the same as the current controller state.
     *
     * @param {State} state The state
     *
     * @return {Boolean} True if the same, false otherwise
     */
    Controller.prototype._isSameState = function (state) {
        var stateMeta;

        if (!this._currentState) {
            return false;
        }

        // Translate to default state if name is empty
        if (!state.getName()) {
            state = state.clone();
            state.setFullName(state.getFullName() + '.' + this._defaultState);
        }

        stateMeta = this._states[state.getName()];

        // Check if state is a wildcard
        if (stateMeta.wildcard) {
            return false;
        }

        // Check if equal
        return this._currentState.isEqual(state, stateMeta.params);
    };

    /**
     * Sets the current state based on the passed in state.
     * Updates all the necessary properties used internally.
     *
     * @param {State} state The state
     */
    Controller.prototype._setCurrentState = function (state) {
        var name,
            fullName,
            stateMeta;

        // Update current state
        this._currentState = state.clone();

        // Resolve to default state always
        if (!state.getName() && this._defaultState) {
            fullName = state.getFullName() ? state.getFullName() + '.' + this._defaultState : this._defaultState;
            this._currentState.setFullName(fullName);

            // Update also the state registry one
            if (state === stateRegistry.getCurrent()) {
                state.setFullName(fullName);
            }
        }

        name = this._currentState.getName();
        stateMeta = this._states[name];

        // Update state params being used by this controller
        this._currentStateParams = pick(this._currentState.getParams(), stateMeta.params);
    };

    /**
     * Performs the state change, calling the state handler if any.
     *
     * @param {State} state The state
     */
    Controller.prototype._performStateChange = function (state) {
        var stateMeta;

        // Update internal state
        this._setCurrentState(state);

        // Advance pointer
        state.next();

        // Execute handler
        stateMeta = this._states[this._currentState.getName()];
        stateMeta.fn.call(this, state.getParams());
    };

    /**
     * Attempts to propagate the state to one of the downlinks.
     *
     * @param {State} state The state
     */
    Controller.prototype._propagateState = function (state) {
        var name,
            curr,
            length,
            x;

        // Update internal state
        this._setCurrentState(state);

        // Advance pointer
        state.next();

        // Find suitable child controller to handle the state
        name = state.getName();
        length = this._downlinks.length;

        for (x = 0; x < length; x += 1) {
            curr = this._downlinks[x];

            if (curr instanceof Controller) {
                if (curr._states[name] || (!name && curr._defaultState)) {
                    curr.delegateState(state);
                    return;
                }
            }
        }

        if (name && has('debug')) {
            console.warn('No child controller of "' + this.$name + '" declared the "' + name + '" state.');
        }
    };

    ////////////////////////////////////////////////////////////////

    Controller._stateParamsRegExp = /\((.+?)\)/;

    return Controller;
});
<|endoftext|>


<commit_before>define('requestfullscreen', function() {
  return function(element) {
    if (element.requestFullScreen) {
      element.requestFullScreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullScreen) {
      element.webkitRequestFullScreen();
    }
  };
});

define('fullscreenelement', function() {
  return function(element) {
    return (element.fullscreenElement || element.mozFullScreenElement || element.webkitFullscreenElement);
  };
});

define('cancelfullscreen', function() {
  return function(element) {
    if (element.cancelFullScreen) {
      element.cancelFullScreen();
    } else if (element.mozCancelFullScreen) {
      element.mozCancelFullScreen();
    } else if (element.webkitCancelFullScreen) {
      element.webkitCancelFullScreen();
    }
  };
});

define('fullscreen', ['requestfullscreen', 'fullscreenelement', 'cancelfullscreen'], function(rf, fs, cf) {
  return {
    request: rf,
    isFullscreen: fs,
    cancel: cf
  };
})
<commit_msg>Fixes jshint error<commit_after>define('requestfullscreen', function() {
  return function(element) {
    if (element.requestFullScreen) {
      element.requestFullScreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullScreen) {
      element.webkitRequestFullScreen();
    }
  };
});

define('fullscreenelement', function() {
  return function(element) {
    return (element.fullscreenElement || element.mozFullScreenElement || element.webkitFullscreenElement);
  };
});

define('cancelfullscreen', function() {
  return function(element) {
    if (element.cancelFullScreen) {
      element.cancelFullScreen();
    } else if (element.mozCancelFullScreen) {
      element.mozCancelFullScreen();
    } else if (element.webkitCancelFullScreen) {
      element.webkitCancelFullScreen();
    }
  };
});

define('fullscreen', ['requestfullscreen', 'fullscreenelement', 'cancelfullscreen'], function(rf, fs, cf) {
  return {
    request: rf,
    isFullscreen: fs,
    cancel: cf
  };
});<|endoftext|>


<commit_before>/*
    FILE STRUCTURE ------------------------------------------------------------
    assets
    -- distribution
    ---- images
    ---- markup
    ---- scripts
    ---- styles
    -- source
    ---- images
    ---- markup
    ---- scripts
    ---- styles
*/

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    cleancss = require('gulp-clean-css'),
    autoprefixer = require('gulp-autoprefixer'),
    sass = require('gulp-sass'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    kit = require('gulp-kit'),
    plumber = require('gulp-plumber'),
    del = require('del');

var distribution = {
        destination: "../assets/distribution/";
    },
    styles = {
        destination: "../assets/distribution/styles/",
        source: "../assets/source/styles/**/*.scss",
        output: "min.css";
    },
    scripts = {
        destination: "../assets/distribution/scripts/",
        source: "../assets/source/scripts/**/*.js",
        output: "min.js";
    },
    markup = {
        destination: "../assets/distribution/markup/",
        source: "../assets/source/markup/**/*.kit";
    },
    index = {
        destination: "../../assets/",
        source: "../../assets/source/markup/index.kit";
    },
    images = {
        destination: "../assets/distribution/images/",
        source: "../assets/source/images/**/*";
    };

gulp.task('scripts', function () {
    return gulp.src(scripts.source)
        .pipe(plumber())
        .pipe(concat(scripts.output))
        .pipe(uglify())
        .pipe(gulp.dest(scripts.destination));
});

gulp.task('styles', function () {
    return gulp.src(styles.source)
        .pipe(plumber())
        .pipe(sass.sync())
        .pipe(autoprefixer())
        // .pipe(cleancss())
        .pipe(concat(styles.output))
        .pipe(gulp.dest(styles.destination));
});

gulp.task('markup', function() {
    return gulp.src(markup.source)
        .pipe(plumber())
        .pipe(kit())
        .pipe(gulp.dest(markup.destination));
});

gulp.task('index', function() {
    return gulp.src(index.source)
        .pipe(plumber())
        .pipe(kit())
        .pipe(gulp.dest(index.destination));
});

gulp.task('images', function() {
    return gulp.src(images.source)
        .pipe(imagemin())
        .pipe(gulp.dest(images.destination));
});

gulp.task('clean', function() {
    console.log('deleting distribution folder');
    return del(gulp.dest(distribution.destination));
});

gulp.task('watch', function () {
    gulp.watch(scripts.source, ['scripts']);
    gulp.watch(styles.source, ['styles']);
    gulp.watch(markup.source, ['markup']);
    gulp.watch(index.source, ['index']);
});

gulp.task('default', ['watch']);
<commit_msg>Update gulpfile.js<commit_after>/*
    FILE STRUCTURE ------------------------------------------------------------
    -- assets
    ---- distribution
    ------ images
    ------ markup
    ------ scripts
    ------ styles
    ---- source
    ------ images
    ------ markup
    ------ scripts
    ------ styles
    -- tools
*/

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    cleancss = require('gulp-clean-css'),
    autoprefixer = require('gulp-autoprefixer'),
    sass = require('gulp-sass'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    kit = require('gulp-kit'),
    plumber = require('gulp-plumber'),
    del = require('del');

var distribution = {
        destination: "../assets/distribution/";
    },
    styles = {
        destination: "../assets/distribution/styles/",
        source: "../assets/source/styles/**/*.scss",
        output: "min.css";
    },
    scripts = {
        destination: "../assets/distribution/scripts/",
        source: "../assets/source/scripts/**/*.js",
        output: "min.js";
    },
    markup = {
        destination: "../assets/distribution/markup/",
        source: "../assets/source/markup/**/*.kit";
    },
    index = {
        destination: "../../assets/",
        source: "../../assets/source/markup/index.kit";
    },
    images = {
        destination: "../assets/distribution/images/",
        source: "../assets/source/images/**/*";
    };

gulp.task('scripts', function () {
    return gulp.src(scripts.source)
        .pipe(plumber())
        .pipe(concat(scripts.output))
        .pipe(uglify())
        .pipe(gulp.dest(scripts.destination));
});

gulp.task('styles', function () {
    return gulp.src(styles.source)
        .pipe(plumber())
        .pipe(sass.sync())
        .pipe(autoprefixer())
        // .pipe(cleancss())
        .pipe(concat(styles.output))
        .pipe(gulp.dest(styles.destination));
});

gulp.task('markup', function() {
    return gulp.src(markup.source)
        .pipe(plumber())
        .pipe(kit())
        .pipe(gulp.dest(markup.destination));
});

gulp.task('index', function() {
    return gulp.src(index.source)
        .pipe(plumber())
        .pipe(kit())
        .pipe(gulp.dest(index.destination));
});

gulp.task('images', function() {
    return gulp.src(images.source)
        .pipe(imagemin())
        .pipe(gulp.dest(images.destination));
});

gulp.task('clean', function() {
    console.log('deleting distribution folder');
    return del(gulp.dest(distribution.destination));
});

gulp.task('watch', function () {
    gulp.watch(scripts.source, ['scripts']);
    gulp.watch(styles.source, ['styles']);
    gulp.watch(markup.source, ['markup']);
    gulp.watch(index.source, ['index']);
});

gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>import _ from 'lodash';
import requireDirectory from 'require-directory';

function renamer(name) {
  return _.camelCase(name);
}

export default requireDirectory(module, __dirname, { rename: renamer });
<commit_msg>Use toLowerCase instead of _.camelCase<commit_after>import requireDirectory from 'require-directory';

function renamer(name) {
  return name.toLowerCase();
}

export default requireDirectory(module, __dirname, { rename: renamer });
<|endoftext|>