<commit_before>const _ = require('lodash');
const j = require('../../lib/transform');
const crypto = require('crypto');

const Generator = require('../../lib/generator');
const OAUTH2_STRATEGY_MAPPINGS = {
  google: 'passport-google-oauth20',
  facebook: 'passport-facebook',
  github: 'passport-github'
};

module.exports = class AuthGenerator extends Generator {
  prompting() {
    this.checkPackage();

    const prompts = [{
      type: 'checkbox',
      name: 'strategies',
      message: 'What authentication providers do you want to use? Other PassportJS strategies not in this list can still be configured manually.',
      default: 'providers',
      choices: [{
        name: 'Username + Password (Local)',
        value: 'local'
      }, {
        name: 'Google',
        value: 'google'
      }, {
        name: 'Facebook',
        value: 'facebook'
      }, {
        name: 'GitHub',
        value: 'github'
      }]
    }, {
      name: 'entity',
      message: 'What is the name of the user (entity) service?',
      default: 'users'
    }];

    return this.prompt(prompts).then(props => {
      this.props = Object.assign(this.props, props);
    });
  }

  _transformCode(code) {
    const ast = j(code);
    const appDeclaration = ast.findDeclaration('app');
    const configureServices = ast.findConfigure('services');
    const requireCall = 'const authentication = require(\'./authentication\');';

    if (appDeclaration.length === 0) {
      throw new Error('Could not find \'app\' variable declaration in app.js to insert database configuration. Did you modify app.js?');
    }

    if (configureServices.length === 0) {
      throw new Error('Could not find .configure(services) call in app.js after which to insert database configuration. Did you modify app.js?');
    }

    appDeclaration.insertBefore(requireCall);
    configureServices.insertBefore('app.configure(authentication);');

    return ast.toSource();
  }

  _writeConfiguration(context) {
    const config = Object.assign({}, this.defaultConfig);

    config.authentication = {
      secret: crypto.randomBytes(256).toString('hex'),
      strategies: [ 'jwt' ],
      path: '/authentication',
      service: context.kebabEntity,
      jwt: {
        header: { type: 'access' },
        audience: 'https://yourdomain.com',
        subject: 'anonymous',
        issuer: 'feathers',
        algorithm: 'HS256',
        expiresIn: '1d'
      }
    };

    if (context.strategies.indexOf('local') !== -1) {
      config.authentication.strategies.push('local');
      config.authentication.local = {
        entity: 'user',
        service: 'users',
        usernameField: 'email',
        passwordField: 'password'
      };
    }

    let includesOAuth = false;

    context.strategies.forEach(strategy => {
      if (OAUTH2_STRATEGY_MAPPINGS[strategy]) {
        const strategyConfig = {
          clientID: `your ${strategy} client id`,
          clientSecret: `your ${strategy} client secret`,
          successRedirect: '/'
        };
        includesOAuth = true;

        if (strategy === 'facebook') {
          strategyConfig.scope = ['public_profile', 'email'];
          strategyConfig.profileFields = ['id', 'displayName', 'first_name', 'last_name', 'email', 'gender', 'profileUrl', 'birthday', 'picture', 'permissions'];
        }

        if (strategy === 'google') {
          strategyConfig.scope = ['profile openid email'];
        }

        config.authentication[strategy] = strategyConfig;
      }
    });

    if (includesOAuth) {
      config.authentication.cookie = {
        enabled: true,
        name: 'feathers-jwt',
        httpOnly: false,
        secure: false
      };
    }

    this.conflicter.force = true;
    this.fs.writeJSON(
      this.destinationPath('config', 'default.json'),
      config
    );
  }

  writing() {
    const dependencies = [
      'feathers-authentication',
      'feathers-authentication-hooks',
      'feathers-authentication-jwt'
    ];
    const context = Object.assign({
      kebabEntity: _.kebabCase(this.props.entity),
      camelEntity: _.camelCase(this.props.entity),
      oauthProviders: []
    }, this.props);

    // Set up strategies and add dependencies
    this.props.strategies.forEach(strategy => {
      const oauthProvider = OAUTH2_STRATEGY_MAPPINGS[strategy];

      if (oauthProvider) {
        dependencies.push('feathers-authentication-oauth2');
        dependencies.push(oauthProvider);
        context.oauthProviders.push({
          name: strategy,
          strategyName: `${_.upperFirst(strategy)}Strategy`,
          module: oauthProvider
        });
      } else {
        dependencies.push(`feathers-authentication-${strategy}`);
      }
    });

    // Create the users service
    this.composeWith(require.resolve('../service'), {
      props: {
        name: context.entity,
        path: `/${context.kebabEntity}`,
        authentication: context
      }
    });

    // If the file doesn't exist yet, add it to the app.js
    if (!this.fs.exists(this.destinationPath(this.libDirectory, 'authentication.js'))) {
      const appjs = this.destinationPath(this.libDirectory, 'app.js');

      this.conflicter.force = true;
      this.fs.write(appjs, this._transformCode(
        this.fs.read(appjs).toString()
      ));
    }

    this.fs.copyTpl(
      this.templatePath('authentication.js'),
      this.destinationPath(this.libDirectory, 'authentication.js'),
      context
    );

    this._writeConfiguration(context);
    this._packagerInstall(dependencies, {
      save: true
    });
  }
};
<commit_msg>Remove wrong entity name from local authentication configuration (#237)<commit_after>const _ = require('lodash');
const j = require('../../lib/transform');
const crypto = require('crypto');

const Generator = require('../../lib/generator');
const OAUTH2_STRATEGY_MAPPINGS = {
  google: 'passport-google-oauth20',
  facebook: 'passport-facebook',
  github: 'passport-github'
};

module.exports = class AuthGenerator extends Generator {
  prompting() {
    this.checkPackage();

    const prompts = [{
      type: 'checkbox',
      name: 'strategies',
      message: 'What authentication providers do you want to use? Other PassportJS strategies not in this list can still be configured manually.',
      default: 'providers',
      choices: [{
        name: 'Username + Password (Local)',
        value: 'local'
      }, {
        name: 'Google',
        value: 'google'
      }, {
        name: 'Facebook',
        value: 'facebook'
      }, {
        name: 'GitHub',
        value: 'github'
      }]
    }, {
      name: 'entity',
      message: 'What is the name of the user (entity) service?',
      default: 'users'
    }];

    return this.prompt(prompts).then(props => {
      this.props = Object.assign(this.props, props);
    });
  }

  _transformCode(code) {
    const ast = j(code);
    const appDeclaration = ast.findDeclaration('app');
    const configureServices = ast.findConfigure('services');
    const requireCall = 'const authentication = require(\'./authentication\');';

    if (appDeclaration.length === 0) {
      throw new Error('Could not find \'app\' variable declaration in app.js to insert database configuration. Did you modify app.js?');
    }

    if (configureServices.length === 0) {
      throw new Error('Could not find .configure(services) call in app.js after which to insert database configuration. Did you modify app.js?');
    }

    appDeclaration.insertBefore(requireCall);
    configureServices.insertBefore('app.configure(authentication);');

    return ast.toSource();
  }

  _writeConfiguration(context) {
    const config = Object.assign({}, this.defaultConfig);

    config.authentication = {
      secret: crypto.randomBytes(256).toString('hex'),
      strategies: [ 'jwt' ],
      path: '/authentication',
      service: context.kebabEntity,
      jwt: {
        header: { type: 'access' },
        audience: 'https://yourdomain.com',
        subject: 'anonymous',
        issuer: 'feathers',
        algorithm: 'HS256',
        expiresIn: '1d'
      }
    };

    if (context.strategies.indexOf('local') !== -1) {
      config.authentication.strategies.push('local');
      config.authentication.local = {
        entity: 'user',
        usernameField: 'email',
        passwordField: 'password'
      };
    }

    let includesOAuth = false;

    context.strategies.forEach(strategy => {
      if (OAUTH2_STRATEGY_MAPPINGS[strategy]) {
        const strategyConfig = {
          clientID: `your ${strategy} client id`,
          clientSecret: `your ${strategy} client secret`,
          successRedirect: '/'
        };
        includesOAuth = true;

        if (strategy === 'facebook') {
          strategyConfig.scope = ['public_profile', 'email'];
          strategyConfig.profileFields = ['id', 'displayName', 'first_name', 'last_name', 'email', 'gender', 'profileUrl', 'birthday', 'picture', 'permissions'];
        }

        if (strategy === 'google') {
          strategyConfig.scope = ['profile openid email'];
        }

        config.authentication[strategy] = strategyConfig;
      }
    });

    if (includesOAuth) {
      config.authentication.cookie = {
        enabled: true,
        name: 'feathers-jwt',
        httpOnly: false,
        secure: false
      };
    }

    this.conflicter.force = true;
    this.fs.writeJSON(
      this.destinationPath('config', 'default.json'),
      config
    );
  }

  writing() {
    const dependencies = [
      'feathers-authentication',
      'feathers-authentication-hooks',
      'feathers-authentication-jwt'
    ];
    const context = Object.assign({
      kebabEntity: _.kebabCase(this.props.entity),
      camelEntity: _.camelCase(this.props.entity),
      oauthProviders: []
    }, this.props);

    // Set up strategies and add dependencies
    this.props.strategies.forEach(strategy => {
      const oauthProvider = OAUTH2_STRATEGY_MAPPINGS[strategy];

      if (oauthProvider) {
        dependencies.push('feathers-authentication-oauth2');
        dependencies.push(oauthProvider);
        context.oauthProviders.push({
          name: strategy,
          strategyName: `${_.upperFirst(strategy)}Strategy`,
          module: oauthProvider
        });
      } else {
        dependencies.push(`feathers-authentication-${strategy}`);
      }
    });

    // Create the users service
    this.composeWith(require.resolve('../service'), {
      props: {
        name: context.entity,
        path: `/${context.kebabEntity}`,
        authentication: context
      }
    });

    // If the file doesn't exist yet, add it to the app.js
    if (!this.fs.exists(this.destinationPath(this.libDirectory, 'authentication.js'))) {
      const appjs = this.destinationPath(this.libDirectory, 'app.js');

      this.conflicter.force = true;
      this.fs.write(appjs, this._transformCode(
        this.fs.read(appjs).toString()
      ));
    }

    this.fs.copyTpl(
      this.templatePath('authentication.js'),
      this.destinationPath(this.libDirectory, 'authentication.js'),
      context
    );

    this._writeConfiguration(context);
    this._packagerInstall(dependencies, {
      save: true
    });
  }
};
<|endoftext|>


<commit_before>import React from 'react'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'

export default () => ({
  // Use beforeRenderToHtml to extract the styles into the page meta
  beforeRenderToHtml: (element, { meta }) => {
    meta.styledComponentsSheet = new ServerStyleSheet()
    return (
      <StyleSheetManager sheet={meta.styledComponentsSheet.instance}>
        {element}
      </StyleSheetManager>
    )
  },
  headElements: (elements, { meta }) => {
    // The styles aren't fully extraced until the react component
    // has been rendered to an html string. So we wait until the head
    // to call the sheet's getStyleElement function
    // and then insert the tag into the Head

    elements = [...elements, meta.styledComponentsSheet.getStyleElement()]

    return elements
  },
})
<commit_msg>Fixed typo (#1351)<commit_after>import React from 'react'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'

export default () => ({
  // Use beforeRenderToHtml to extract the styles into the page meta
  beforeRenderToHtml: (element, { meta }) => {
    meta.styledComponentsSheet = new ServerStyleSheet()
    return (
      <StyleSheetManager sheet={meta.styledComponentsSheet.instance}>
        {element}
      </StyleSheetManager>
    )
  },
  headElements: (elements, { meta }) => {
    // The styles aren't fully extracted until the react component
    // has been rendered to an html string. So we wait until the head
    // to call the sheet's getStyleElement function
    // and then insert the tag into the Head

    elements = [...elements, meta.styledComponentsSheet.getStyleElement()]

    return elements
  },
})
<|endoftext|>


<commit_before>/**
 *
 * Li
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import cn from 'classnames';
import moment from 'moment';

import FileIcon from 'components/FileIcon';
import IcoContainer from 'components/IcoContainer';
import PopUpWarning from 'components/PopUpWarning';

import styles from './styles.scss';

/* eslint-disable react/no-string-refs */
class Li extends React.Component {
  state = { isOpen: false, copied: false };

  componentDidUpdate(prevProps, prevState) {
    if (prevState.copied !== this.state.copied && this.state.copied) {
      setTimeout(() => {
        this.setState({ copied: false });
      }, 3000);
    }
  }

  getUnit = (value) => {
    let unit;
    let divider;

    switch (true) {
      case value > 10000:
        unit = 'GB';
        divider = 1000;
        break;
      case value < 1:
        unit = 'B';
        divider = 1;
        break;
      case value > 1000:
        unit = 'MB';
        divider = 1000;
        break;
      default:
        unit = 'KB';
        divider = 1;
    }

    return { divider, unit };
  }

  handleClick = (e) => {
    e.preventDefault();
    const aTag = document.getElementById('aTag');
    aTag.click();
  }

  handleDelete = (e) => {
    e.preventDefault();
    this.context.deleteData(this.props.item);
  }

  renderLiCopied = () => (

          <FormattedMessage id="upload.Li.linkCopied" />

  );

  render() {
    const { item } = this.props;

    if (this.state.copied) {
      return this.renderLiCopied();
    }

    const icons = [
      // {
      //   icoType: item.private ? 'lock' : 'unlock',
      //   onClick: () => {},
      // },
      {
        icoType: 'eye',
        onClick: this.handleClick,
      },
      {
        icoType: 'trash',
        onClick: () => this.setState({ isOpen: true }),
      },
    ];

    return (
      <CopyToClipboard text={item.url} onCopy={() => this.setState({copied: true})}>

          nothing

              <FileIcon fileType={item.ext} />

            {['hash', 'name', 'updatedAt', 'size', 'relatedTo', ''].map((value, key) => {
              if (value === 'updatedAt') {
                return (

{moment(item[value]).format('YYYY/MM/DD - HH:mm')}

                );
              }

              if (value === 'size') {
                const { divider, unit } = this.getUnit(item[value]);
                const size = item[value]/divider;

                return (

{Math.round(size * 100) / 100 } {unit}

                );
              }

              if (value !== '') {
                return (

{item[value]}

                );
              }

              return <IcoContainer key={key} icons={icons} />;
            })}

          <PopUpWarning
            isOpen={this.state.isOpen}
            onConfirm={this.handleDelete}
            toggleModal={() => this.setState({ isOpen: false })}
          />

      </CopyToClipboard>
    );
  }
}

Li.contextTypes = {
  deleteData: PropTypes.func.isRequired,
};

Li.defaultProps = {
  item: {
    type: 'pdf',
    hash: '1234',
    name: 'avatar.pdf',
    updated: '20/11/2017 19:29:54',
    size: '24 B',
    relatedTo: 'John Doe',
  },
};

Li.propTypes = {
  item: PropTypes.object,
};

export default Li;
<commit_msg>Fix #1761 GB MB<commit_after>/**
 *
 * Li
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import cn from 'classnames';
import moment from 'moment';

import FileIcon from 'components/FileIcon';
import IcoContainer from 'components/IcoContainer';
import PopUpWarning from 'components/PopUpWarning';

import styles from './styles.scss';

/* eslint-disable react/no-string-refs */
class Li extends React.Component {
  state = { isOpen: false, copied: false };

  componentDidUpdate(prevProps, prevState) {
    if (prevState.copied !== this.state.copied && this.state.copied) {
      setTimeout(() => {
        this.setState({ copied: false });
      }, 3000);
    }
  }

  getUnit = (value) => {
    let unit;
    let divider;

    switch (true) {
      case value > 1000000:
        unit = 'GB';
        divider = 1000000;
        break;
      case value < 1:
        unit = 'B';
        divider = .001;
        break;
      case value > 1000:
        unit = 'MB';
        divider = 1000;
        break;
      default:
        unit = 'KB';
        divider = 1;
    }

    return { divider, unit };
  }

  handleClick = (e) => {
    e.preventDefault();
    const aTag = document.getElementById('aTag');
    aTag.click();
  }

  handleDelete = (e) => {
    e.preventDefault();
    this.context.deleteData(this.props.item);
  }

  renderLiCopied = () => (

          <FormattedMessage id="upload.Li.linkCopied" />

  );

  render() {
    const { item } = this.props;

    if (this.state.copied) {
      return this.renderLiCopied();
    }

    const icons = [
      // {
      //   icoType: item.private ? 'lock' : 'unlock',
      //   onClick: () => {},
      // },
      {
        icoType: 'eye',
        onClick: this.handleClick,
      },
      {
        icoType: 'trash',
        onClick: () => this.setState({ isOpen: true }),
      },
    ];

    return (
      <CopyToClipboard text={item.url} onCopy={() => this.setState({copied: true})}>

          nothing

              <FileIcon fileType={item.ext} />

            {['hash', 'name', 'updatedAt', 'size', 'relatedTo', ''].map((value, key) => {
              if (value === 'updatedAt') {
                return (

{moment(item[value]).format('YYYY/MM/DD - HH:mm')}

                );
              }

              if (value === 'size') {
                const { divider, unit } = this.getUnit(item[value]);
                const size = item[value]/divider;

                return (

{Math.round(size * 100) / 100 } {unit}

                );
              }

              if (value !== '') {
                return (

{item[value]}

                );
              }

              return <IcoContainer key={key} icons={icons} />;
            })}

          <PopUpWarning
            isOpen={this.state.isOpen}
            onConfirm={this.handleDelete}
            toggleModal={() => this.setState({ isOpen: false })}
          />

      </CopyToClipboard>
    );
  }
}

Li.contextTypes = {
  deleteData: PropTypes.func.isRequired,
};

Li.defaultProps = {
  item: {
    type: 'pdf',
    hash: '1234',
    name: 'avatar.pdf',
    updated: '20/11/2017 19:29:54',
    size: '24 B',
    relatedTo: 'John Doe',
  },
};

Li.propTypes = {
  item: PropTypes.object,
};

export default Li;
<|endoftext|>


<commit_before>/*
 *
 * CommunityContent
 *
 */

import React from 'react'

import { connectStore, ROUTE } from '@utils'

import PostsThread from '@containers//PostsThread'
import VideosThread from '@containers/VideosThread'
import ReposThread from '@containers/ReposThread'
import WikiThread from '@containers/WikiThread'
import JobsThread from '@containers/JobsThread'
import UsersThread from '@containers/UsersThread'
import CheatsheetThread from '@containers/CheatsheetThread'

import { Wrapper } from './styles'
import { useInit } from './logic'

/* eslint-disable-next-line */
const debug = makeDebugger('C:CommunityContent')

const ComunityContent = ({ curRoute }) => {
  const { subPath } = curRoute
  switch (subPath) {
    case ROUTE.REPOS:
      return <ReposThread />

    case ROUTE.USERS:
      return <UsersThread />

    case ROUTE.VIDEOS:
      return <VideosThread />

    case ROUTE.JOBS:
      return <JobsThread />

    case ROUTE.WIKI:
      return <WikiThread />

    case ROUTE.CHEATSHEET:
      return <CheatsheetThread />

    default:
      return <PostsThread />
  }
}

const CommunityContentContainer = ({ communityContent }) => {
  useInit(communityContent)

  const { curRoute } = communityContent

  return (
    <Wrapper testid="community-content">
      <ComunityContent curRoute={curRoute} />
    </Wrapper>
  )
}

export default connectStore(CommunityContentContainer)
<commit_msg>fix: missing import<commit_after>/*
 *
 * CommunityContent
 *
 */

import React from 'react'

import { connectStore, makeDebugger, ROUTE } from '@utils'

import PostsThread from '@containers//PostsThread'
import VideosThread from '@containers/VideosThread'
import ReposThread from '@containers/ReposThread'
import WikiThread from '@containers/WikiThread'
import JobsThread from '@containers/JobsThread'
import UsersThread from '@containers/UsersThread'
import CheatsheetThread from '@containers/CheatsheetThread'

import { Wrapper } from './styles'
import { useInit } from './logic'

/* eslint-disable-next-line */
const debug = makeDebugger('C:CommunityContent')

const ComunityContent = ({ curRoute }) => {
  const { subPath } = curRoute
  switch (subPath) {
    case ROUTE.REPOS:
      return <ReposThread />

    case ROUTE.USERS:
      return <UsersThread />

    case ROUTE.VIDEOS:
      return <VideosThread />

    case ROUTE.JOBS:
      return <JobsThread />

    case ROUTE.WIKI:
      return <WikiThread />

    case ROUTE.CHEATSHEET:
      return <CheatsheetThread />

    default:
      return <PostsThread />
  }
}

const CommunityContentContainer = ({ communityContent }) => {
  useInit(communityContent)

  const { curRoute } = communityContent

  return (
    <Wrapper testid="community-content">
      <ComunityContent curRoute={curRoute} />
    </Wrapper>
  )
}

export default connectStore(CommunityContentContainer)
<|endoftext|>


<commit_before>"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _path = _interopRequireDefault(require("path"));

var _schemaUtils = _interopRequireDefault(require("schema-utils"));

var _loaderUtils = require("loader-utils");

var _options = _interopRequireDefault(require("./options.json"));

var _getSassImplementation = _interopRequireDefault(require("./getSassImplementation"));

var _getSassOptions = _interopRequireDefault(require("./getSassOptions"));

var _webpackImporter = _interopRequireDefault(require("./webpackImporter"));

var _getRenderFunctionFromSassImplementation = _interopRequireDefault(require("./getRenderFunctionFromSassImplementation"));

var _SassError = _interopRequireDefault(require("./SassError"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * The sass-loader makes node-sass and dart-sass available to webpack modules.
 *
 * @this {object}
 * @param {string} content
 */
function loader(content) {
  const options = (0, _loaderUtils.getOptions)(this) || {};
  // fixed by xxxxxx
  const isNVue = !!options.nvue
  delete options.nvue
  (0, _schemaUtils.default)(_options.default, options, {
    name: 'Sass Loader',
    baseDataPath: 'options'
  });
  const implementation = (0, _getSassImplementation.default)(options.implementation);
  const callback = this.async();

  const addNormalizedDependency = file => {
    // node-sass returns POSIX paths
    this.addDependency(_path.default.normalize(file));
  };

  const sassOptions = (0, _getSassOptions.default)(this, options, content, implementation);
  const shouldUseWebpackImporter = typeof options.webpackImporter === 'boolean' ? options.webpackImporter : true;

  if (shouldUseWebpackImporter) {
    const resolve = this.getResolve({
      mainFields: ['sass', 'style', 'main', '...'],
      mainFiles: ['_index', 'index', '...'],
      extensions: ['.scss', '.sass', '.css', '...']
    });
    sassOptions.importer.push((0, _webpackImporter.default)(this.resourcePath, resolve, addNormalizedDependency, isNVue));
  } // Skip empty files, otherwise it will stop webpack, see issue #21

  if (sassOptions.data.trim() === '') {
    callback(null, '');
    return;
  }

  const render = (0, _getRenderFunctionFromSassImplementation.default)(implementation);
  render(sassOptions, (error, result) => {
    if (error) {
      if (error.file) {
        addNormalizedDependency(error.file);
      }

      callback(new _SassError.default(error, this.resourcePath));
      return;
    }

    if (result.map && result.map !== '{}') {
      // eslint-disable-next-line no-param-reassign
      result.map = JSON.parse(result.map); // result.map.file is an optional property that provides the output filename.
      // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
      // eslint-disable-next-line no-param-reassign

      delete result.map.file; // One of the sources is 'stdin' according to dart-sass/node-sass because we've used the data input.
      // Now let's override that value with the correct relative path.
      // Since we specified options.sourceMap = path.join(process.cwd(), "/sass.map"); in getSassOptions,
      // we know that this path is relative to process.cwd(). This is how node-sass works.
      // eslint-disable-next-line no-param-reassign

      const stdinIndex = result.map.sources.findIndex(source => source.includes('stdin'));

      if (stdinIndex !== -1) {
        // eslint-disable-next-line no-param-reassign
        result.map.sources[stdinIndex] = _path.default.relative(process.cwd(), this.resourcePath);
      } // node-sass returns POSIX paths, that's why we need to transform them back to native paths.
      // This fixes an error on windows where the source-map module cannot resolve the source maps.
      // @see https://github.com/webpack-contrib/sass-loader/issues/366#issuecomment-279460722
      // eslint-disable-next-line no-param-reassign

      result.map.sourceRoot = _path.default.normalize(result.map.sourceRoot); // eslint-disable-next-line no-param-reassign

      result.map.sources = result.map.sources.map(_path.default.normalize);
    } else {
      // eslint-disable-next-line no-param-reassign
      result.map = null;
    }

    result.stats.includedFiles.forEach(addNormalizedDependency);
    callback(null, result.css.toString(), result.map);
  });
}

var _default = loader;
exports.default = _default;
<commit_msg>fix(nvue): preprocess css<commit_after>"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _path = _interopRequireDefault(require("path"));

var _schemaUtils = _interopRequireDefault(require("schema-utils"));

var _loaderUtils = require("loader-utils");

var _options = _interopRequireDefault(require("./options.json"));

var _getSassImplementation = _interopRequireDefault(require("./getSassImplementation"));

var _getSassOptions = _interopRequireDefault(require("./getSassOptions"));

var _webpackImporter = _interopRequireDefault(require("./webpackImporter"));

var _getRenderFunctionFromSassImplementation = _interopRequireDefault(require("./getRenderFunctionFromSassImplementation"));

var _SassError = _interopRequireDefault(require("./SassError"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * The sass-loader makes node-sass and dart-sass available to webpack modules.
 *
 * @this {object}
 * @param {string} content
 */
function loader(content) {
  const options = (0, _loaderUtils.getOptions)(this) || {};
  // fixed by xxxxxx
  const isNVue = !!options.nvue;
  delete options.nvue;
  (0, _schemaUtils.default)(_options.default, options, {
    name: 'Sass Loader',
    baseDataPath: 'options'
  });
  const implementation = (0, _getSassImplementation.default)(options.implementation);
  const callback = this.async();

  const addNormalizedDependency = file => {
    // node-sass returns POSIX paths
    this.addDependency(_path.default.normalize(file));
  };

  const sassOptions = (0, _getSassOptions.default)(this, options, content, implementation);
  const shouldUseWebpackImporter = typeof options.webpackImporter === 'boolean' ? options.webpackImporter : true;

  if (shouldUseWebpackImporter) {
    const resolve = this.getResolve({
      mainFields: ['sass', 'style', 'main', '...'],
      mainFiles: ['_index', 'index', '...'],
      extensions: ['.scss', '.sass', '.css', '...']
    });
    sassOptions.importer.push((0, _webpackImporter.default)(this.resourcePath, resolve, addNormalizedDependency, isNVue));
  } // Skip empty files, otherwise it will stop webpack, see issue #21

  if (sassOptions.data.trim() === '') {
    callback(null, '');
    return;
  }

  const render = (0, _getRenderFunctionFromSassImplementation.default)(implementation);
  render(sassOptions, (error, result) => {
    if (error) {
      if (error.file) {
        addNormalizedDependency(error.file);
      }

      callback(new _SassError.default(error, this.resourcePath));
      return;
    }

    if (result.map && result.map !== '{}') {
      // eslint-disable-next-line no-param-reassign
      result.map = JSON.parse(result.map); // result.map.file is an optional property that provides the output filename.
      // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
      // eslint-disable-next-line no-param-reassign

      delete result.map.file; // One of the sources is 'stdin' according to dart-sass/node-sass because we've used the data input.
      // Now let's override that value with the correct relative path.
      // Since we specified options.sourceMap = path.join(process.cwd(), "/sass.map"); in getSassOptions,
      // we know that this path is relative to process.cwd(). This is how node-sass works.
      // eslint-disable-next-line no-param-reassign

      const stdinIndex = result.map.sources.findIndex(source => source.includes('stdin'));

      if (stdinIndex !== -1) {
        // eslint-disable-next-line no-param-reassign
        result.map.sources[stdinIndex] = _path.default.relative(process.cwd(), this.resourcePath);
      } // node-sass returns POSIX paths, that's why we need to transform them back to native paths.
      // This fixes an error on windows where the source-map module cannot resolve the source maps.
      // @see https://github.com/webpack-contrib/sass-loader/issues/366#issuecomment-279460722
      // eslint-disable-next-line no-param-reassign

      result.map.sourceRoot = _path.default.normalize(result.map.sourceRoot); // eslint-disable-next-line no-param-reassign

      result.map.sources = result.map.sources.map(_path.default.normalize);
    } else {
      // eslint-disable-next-line no-param-reassign
      result.map = null;
    }

    result.stats.includedFiles.forEach(addNormalizedDependency);
    callback(null, result.css.toString(), result.map);
  });
}

var _default = loader;
exports.default = _default;
<|endoftext|>


<commit_before>/**
	_moon.CalendarPicker_ is a control that displays a monthly calendar, with the
	month name at the top and a grid of days, grouped into rows by week, below.

	The header buttons are used to navigate to the desired month; the desired day
	is selected by tapping on it.

	{kind: "moon.CalendarPicker", content: "Calendar Title"}
*/
enyo.kind({
	name: "moon.CalendarPickerDate",
	kind: "moon.Button",
	small: true,
	marquee: false,
	classes: "moon-calendar-picker-date enyo-unselectable",
	published: {
		value: null,
		color: 0
	},
	create: function() {
		this.inherited(arguments);
		if (typeof ilib !== "undefined") {
			this._tf = new ilib.DateFmt({
				type: "date",	//only format the date component, not the time
				date: "d",		//'d' is the date of month
				length: "short"	//it uses 2 chars to abbreviate properly
			});
		}
	},
	colorChanged: function(inOld) {
		if (this.color) {
			this.addClass("moon-calendar-picker-date-shadow");
		} else {
			this.removeClass("moon-calendar-picker-date-shadow");
		}
	},
	valueChanged: function() {
		if (typeof ilib !== "undefined") {
			var date = ilib.Date.newInstance({unixtime: (this.value.getDate() - 1) * (24*60*60*1000)});
			this.setContent(this._tf.format(date));
		} else {
			this.setContent(this.value.getDate());
		}
	}
});

enyo.kind({
	name: "moon.CalendarPicker",
	classes: "moon-calendar-picker",
	events: {
		/**
			Fires when the date changes.

			_inEvent.name_ contains the name of this control.

			_inEvent.value_ contains a standard JavaScript Date object representing
			the current date.
		*/
		onChange: ""
	},
	handlers: {
		ontap: "selectDate"
	},
	published: {
		/**
			ilib locale info instance. It gives information about the paarticular locale.
		*/
		ilibLocaleInfo: null,
		/**
			Current locale used for formatting. May be set after the control is
			created, in which case the control will be updated to reflect the
			new value.
		*/
		locale: "en_us",
		/**
			The current Date object. When a Date object is passed to _setValue_,
			the control is updated to reflect the new value. _getValue_ returns
			a Date object.
		*/
		value: null,
		/**
			The day of week that starts weeks in current locale.
			As a default, Sunday is the first day of week.
		*/
		firstDayOfWeek: 0,
		/**
			The maximum number of weeks to display in a screen.
			If this value is greater than 9, dates two months in the future may be
			shown. Unexpected input may result in errors.
		*/
		maxWeeks: 6,
		months: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
		days: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
	},
	components: [
		{name: "simplePicker", kind: "moon.SimplePicker", classes: "moon-calendar-picker-simplepicker"},
		{name: "days", kind: "enyo.Group"},
		{name: "dates", kind: "enyo.Group"}
	],
	create: function() {
		this.inherited(arguments);
		this.setupSimplePicker();
		this.setupCalendar();

		if (typeof ilib !== "undefined") {
			this._tf = new ilib.DateFmt({
				type: "date",	//only format the date component, not the time
				date: "w",		//'w' is the day of the week
				length: "short"	//it uses 2 chars to abbreviate properly
			});

			this.ilibLocaleInfo = new ilib.LocaleInfo();
			this.setLocale(this.ilibLocaleInfo.locale);
		} else {
			this.initDefaults();
		}
	},
	initDefaults: function() {
		this.setValue(this.value || new Date());
		//Attempt to use the ilib lib (assuming that it is loaded)
		if (typeof ilib !== "undefined") {
			var dayOfWeek = this.ilibLocaleInfo.getFirstDayOfWeek();
			this.setFirstDayOfWeek(dayOfWeek);
		} else {
			this.setupDays(this.days);
		}
	},
	/**
		Sets up days of the week from first day to last day.
		Initially, SUN is the first day and SAT is the last day.
	*/
	setupDays: function(days) {
		for(var i = 0; i < days.length; i++) {
			this.$.days.createComponent({
				kind: "moon.Button",
				classes: "moon-calendar-picker-day",
				disabled: true,
				content: days[i]
			});
		}
	},
	/**
		Populates SimplePicker with months of the year, from JAN to DEC.
	*/
	setupSimplePicker: function() {
		var months = this.months;
		this.$.simplePicker.addClass("moon-simple-picker-button-bold");
		for (var i = 0; i < 12; i++) {
			this.$.simplePicker.createComponent(
				{content: months[i], classes: "picker-content"}
			);
		}
	},
	/**
		Compose calendar with number of calendarDate
	*/
	setupCalendar: function() {
		if (!this.$.dates.controls.length) {
			for (var i = 1; i <= this.maxWeeks * 7; i++) {
				this.$.dates.createComponent({kind: "moon.CalendarPickerDate"});
			}
		}
	},
	parseDate: function() {
		if (this._tf) {
			return this._tf.format(new ilib.Date.GregDate({unixtime: this.value.getTime(), timezone:"UTC"}));
		} else {
			return this.months[this.value.getMonth()] + " " + this.value.getDate() + ", " + this.value.getFullYear();
		}
	},
	/**
		Sets up the first week of this month.
		Before the first day of this month, days from the previous month will be
		used to fill the calendar.
	*/
	updatePrevMonth: function() {
		var value = this.value;
		var dt = new Date(value.getFullYear(), value.getMonth(), value.getDate());
		dt.setDate(0);
		var thisYear = dt.getFullYear(),
			datesOfPrevMonth = dt.getDate(),
			dayOfLastDate = dt.getDay() - this.firstDayOfWeek,
			prevMonth = dt.getMonth();
		if (dayOfLastDate < 0) {
			dayOfLastDate += 7;
		}
		if (dayOfLastDate !== 6) {
			var dates = this.$.dates.getControls();
			for (var i = 0; i <= dayOfLastDate; i++) {
				dates[i].setValue(new Date(thisYear, prevMonth, datesOfPrevMonth - dayOfLastDate + i));
				dates[i].setColor(1);
			}
			return i;
		}
		return 0;
	},
	/**
		Sets up the last week of this month.
		After the last day of this month, days from the next month will be used to
		fill the calendar.
	*/
	updateNextMonth: function(startIndex) {
		var value = this.value;
		var dt = new Date(value.getFullYear(), value.getMonth(), value.getDate());
		dt.setMonth(dt.getMonth() + 1);
		var thisYear = dt.getFullYear(),
			nextMonth = dt.getMonth();
		var dates = this.$.dates.getControls();
		for (var i = 0; i < this.$.dates.controls.length - startIndex; i++) {
			dates[startIndex + i].setValue(new Date(thisYear, nextMonth, i + 1));
			dates[startIndex + i].setColor(1);
		}
	},
	updateDates: function() {
		var datesOfPrevMonth = this.updatePrevMonth();

		var thisYear = this.value.getFullYear(),
			thisMonth = this.value.getMonth();
		var	monthLength = this.getMonthLength(thisYear, thisMonth);
		var dates = this.$.dates.getControls();
		for (var i = 0; i < monthLength; i++) {
			dates[datesOfPrevMonth + i].setValue(new Date(thisYear, thisMonth, i + 1));
			dates[datesOfPrevMonth + i].setColor(0);
		}
		this.$.dates.setActive(dates[datesOfPrevMonth - 1 + this.value.getDate()]);
		this.updateNextMonth(datesOfPrevMonth + monthLength);
	},
	setYear: function(newYear) {
		var value = this.value,
			newValue,
			newMonthLength = this.getMonthLength(newYear, value.getMonth());
		if(newMonthLength < value.getDate()) {
			newValue = new Date(newYear, value.getMonth(), newMonthLength);
		} else {
			newValue = new Date(newYear, value.getMonth(), value.getDate());
		}
		this.setValue(newValue);
	},
	setMonth: function(newMonth) {
		var value = this.value,
			newValue,
			newMonthLength = this.getMonthLength(value.getFullYear(), newMonth - 1);
		if(newMonthLength < value.getDate()) {
			newValue = new Date(value.getFullYear(), newMonth - 1, newMonthLength);
		} else {
			newValue = new Date(value.getFullYear(), newMonth - 1, value.getDate());
		}
		this.setValue(newValue);
	},
	setDate: function(newDate) {
		var value = this.value,
			newValue,
			monthLength = this.getMonthLength(value.getFullYear(), value.getMonth());
		if(monthLength < newDate) {
			newValue = new Date(value.getFullYear(), value.getMonth(), monthLength);
		} else {
			newValue = new Date(value.getFullYear(), value.getMonth(), newDate);
		}
		this.setValue(newValue);
	},
	selectDate: function(inSender, inEvent) {
		if (inEvent.originator.owner.kind == "moon.CalendarPickerDate") {
			var newValue = inEvent.originator.owner.value;
			this.setValue(newValue);
		}
		return true;
	},
	/**
		Returns number of days in a particular month/year.
		@param inYear
		@param inMonth
		@return Number of dates in given year and month
	*/
	getMonthLength: function(inYear, inMonth) {
		if (typeof ilib !== "undefined") {
			var d = ilib.Date.newInstance({unixtime: this.value.getTime()});
			var cal = ilib.Cal.newInstance({name: d.getCalendar()});
			return cal.getMonLength(inMonth, inYear);
		} else {
			return 32 - new Date(inYear, inMonth, 32).getDate();
		}
	},
	/**
		Updates calendar when value of DatePicker changes.
	*/
	updateSimplePicker: function(inSender, inEvent) {
		//* Avoid onChange events coming from itself
		if (inEvent && inEvent.originator == this || inEvent.originator.kind == "Selection") {
			return;
		}
		var value = this.value,
			month = this.$.simplePicker.getSelectedIndex();
		//* Determine whether calender need to redraw or not
		if (month != this.value.getMonth()) {
			this.setValue(new Date(value.getFullYear(), month, value.getDate()));
		} else {
			this.value.setYear(value.getFullYear());
			this.value.setMonth(month);
			this.value.setDate(value.getDate());
		}
		return true;
	},
	localeChanged: function() {
		if (typeof ilib !== "undefined") {
			this.ilibLocaleInfo = new ilib.LocaleInfo(this.locale);
		}
		this.refresh();
		this.doChange({value: this.value});
	},
	valueChanged: function(inOld) {
		if (this.$.simplePicker.getSelectedIndex() != this.value.getMonth()) {
			this.$.simplePicker.setSelectedIndex(this.value.getMonth());
		}
		this.updateDates();
		if (this.value) {
			this.doChange({value: this.value});
		}
	},
	/**
		Sometimes first day of week is channged based on locale changing.
		In this case, destroy day label and reconsturct it.
		Create new ilib.Date instance with time of given day, and get Gregorian
		date instance that represents the first date of the week.

	*/
	firstDayOfWeekChanged: function() {
		this.$.days.destroyClientControls();

		var d = ilib.Date.newInstance({unixtime: this.value.getTime()});
		var firstDate = d.onOrBefore(this.firstDayOfWeek);
		var days = [];
		var firstTime = firstDate.getTime();	//get unix time
		for(var i = 0; i < 7; i++) {
			var date = ilib.Date.newInstance({unixtime: i*(24*60*60*1000) + firstTime});
			days.push(this._tf.format(date));
		}
		this.days = days;
		this.setupDays(this.days);
		this.updateDates();
	},
	refresh: function(){
		this.destroyClientControls();
		this.initDefaults();
		this.render();
	}
});<commit_msg>GF-5466: Rename method and property to make clear<commit_after>/**
	_moon.CalendarPicker_ is a control that displays a monthly calendar, with the
	month name at the top and a grid of days, grouped into rows by week, below.

	The header buttons are used to navigate to the desired month; the desired day
	is selected by tapping on it.

	{kind: "moon.CalendarPicker", content: "Calendar Title"}
*/
enyo.kind({
	name: "moon.CalendarPickerDate",
	kind: "moon.Button",
	small: true,
	marquee: false,
	classes: "moon-calendar-picker-date enyo-unselectable",
	published: {
		value: null,
		color: 0
	},
	create: function() {
		this.inherited(arguments);
		if (typeof ilib !== "undefined") {
			this._tf = new ilib.DateFmt({
				type: "date",	//only format the date component, not the time
				date: "d",		//'d' is the date of month
				length: "short"	//it uses 2 chars to abbreviate properly
			});
		}
	},
	colorChanged: function(inOld) {
		if (this.color) {
			this.addClass("moon-calendar-picker-date-shadow");
		} else {
			this.removeClass("moon-calendar-picker-date-shadow");
		}
	},
	valueChanged: function() {
		if (typeof ilib !== "undefined") {
			var date = ilib.Date.newInstance({unixtime: (this.value.getDate() - 1) * (24*60*60*1000)});
			this.setContent(this._tf.format(date));
		} else {
			this.setContent(this.value.getDate());
		}
	}
});

enyo.kind({
	name: "moon.CalendarPicker",
	classes: "moon-calendar-picker",
	events: {
		/**
			Fires when the date changes.

			_inEvent.name_ contains the name of this control.

			_inEvent.value_ contains a standard JavaScript Date object representing
			the current date.
		*/
		onChange: ""
	},
	handlers: {
		ontap: "selectDate"
	},
	published: {
		/**
			ilib locale info instance. It gives information about the paarticular locale.
		*/
		ilibLocaleInfo: null,
		/**
			Current locale used for formatting. May be set after the control is
			created, in which case the control will be updated to reflect the
			new value.
		*/
		locale: "en_us",
		/**
			The current Date object. When a Date object is passed to _setValue_,
			the control is updated to reflect the new value. _getValue_ returns
			a Date object.
		*/
		value: null,
		/**
			The day of week that starts weeks in current locale.
			As a default, Sunday is the first day of week.
		*/
		firstDayOfWeek: 0,
		/**
			The maximum number of weeks to display in a screen.
			If this value is greater than 9, dates two months in the future may be
			shown. Unexpected input may result in errors.
		*/
		maxWeeks: 6,
		months: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
		days: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
	},
	components: [
		{name: "monthPicker", kind: "moon.SimplePicker"},
		{name: "days", kind: "enyo.Group"},
		{name: "dates", kind: "enyo.Group"}
	],
	create: function() {
		this.inherited(arguments);
		this.initMonthPicker();
		this.initCalendar();

		if (typeof ilib !== "undefined") {
			this._tf = new ilib.DateFmt({
				type: "date",	//only format the date component, not the time
				date: "w",		//'w' is the day of the week
				length: "short"	//it uses 2 chars to abbreviate properly
			});

			this.ilibLocaleInfo = new ilib.LocaleInfo();
			this.setLocale(this.ilibLocaleInfo.locale);
		} else {
			this.initDefaults();
		}
	},
	initDefaults: function() {
		this.setValue(this.value || new Date());
		//Attempt to use the ilib lib (assuming that it is loaded)
		if (typeof ilib !== "undefined") {
			var dayOfWeek = this.ilibLocaleInfo.getFirstDayOfWeek();
			this.setFirstDayOfWeek(dayOfWeek);
		} else {
			this.setupDays(this.days);
		}
	},
	/**
		Sets up days of the week from first day to last day.
		Initially, SUN is the first day and SAT is the last day.
	*/
	setupDays: function(days) {
		for(var i = 0; i < days.length; i++) {
			this.$.days.createComponent({
				kind: "moon.Button",
				classes: "moon-calendar-picker-day",
				disabled: true,
				content: days[i]
			});
		}
	},
	/**
		Populates SimplePicker with months of the year, from JAN to DEC.
	*/
	initMonthPicker: function() {
		var months = this.months;
		this.$.monthPicker.addClass("moon-simple-picker-button-bold");
		for (var i = 0; i < 12; i++) {
			this.$.monthPicker.createComponent(
				{content: months[i], classes: "picker-content"}
			);
		}
	},
	/**
		Compose calendar with number of calendarDate
	*/
	initCalendar: function() {
		if (!this.$.dates.controls.length) {
			for (var i = 1; i <= this.maxWeeks * 7; i++) {
				this.$.dates.createComponent({kind: "moon.CalendarPickerDate"});
			}
		}
	},
	parseDate: function() {
		if (this._tf) {
			return this._tf.format(new ilib.Date.GregDate({unixtime: this.value.getTime(), timezone:"UTC"}));
		} else {
			return this.months[this.value.getMonth()] + " " + this.value.getDate() + ", " + this.value.getFullYear();
		}
	},
	/**
		Sets up the first week of this month.
		Before the first day of this month, days from the previous month will be
		used to fill the calendar.
	*/
	updatePrevMonth: function() {
		var value = this.value;
		var dt = new Date(value.getFullYear(), value.getMonth(), value.getDate());
		dt.setDate(0);
		var thisYear = dt.getFullYear(),
			datesOfPrevMonth = dt.getDate(),
			dayOfLastDate = dt.getDay() - this.firstDayOfWeek,
			prevMonth = dt.getMonth();
		if (dayOfLastDate < 0) {
			dayOfLastDate += 7;
		}
		if (dayOfLastDate !== 6) {
			var dates = this.$.dates.getControls();
			for (var i = 0; i <= dayOfLastDate; i++) {
				dates[i].setValue(new Date(thisYear, prevMonth, datesOfPrevMonth - dayOfLastDate + i));
				dates[i].setColor(1);
			}
			return i;
		}
		return 0;
	},
	/**
		Sets up the last week of this month.
		After the last day of this month, days from the next month will be used to
		fill the calendar.
	*/
	updateNextMonth: function(startIndex) {
		var value = this.value;
		var dt = new Date(value.getFullYear(), value.getMonth(), value.getDate());
		dt.setMonth(dt.getMonth() + 1);
		var thisYear = dt.getFullYear(),
			nextMonth = dt.getMonth();
		var dates = this.$.dates.getControls();
		for (var i = 0; i < this.$.dates.controls.length - startIndex; i++) {
			dates[startIndex + i].setValue(new Date(thisYear, nextMonth, i + 1));
			dates[startIndex + i].setColor(1);
		}
	},
	updateDates: function() {
		var datesOfPrevMonth = this.updatePrevMonth();

		var thisYear = this.value.getFullYear(),
			thisMonth = this.value.getMonth();
		var	monthLength = this.getMonthLength(thisYear, thisMonth);
		var dates = this.$.dates.getControls();
		for (var i = 0; i < monthLength; i++) {
			dates[datesOfPrevMonth + i].setValue(new Date(thisYear, thisMonth, i + 1));
			dates[datesOfPrevMonth + i].setColor(0);
		}
		this.$.dates.setActive(dates[datesOfPrevMonth - 1 + this.value.getDate()]);
		this.updateNextMonth(datesOfPrevMonth + monthLength);
	},
	setYear: function(newYear) {
		var value = this.value,
			newValue,
			newMonthLength = this.getMonthLength(newYear, value.getMonth());
		if(newMonthLength < value.getDate()) {
			newValue = new Date(newYear, value.getMonth(), newMonthLength);
		} else {
			newValue = new Date(newYear, value.getMonth(), value.getDate());
		}
		this.setValue(newValue);
	},
	setMonth: function(newMonth) {
		var value = this.value,
			newValue,
			newMonthLength = this.getMonthLength(value.getFullYear(), newMonth - 1);
		if(newMonthLength < value.getDate()) {
			newValue = new Date(value.getFullYear(), newMonth - 1, newMonthLength);
		} else {
			newValue = new Date(value.getFullYear(), newMonth - 1, value.getDate());
		}
		this.setValue(newValue);
	},
	setDate: function(newDate) {
		var value = this.value,
			newValue,
			monthLength = this.getMonthLength(value.getFullYear(), value.getMonth());
		if(monthLength < newDate) {
			newValue = new Date(value.getFullYear(), value.getMonth(), monthLength);
		} else {
			newValue = new Date(value.getFullYear(), value.getMonth(), newDate);
		}
		this.setValue(newValue);
	},
	selectDate: function(inSender, inEvent) {
		if (inEvent.originator.owner.kind == "moon.CalendarPickerDate") {
			var newValue = inEvent.originator.owner.value;
			this.setValue(newValue);
		}
		return true;
	},
	/**
		Returns number of days in a particular month/year.
		@param inYear
		@param inMonth
		@return Number of dates in given year and month
	*/
	getMonthLength: function(inYear, inMonth) {
		if (typeof ilib !== "undefined") {
			var d = ilib.Date.newInstance({unixtime: this.value.getTime()});
			var cal = ilib.Cal.newInstance({name: d.getCalendar()});
			return cal.getMonLength(inMonth, inYear);
		} else {
			return 32 - new Date(inYear, inMonth, 32).getDate();
		}
	},
	localeChanged: function() {
		if (typeof ilib !== "undefined") {
			this.ilibLocaleInfo = new ilib.LocaleInfo(this.locale);
		}
		this.refresh();
		this.doChange({value: this.value});
	},
	valueChanged: function(inOld) {
		if (this.$.monthPicker.getSelectedIndex() != this.value.getMonth()) {
			this.$.monthPicker.setSelectedIndex(this.value.getMonth());
		}
		this.updateDates();
		if (this.value) {
			this.doChange({value: this.value});
		}
	},
	/**
		Sometimes first day of week is channged based on locale changing.
		In this case, destroy day label and reconsturct it.
		Create new ilib.Date instance with time of given day, and get Gregorian
		date instance that represents the first date of the week.

	*/
	firstDayOfWeekChanged: function() {
		this.$.days.destroyClientControls();

		var d = ilib.Date.newInstance({unixtime: this.value.getTime()});
		var firstDate = d.onOrBefore(this.firstDayOfWeek);
		var days = [];
		var firstTime = firstDate.getTime();	//get unix time
		for(var i = 0; i < 7; i++) {
			var date = ilib.Date.newInstance({unixtime: i*(24*60*60*1000) + firstTime});
			days.push(this._tf.format(date));
		}
		this.days = days;
		this.setupDays(this.days);
		this.updateDates();
	},
	refresh: function(){
		this.destroyClientControls();
		this.initDefaults();
		this.render();
	}
});<|endoftext|>


<commit_before>/**
	_moon.CalendarPicker_ is a control that displays a monthly calendar, with the
	month name at the top and a grid of days, grouped into rows by week, below.

	The header buttons are used to navigate to the desired month; the desired day
	is selected by tapping on it.

	{kind: "moon.CalendarPicker", content: "Calendar Title"}
*/
enyo.kind({
	name: "moon.CalendarPickerDate",
	kind: "moon.Button",
	small: true,
	marquee: false,
	classes: "moon-calendar-picker-date enyo-unselectable",
	published: {
		value: null,
		color: 0
	},
	colorChanged: function(inOld) {
		if (this.color) {
			this.addClass("moon-calendar-picker-date-shadow");
		} else {
			this.removeClass("moon-calendar-picker-date-shadow");
		}
	},
	valueChanged: function() {
		this.setContent(this.value.getDate());
	}
});

enyo.kind({
	name: "moon.CalendarPicker",
	classes: "moon-calendar-picker",
	events: {
		/**
			Fires when the date changes.

			_inEvent.name_ contains the name of this control.

			_inEvent.value_ contains a standard JavaScript Date object representing
			the current date.
		*/
		onChange: ""
	},
	handlers: {
		ontap: "selectDate",
		//* Handler for _onChange_ events coming from constituent controls
		onChange: "updateSimplePicker"
	},
	published: {
		/**
			Current locale used for formatting. May be set after the control is
			created, in which case the control will be updated to reflect the
			new value.
		*/
		locale: "en_us",
		/**
			The current Date object. When a Date object is passed to _setValue_,
			the control is updated to reflect the new value. _getValue_ returns
			a Date object.
		*/
		value: null,
		/**
			The day of week that starts weeks in current locale.
			As a default, Sunday is the first day of week.
		*/
		firstDayOfWeek: 0,
		/**
			The maximum number of weeks to display in a screen.
			If this value is greater than 9, dates two months in the future may be
			shown. Unexpected input may result in errors.
		*/
		maxWeeks: 6,
		months: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
		days: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
	},
	components: [
		{name: "simplePicker", kind: "moon.SimplePicker", classes: "moon-calendar-picker-simplepicker"},
		{name: "days", kind: "enyo.Group"},
		{name: "dates", kind: "enyo.Group"}
	],
	create: function() {
		this.inherited(arguments);
		this.setupSimplePicker();
		this.setupCalendar();

		if (typeof ilib !== "undefined") {
			this._tf = new ilib.DateFmt({
				type: "date",	//only format the date component, not the time
				date: "w",		//'w' is the day of the week
				length: "short"	//it uses 2 chars to abbreviate properly
			});

			this.localeInfo = new ilib.LocaleInfo();
			this.setLocale(this.localeInfo.locale);
		} else {
			this.initDefaults();
		}
	},
	initDefaults: function() {
		this.setValue(this.value || new Date());
		//Attempt to use the ilib lib (assuming that it is loaded)
		if (typeof ilib !== "undefined") {
			var dayOfWeek = this.localeInfo.getFirstDayOfWeek();
			this.setFirstDayOfWeek(dayOfWeek);
		} else {
			this.setupDays(this.days);
		}
	},
	/**
		Sets up days of the week from first day to last day.
		Initially, SUN is the first day and SAT is the last day.
	*/
	setupDays: function(days) {
		for(var i = 0; i < days.length; i++) {
			this.$.days.createComponent({
				kind: "moon.Button",
				classes: "moon-calendar-picker-day",
				disabled: true,
				content: days[i]
			});
		}
	},
	/**
		Populates SimplePicker with months of the year, from JAN to DEC.
	*/
	setupSimplePicker: function() {
		var months = this.months;
		this.$.simplePicker.addClass("moon-simple-picker-button-bold");
		for (var i = 0; i < 12; i++) {
			this.$.simplePicker.createComponent(
				{content: months[i], classes: "picker-content"}
			);
		}
	},
	/**
		Compose calendar with number of calendarDate
	*/
	setupCalendar: function() {
		if (!this.$.dates.controls.length) {
			for (var i = 1; i <= this.maxWeeks * 7; i++) {
				this.$.dates.createComponent({kind: "moon.CalendarPickerDate"});
			}
		}
	},
	parseDate: function() {
		if (this._tf) {
			return this._tf.format(new ilib.Date.GregDate({unixtime: this.value.getTime(), timezone:"UTC"}));
		} else {
			return this.months[this.value.getMonth()] + " " + this.value.getDate() + ", " + this.value.getFullYear();
		}
	},
	/**
		Sets up the first week of this month.
		Before the first day of this month, days from the previous month will be
		used to fill the calendar.
	*/
	updatePrevMonth: function() {
		var value = this.value;
		var dt = new Date(value.getFullYear(), value.getMonth(), value.getDate());
		dt.setDate(0);
		var thisYear = dt.getFullYear(),
			datesOfPrevMonth = dt.getDate(),
			dayOfLastDate = dt.getDay() - this.firstDayOfWeek,
			prevMonth = dt.getMonth();
		if (dayOfLastDate < 0) {
			dayOfLastDate += 7;
		}
		if (dayOfLastDate !== 6) {
			var dates = this.$.dates.getControls();
			for (var i = 0; i <= dayOfLastDate; i++) {
				dates[i].setValue(new Date(thisYear, prevMonth, datesOfPrevMonth - dayOfLastDate + i));
				dates[i].setColor(1);
			}
			return i;
		}
		return 0;
	},
	/**
		Sets up the last week of this month.
		After the last day of this month, days from the next month will be used to
		fill the calendar.
	*/
	updateNextMonth: function(startIndex) {
		var value = this.value;
		var dt = new Date(value.getFullYear(), value.getMonth(), value.getDate());
		dt.setMonth(dt.getMonth() + 1);
		var thisYear = dt.getFullYear(),
			nextMonth = dt.getMonth();
		var dates = this.$.dates.getControls();
		for (var i = 0; i < this.$.dates.controls.length - startIndex; i++) {
			dates[startIndex + i].setValue(new Date(thisYear, nextMonth, i + 1));
			dates[startIndex + i].setColor(1);
		}
	},
	updateDates: function() {
		var datesOfPrevMonth = this.updatePrevMonth();

		var thisYear = this.value.getFullYear(),
			thisMonth = this.value.getMonth();
		var	monthLength = this.getMonthLength(thisYear, thisMonth);
		var dates = this.$.dates.getControls();
		for (var i = 0; i < monthLength; i++) {
			dates[datesOfPrevMonth + i].setValue(new Date(thisYear, thisMonth, i + 1));
			dates[datesOfPrevMonth + i].setColor(0);
		}
		this.$.dates.setActive(dates[datesOfPrevMonth - 1 + this.value.getDate()]);
		this.updateNextMonth(datesOfPrevMonth + monthLength);
	},
	setYear: function(newYear) {
		var value = this.value,
			newValue,
			newMonthLength = this.getMonthLength(newYear, value.getMonth());
		if(newMonthLength < value.getDate()) {
			newValue = new Date(newYear, value.getMonth(), newMonthLength);
		} else {
			newValue = new Date(newYear, value.getMonth(), value.getDate());
		}
		this.setValue(newValue);
	},
	setMonth: function(newMonth) {
		var value = this.value,
			newValue,
			newMonthLength = this.getMonthLength(value.getFullYear(), newMonth - 1);
		if(newMonthLength < value.getDate()) {
			newValue = new Date(value.getFullYear(), newMonth - 1, newMonthLength);
		} else {
			newValue = new Date(value.getFullYear(), newMonth - 1, value.getDate());
		}
		this.setValue(newValue);
	},
	setDate: function(newDate) {
		var value = this.value,
			newValue,
			monthLength = this.getMonthLength(value.getFullYear(), value.getMonth());
		if(monthLength < newDate) {
			newValue = new Date(value.getFullYear(), value.getMonth(), monthLength);
		} else {
			newValue = new Date(value.getFullYear(), value.getMonth(), newDate);
		}
		this.setValue(newValue);
	},
	selectDate: function(inSender, inEvent) {
		if (inEvent.originator.owner.kind == "moon.CalendarPickerDate") {
			var newValue = inEvent.originator.owner.value;
			this.setValue(newValue);
		}
		return true;
	},
	/**
		Returns number of days in a particular month/year.
	*/
	getMonthLength: function(inYear, inMonth) {
		return 32 - new Date(inYear, inMonth, 32).getDate();
	},
	/**
		Updates calendar when value of DatePicker changes.
	*/
	updateSimplePicker: function(inSender, inEvent) {
		//* Avoid onChange events coming from itself
		if (inEvent && inEvent.originator == this || inEvent.originator.kind == "Selection") {
			return;
		}
		var value = this.value,
			month = this.$.simplePicker.getSelectedIndex();
		//* Determine whether calender need to redraw or not
		if (month != this.value.getMonth()) {
			this.setValue(new Date(value.getFullYear(), month, value.getDate()));
		} else {
			this.value.setYear(value.getFullYear());
			this.value.setMonth(month);
			this.value.setDate(value.getDate());
		}
		return true;
	},
	localeChanged: function() {
		this.refresh();
		this.doChange({value: this.value});
	},
	valueChanged: function(inOld) {
		if (this.$.simplePicker.getSelectedIndex() != this.value.getMonth()) {
			this.$.simplePicker.setSelectedIndex(this.value.getMonth());
		}
		this.updateDates();
		if (this.value) {
			this.doChange({value: this.value});
		}
	},
	/**
		Sometimes first day of week is channged based on locale changing.
		In this case, destroy day label and reconsturct it.
		Create new ilib.Date instance with time of given day, and get Gregorian
		date instance that represents the first date of the week.

	*/
	firstDayOfWeekChanged: function() {
		this.$.days.destroyClientControls();

		var d = ilib.Date.newInstance({unixtime: this.value.getTime()});
		var firstDate = d.onOrBefore(this.firstDayOfWeek);
		var days = [];
		var firstTime = firstDate.getTime();	//get unix time
		for(var i = 0; i < 7; i++) {
			var date = ilib.Date.newInstance({unixtime: i*(24*60*60*1000) + firstTime});
			days.push(this._tf.format(date));
		}
		this.days = days;
		this.setupDays(this.days);
		this.updateDates();
	},
	refresh: function(){
		this.destroyClientControls();
		this.initDefaults();
		this.render();
	}
});<commit_msg>GF-5466: Get month length from ilib<commit_after>/**
	_moon.CalendarPicker_ is a control that displays a monthly calendar, with the
	month name at the top and a grid of days, grouped into rows by week, below.

	The header buttons are used to navigate to the desired month; the desired day
	is selected by tapping on it.

	{kind: "moon.CalendarPicker", content: "Calendar Title"}
*/
enyo.kind({
	name: "moon.CalendarPickerDate",
	kind: "moon.Button",
	small: true,
	marquee: false,
	classes: "moon-calendar-picker-date enyo-unselectable",
	published: {
		value: null,
		color: 0
	},
	colorChanged: function(inOld) {
		if (this.color) {
			this.addClass("moon-calendar-picker-date-shadow");
		} else {
			this.removeClass("moon-calendar-picker-date-shadow");
		}
	},
	valueChanged: function() {
		this.setContent(this.value.getDate());
	}
});

enyo.kind({
	name: "moon.CalendarPicker",
	classes: "moon-calendar-picker",
	events: {
		/**
			Fires when the date changes.

			_inEvent.name_ contains the name of this control.

			_inEvent.value_ contains a standard JavaScript Date object representing
			the current date.
		*/
		onChange: ""
	},
	handlers: {
		ontap: "selectDate",
		//* Handler for _onChange_ events coming from constituent controls
		onChange: "updateSimplePicker"
	},
	published: {
		/**
			ilib locale info instance. It gives information about the paarticular locale.
		*/
		ilibLocaleInfo: null,
		/**
			Current locale used for formatting. May be set after the control is
			created, in which case the control will be updated to reflect the
			new value.
		*/
		locale: "en_us",
		/**
			The current Date object. When a Date object is passed to _setValue_,
			the control is updated to reflect the new value. _getValue_ returns
			a Date object.
		*/
		value: null,
		/**
			The day of week that starts weeks in current locale.
			As a default, Sunday is the first day of week.
		*/
		firstDayOfWeek: 0,
		/**
			The maximum number of weeks to display in a screen.
			If this value is greater than 9, dates two months in the future may be
			shown. Unexpected input may result in errors.
		*/
		maxWeeks: 6,
		months: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
		days: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
	},
	components: [
		{name: "simplePicker", kind: "moon.SimplePicker", classes: "moon-calendar-picker-simplepicker"},
		{name: "days", kind: "enyo.Group"},
		{name: "dates", kind: "enyo.Group"}
	],
	create: function() {
		this.inherited(arguments);
		this.setupSimplePicker();
		this.setupCalendar();

		if (typeof ilib !== "undefined") {
			this._tf = new ilib.DateFmt({
				type: "date",	//only format the date component, not the time
				date: "w",		//'w' is the day of the week
				length: "short"	//it uses 2 chars to abbreviate properly
			});

			this.ilibLocaleInfo = new ilib.LocaleInfo();
			this.setLocale(this.ilibLocaleInfo.locale);
		} else {
			this.initDefaults();
		}
	},
	initDefaults: function() {
		this.setValue(this.value || new Date());
		//Attempt to use the ilib lib (assuming that it is loaded)
		if (typeof ilib !== "undefined") {
			var dayOfWeek = this.ilibLocaleInfo.getFirstDayOfWeek();
			this.setFirstDayOfWeek(dayOfWeek);
		} else {
			this.setupDays(this.days);
		}
	},
	/**
		Sets up days of the week from first day to last day.
		Initially, SUN is the first day and SAT is the last day.
	*/
	setupDays: function(days) {
		for(var i = 0; i < days.length; i++) {
			this.$.days.createComponent({
				kind: "moon.Button",
				classes: "moon-calendar-picker-day",
				disabled: true,
				content: days[i]
			});
		}
	},
	/**
		Populates SimplePicker with months of the year, from JAN to DEC.
	*/
	setupSimplePicker: function() {
		var months = this.months;
		this.$.simplePicker.addClass("moon-simple-picker-button-bold");
		for (var i = 0; i < 12; i++) {
			this.$.simplePicker.createComponent(
				{content: months[i], classes: "picker-content"}
			);
		}
	},
	/**
		Compose calendar with number of calendarDate
	*/
	setupCalendar: function() {
		if (!this.$.dates.controls.length) {
			for (var i = 1; i <= this.maxWeeks * 7; i++) {
				this.$.dates.createComponent({kind: "moon.CalendarPickerDate"});
			}
		}
	},
	parseDate: function() {
		if (this._tf) {
			return this._tf.format(new ilib.Date.GregDate({unixtime: this.value.getTime(), timezone:"UTC"}));
		} else {
			return this.months[this.value.getMonth()] + " " + this.value.getDate() + ", " + this.value.getFullYear();
		}
	},
	/**
		Sets up the first week of this month.
		Before the first day of this month, days from the previous month will be
		used to fill the calendar.
	*/
	updatePrevMonth: function() {
		var value = this.value;
		var dt = new Date(value.getFullYear(), value.getMonth(), value.getDate());
		dt.setDate(0);
		var thisYear = dt.getFullYear(),
			datesOfPrevMonth = dt.getDate(),
			dayOfLastDate = dt.getDay() - this.firstDayOfWeek,
			prevMonth = dt.getMonth();
		if (dayOfLastDate < 0) {
			dayOfLastDate += 7;
		}
		if (dayOfLastDate !== 6) {
			var dates = this.$.dates.getControls();
			for (var i = 0; i <= dayOfLastDate; i++) {
				dates[i].setValue(new Date(thisYear, prevMonth, datesOfPrevMonth - dayOfLastDate + i));
				dates[i].setColor(1);
			}
			return i;
		}
		return 0;
	},
	/**
		Sets up the last week of this month.
		After the last day of this month, days from the next month will be used to
		fill the calendar.
	*/
	updateNextMonth: function(startIndex) {
		var value = this.value;
		var dt = new Date(value.getFullYear(), value.getMonth(), value.getDate());
		dt.setMonth(dt.getMonth() + 1);
		var thisYear = dt.getFullYear(),
			nextMonth = dt.getMonth();
		var dates = this.$.dates.getControls();
		for (var i = 0; i < this.$.dates.controls.length - startIndex; i++) {
			dates[startIndex + i].setValue(new Date(thisYear, nextMonth, i + 1));
			dates[startIndex + i].setColor(1);
		}
	},
	updateDates: function() {
		var datesOfPrevMonth = this.updatePrevMonth();

		var thisYear = this.value.getFullYear(),
			thisMonth = this.value.getMonth();
		var	monthLength = this.getMonthLength(thisYear, thisMonth);
		var dates = this.$.dates.getControls();
		for (var i = 0; i < monthLength; i++) {
			dates[datesOfPrevMonth + i].setValue(new Date(thisYear, thisMonth, i + 1));
			dates[datesOfPrevMonth + i].setColor(0);
		}
		this.$.dates.setActive(dates[datesOfPrevMonth - 1 + this.value.getDate()]);
		this.updateNextMonth(datesOfPrevMonth + monthLength);
	},
	setYear: function(newYear) {
		var value = this.value,
			newValue,
			newMonthLength = this.getMonthLength(newYear, value.getMonth());
		if(newMonthLength < value.getDate()) {
			newValue = new Date(newYear, value.getMonth(), newMonthLength);
		} else {
			newValue = new Date(newYear, value.getMonth(), value.getDate());
		}
		this.setValue(newValue);
	},
	setMonth: function(newMonth) {
		var value = this.value,
			newValue,
			newMonthLength = this.getMonthLength(value.getFullYear(), newMonth - 1);
		if(newMonthLength < value.getDate()) {
			newValue = new Date(value.getFullYear(), newMonth - 1, newMonthLength);
		} else {
			newValue = new Date(value.getFullYear(), newMonth - 1, value.getDate());
		}
		this.setValue(newValue);
	},
	setDate: function(newDate) {
		var value = this.value,
			newValue,
			monthLength = this.getMonthLength(value.getFullYear(), value.getMonth());
		if(monthLength < newDate) {
			newValue = new Date(value.getFullYear(), value.getMonth(), monthLength);
		} else {
			newValue = new Date(value.getFullYear(), value.getMonth(), newDate);
		}
		this.setValue(newValue);
	},
	selectDate: function(inSender, inEvent) {
		if (inEvent.originator.owner.kind == "moon.CalendarPickerDate") {
			var newValue = inEvent.originator.owner.value;
			this.setValue(newValue);
		}
		return true;
	},
	/**
		Returns number of days in a particular month/year.
		@param inYear
		@param inMonth
		@return Number of dates in given year and month
	*/
	getMonthLength: function(inYear, inMonth) {
		if (typeof ilib !== "undefined") {
			var d = ilib.Date.newInstance({unixtime: this.value.getTime()});
			var cal = ilib.Cal.newInstance({name: d.getCalendar()});
			return cal.getMonLength(inMonth, inYear);
		} else {
			return 32 - new Date(inYear, inMonth, 32).getDate();
		}
	},
	/**
		Updates calendar when value of DatePicker changes.
	*/
	updateSimplePicker: function(inSender, inEvent) {
		//* Avoid onChange events coming from itself
		if (inEvent && inEvent.originator == this || inEvent.originator.kind == "Selection") {
			return;
		}
		var value = this.value,
			month = this.$.simplePicker.getSelectedIndex();
		//* Determine whether calender need to redraw or not
		if (month != this.value.getMonth()) {
			this.setValue(new Date(value.getFullYear(), month, value.getDate()));
		} else {
			this.value.setYear(value.getFullYear());
			this.value.setMonth(month);
			this.value.setDate(value.getDate());
		}
		return true;
	},
	localeChanged: function() {
		this.refresh();
		this.doChange({value: this.value});
	},
	valueChanged: function(inOld) {
		if (this.$.simplePicker.getSelectedIndex() != this.value.getMonth()) {
			this.$.simplePicker.setSelectedIndex(this.value.getMonth());
		}
		this.updateDates();
		if (this.value) {
			this.doChange({value: this.value});
		}
	},
	/**
		Sometimes first day of week is channged based on locale changing.
		In this case, destroy day label and reconsturct it.
		Create new ilib.Date instance with time of given day, and get Gregorian
		date instance that represents the first date of the week.

	*/
	firstDayOfWeekChanged: function() {
		this.$.days.destroyClientControls();

		var d = ilib.Date.newInstance({unixtime: this.value.getTime()});
		var firstDate = d.onOrBefore(this.firstDayOfWeek);
		var days = [];
		var firstTime = firstDate.getTime();	//get unix time
		for(var i = 0; i < 7; i++) {
			var date = ilib.Date.newInstance({unixtime: i*(24*60*60*1000) + firstTime});
			days.push(this._tf.format(date));
		}
		this.days = days;
		this.setupDays(this.days);
		this.updateDates();
	},
	refresh: function(){
		this.destroyClientControls();
		this.initDefaults();
		this.render();
	}
});<|endoftext|>


<commit_before>/*
	Class: UI.Button
		Creates button and let you _initEvents events action

	Extend:
		<UI.Control>

	Arguments:
		options

	Options:
		text - (string) Text to show in button
		submit - (boolean) Set to true if you want your button act as a submit button

	Example:
	(start code)
		var button = new UI.Button({
			text        : 'i am a new UI.Button',
			onClick     : { alert('click') }
		}).inject(document.body);
	(end)

	Implied global:
		UI,
		Class,Event

*/

UI.Button = new Class({

	Extends: UI.Control,

	name: 'button',

	options: {
		type: null, // push, file
		element: {
			tag: 'span'
		}
	},

	/*
	Function: _initElement
		private function

		Create a textLabel and call parent method

	Returns:
		(void)

	See also:
		<UI.Control::_initElement>
		<UI.Component::_initElement>
	*/

	_initElement: function(){
		this.parent();
		var opts = this.options;
			type = opts.type;

		if (type === null)
			type = 'icon-text';

		//console.log(type, type.indexOf('icon'));

		if (opts.text && type != 'icon')
			this.element.set('html', opts.text);
		//var text = opts.type.match(/text/g);

		//console.log('title', this.element,  opts.text);
		this.element.set('title', opts.text);

		if ((opts.icon && type.indexOf('icon') > -1) || type == 'file')
			this._initIcon();

		this._initClass();

		if (this.options.clss)
			this.element.addClass(this.options.clss);

		if (opts.type == 'file') {
			this._initFile();
		}
	},

	_initIcon: function() {
		var opts = this.options;

		var tag = 'span';
		if (type == 'file')	tag = 'label';

		var pos = 'top';
		if (type == 'text-icon')
			pos = 'bottom';

		this.icon = new Element(tag, {
			'class': 'button-icon',
			for: 'upload'
		}).inject(this.element, pos);

		this.icon.addClass(opts.icon);
	},

	_initFile: function() {
		var self = this;

		var file = new Element('input', {
			type: 'file',
			name: 'upload',
			id: 'upload'
		}).inject(this.element);

		file.addEvent('change', function(info) {
			//console.log('change', info);
		});

		file.onchange = function(info) {
			var files = this.files;
			console.log(files);
			if (files)
			self.fireEvent('uploadFile', [files]);

		};

		this.addEvent('injected', function() {
			var coord = self.icon.getCoordinates();

			coord.top = '0';
			coord.left = '0';

			file.setStyles(coord);
		});
	},

	_initEvents: function(){
		this.parent();

		var self = this,
			opts = this.options,
			state = opts.state;

		this.element.addEvents({
			mousedown: function(e) {
				self.fireEvent('mousedown');
				e.stop();
			},
			click: function(e){
				e.stopPropagation();
				if (opts.emit && self.state != 'disabled')
					self.fireEvent(opts.emit);
					self.fireEvent('press', opts.emit);

				if (opts.call && self.state != 'disabled')
					opts.call();
			},
			mouseup: function(){
				if (opts.type == 'check') {
					if (self.state == 'checked')
						self.setState(null);
					else self.setState('checked');
				}

			}
		});
	},

	/*
		function : _initClass

			Build the split containers

	*/
	_initClass: function() {
		var opts = this.options;
		//console.log(this.name);

		if (this.options.klss)
			this.element.addClass(this.options.klss);

		if (this.options.type)
			this.element.addClass('type-' + this.options.type);

		this.element.addClass(opts.prefix + this.name);
	}
});

<commit_msg>Add insert to windows list<commit_after>/*
	Class: UI.Button
		Creates button and let you _initEvents events action

	Extend:
		<UI.Control>

	Arguments:
		options

	Options:
		text - (string) Text to show in button
		submit - (boolean) Set to true if you want your button act as a submit button

	Example:
	(start code)
		var button = new UI.Button({
			text        : 'i am a new UI.Button',
			onClick     : { alert('click') }
		}).inject(document.body);
	(end)

	Implied global:
		UI,
		Class,Event

*/

UI.Button = new Class({

	Extends: UI.Control,

	name: 'button',

	options: {
		type: null, // push, file
		element: {
			tag: 'span'
		}
	},

	/*
	Function: _initElement
		private function

		Create a textLabel and call parent method

	Returns:
		(void)

	See also:
		<UI.Control::_initElement>
		<UI.Component::_initElement>
	*/

	_initElement: function(){
		this.parent();
		var opts = this.options;
			type = opts.type;

		if (type === null)
			type = 'icon-text';

		//console.log(type, type.indexOf('icon'));

		if (opts.text && type != 'icon')
			this.element.set('html', opts.text);
		//var text = opts.type.match(/text/g);

		//console.log('title', this.element,  opts.text);
		this.element.set('title', opts.text);

		if ((opts.icon && type.indexOf('icon') > -1) || type == 'file')
			this._initIcon();

		this._initClass();

		if (this.options.clss)
			this.element.addClass(this.options.clss);

		if (opts.type == 'file') {
			this._initFile();
		}
	},

	_initIcon: function() {
		var opts = this.options;

		var tag = 'span';
		if (type == 'file')	tag = 'label';

		var pos = 'top';
		if (type == 'text-icon')
			pos = 'bottom';

		this.icon = new Element(tag, {
			'class': 'button-icon',
			for: 'upload'
		}).inject(this.element, pos);

		this.icon.addClass(opts.icon);
	},

	_initFile: function() {
		var self = this;

		var file = new Element('input', {
			type: 'file',
			name: 'upload',
			id: 'upload'
		}).inject(this.element);

		file.addEvent('change', function(info) {
			//console.log('change', info);
		});

		file.onchange = function(info) {
			var files = this.files;
			//console.log(files);
			if (files)
			self.fireEvent('uploadFile', [files]);

		};

		this.addEvent('injected', function() {
			var coord = self.icon.getCoordinates();

			coord.top = '0';
			coord.left = '0';

			file.setStyles(coord);
		});
	},

	_initEvents: function(){
		this.parent();

		var self = this,
			opts = this.options,
			state = opts.state;

		this.element.addEvents({
			mousedown: function(e) {
				self.fireEvent('mousedown');
				e.stop();
			},
			click: function(e){
				e.stopPropagation();
				if (opts.emit && self.state != 'disabled')
					self.fireEvent(opts.emit);
					self.fireEvent('press', opts.emit);

				if (opts.call && self.state != 'disabled')
					opts.call();
			},
			mouseup: function(){
				if (opts.type == 'check') {
					if (self.state == 'checked')
						self.setState(null);
					else self.setState('checked');
				}

			}
		});
	},

	/*
		function : _initClass

			Build the split containers

	*/
	_initClass: function() {
		var opts = this.options;
		//console.log(this.name);

		if (this.options.klss)
			this.element.addClass(this.options.klss);

		if (this.options.type)
			this.element.addClass('type-' + this.options.type);

		this.element.addClass(opts.prefix + this.name);
	}
});

<|endoftext|>


<commit_before>/**
	_onyx.InputDecorator_ is a control that provides input styling. Any controls
	in the InputDecorator will appear to be inside an area styled as an	input.
	Usually, an InputDecorator surrounds an	onyx.Input.

		{kind: "onyx.InputDecorator", components: [
			{kind: "onyx.Input"}
		]}

	Other controls, such as buttons, may be placed to the right or left of the
	input control, e.g.:

		{kind: "onyx.InputDecorator", components: [
			{kind: "onyx.IconButton", src: "search.png"},
			{kind: "onyx.Input"},
			{kind: "onyx.IconButton", src: "cancel.png"}
		]}

	Note that the InputDecorator fits around the content inside it. If the
	decorator is sized, then its contents will likely need to be sized as well.

		{kind: "onyx.InputDecorator", style: "width: 500px;", components: [
			{kind: "onyx.Input", style: "width: 100%;"}
		]}
*/
enyo.kind({
	name: "onyx.InputDecorator",
	kind: "enyo.ToolDecorator",
	tag: "label",
	classes: "onyx-input-decorator",
	//* @protected
	handlers: {
		onDisabledChange: "disabledChange",
		onfocus: "receiveFocus",
		onblur: "receiveBlur"
	},
	receiveFocus: function() {
		this.addClass("onyx-focused");
	},
	receiveBlur: function() {
		this.removeClass("onyx-focused");
	},
	disabledChange: function(inSender, inEvent) {
		this.addRemoveClass("onyx-disabled", inEvent.originator.disabled);
	}
});<commit_msg>added alwaysLooksFocused property to onyx.InputDecorator<commit_after>/**
	_onyx.InputDecorator_ is a control that provides input styling. Any controls
	in the InputDecorator will appear to be inside an area styled as an	input.
	Usually, an InputDecorator surrounds an	onyx.Input.

		{kind: "onyx.InputDecorator", components: [
			{kind: "onyx.Input"}
		]}

	Other controls, such as buttons, may be placed to the right or left of the
	input control, e.g.:

		{kind: "onyx.InputDecorator", components: [
			{kind: "onyx.IconButton", src: "search.png"},
			{kind: "onyx.Input"},
			{kind: "onyx.IconButton", src: "cancel.png"}
		]}

	Note that the InputDecorator fits around the content inside it. If the
	decorator is sized, then its contents will likely need to be sized as well.

		{kind: "onyx.InputDecorator", style: "width: 500px;", components: [
			{kind: "onyx.Input", style: "width: 100%;"}
		]}
*/
enyo.kind({
    name: "onyx.InputDecorator",
    kind: "enyo.ToolDecorator",
    tag: "label",
    classes: "onyx-input-decorator",
    published:{
        //* Set to true to make the input look focused when it's not.
        alwaysLooksFocused:false
    },
    //* @protected
    handlers: {
        onDisabledChange: "disabledChange",
        onfocus: "receiveFocus",
        onblur: "receiveBlur"
    },
    create:function() {
        this.inherited(arguments);
        this.alwaysLooksFocusedChanged();
    },
    alwaysLooksFocusedChanged:function() {
        if(!this.hasClass("onyx-focused") && this.alwaysLooksFocused) {
            this.addClass("onyx-focused");
        }
    },
    receiveFocus: function() {
        this.addClass("onyx-focused");
    },
    receiveBlur: function() {
        if(!this.alwaysLooksFocused) {
            this.removeClass("onyx-focused");
        }
    },
    disabledChange: function(inSender, inEvent) {
        this.addRemoveClass("onyx-disabled", inEvent.originator.disabled);
    }
});<|endoftext|>


<commit_before>var LooReport = require('../../../../models/loo_report'),
    thunk = require('thunkify'),
    parse = require('co-body'),
    _ = require('lodash'),
    routes = {};

routes.submit_report = {
    handler: function*(){
        var data = yield parse(this);
        data.attribution = this.user.name;
        var validator = new LooReport(data);
        validator.validate = thunk(validator.validate);
        try {
            yield validator.validate();
        } catch (e) {
            if (e.name === 'ValidationError') {
                this.throw(400, _.pluck(e.errors, 'message').join('\n'));
            } else {
                throw e;
            }
        }
        var results = yield LooReport.processReport(data);
        this.status = 201;
        this.set('Location', this.app.url('report', {id: results[0]._id}));
        this.set('Content-Location', this.app.url('loo', {id: results[1]._id}));
    },
    path: '/reports',
    method: 'post'
};

module.exports = routes;<commit_msg>Echo provided data on error<commit_after>var LooReport = require('../../../../models/loo_report'),
    thunk = require('thunkify'),
    parse = require('co-body'),
    _ = require('lodash'),
    routes = {};

routes.submit_report = {
    handler: function*(){
        var data = yield parse(this);
        data.attribution = this.user.name;
        var validator = new LooReport(data);
        validator.validate = thunk(validator.validate);
        try {
            yield validator.validate();
        } catch (e) {
            if (e.name === 'ValidationError') {
                this.throw(400, _.pluck(e.errors, 'message').concat(['Provided: '+JSON.stringify(data, null, '\t')]).join('\n'));
            } else {
                throw e;
            }
        }
        var results = yield LooReport.processReport(data);
        this.status = 201;
        this.set('Location', this.app.url('report', {id: results[0]._id}));
        this.set('Content-Location', this.app.url('loo', {id: results[1]._id}));
    },
    path: '/reports',
    method: 'post'
};

module.exports = routes;<|endoftext|>


<commit_before>angular
	.module("App")
		.controller("packageListController", packageListController )
		.service("packageService", packageService );

function packageListController( $scope, packageService ) {
	function success(obj){
		console.log('Data: ', obj);
		$scope.packages = obj.data;
	}
	function error(err){
		console.log('Erro: ', err);
	}

	packageService
		.getList()
		.then(success, error);

}

function packageService($http) {
	var REQ = {
			url: 'http://localhost:3000/app/app-admin/app-ajax.php',
			method: 'POST'
		};

		this.getList = function() {
			return $http(REQ);
		};
	return this;
}

packageListController.$inject = ['$scope', 'packageService'];
packageService.$inject = ['$http'];  <commit_msg>removendo console.log<commit_after>angular
	.module("App")
		.controller("packageListController", packageListController )
		.service("packageService", packageService );

function packageListController( $scope, packageService ) {
	function success(obj){
		// console.log('Data: ', obj);
		// $scope.packages = obj.data;
	}
	function error(err){
		console.log('Erro: ', err);
	}

	packageService
		.getList()
		.then(success, error);

}

function packageService($http) {
	var REQ = {
			url: 'http://localhost:3000/app/app-admin/app-ajax.php',
			method: 'POST'
		};

		this.getList = function() {
			return $http(REQ);
		};
	return this;
}

packageListController.$inject = ['$scope', 'packageService'];
packageService.$inject = ['$http'];  <|endoftext|>


<commit_before>/* global define, it, describe */
import expect from 'expect';
import {
  addElementChild,
  removeElement,
  hideElement,
  changeElementDisplayName,
  changeElementPath,
  applyElementProp,
  removeElementProp,
  redoTreeAction,
  undoTreeAction,
} from './tree';
import {
  ADD_ELEMENT_CHILD,
  REMOVE_ELEMENT,
  HIDE_ELEMENT,
  CHANGE_ELEMENT_PATH,
  APPLY_ELEMENT_PROP,
  REMOVE_ELEMENT_PROP,
  REDO_TREE_ACTION,
  UNDO_TREE_ACTION,
} from '../constants/actionTypes';

describe('interface editor: tree action creators', () => {
  it('should create an action to add element child', () => {
    const elementPath = {};
    const child = {};
    const expectedAction = {
      type: ADD_ELEMENT_CHILD,
      elementPath,
      child,
    };

    expect(
      addElementChild(elementPath, child)
    ).toEqual(expectedAction);
  });

  it('should create an action to remove element', () => {
    const elementPath = {};
    const expectedAction = {
      type: REMOVE_ELEMENT,
      elementPath,
    };

    expect(
      removeElement(elementPath)
    ).toEqual(expectedAction);
  });

  it('should create an action to hide element', () => {
    const elementPath = {};
    const expectedAction = {
      type: HIDE_ELEMENT,
      elementPath,
    };

    expect(
      hideElement(elementPath)
    ).toEqual(expectedAction);
  });

  it('should create an action to change element display name', () => {
    const elementPath = {};
    const newDisplayName = 'MyView';
    const expectedAction = {
      type: CHANGE_ELEMENT_PATH,
      elementPath,
      newDisplayName,
    };

    expect(
      changeElementDisplayName(elementPath, newDisplayName)
    ).toEqual(expectedAction);
  });

  it('should create an action to change element path', () => {
    const elementPath = {};
    const newElementPath = {};
    const expectedAction = {
      type: CHANGE_ELEMENT_PATH,
      elementPath,
      newElementPath,
    };

    expect(
      changeElementPath(elementPath, newElementPath)
    ).toEqual(expectedAction);
  });

  it('should create an action to apply element prop', () => {
    const elementPath = {};
    const propName = 'style';
    const propValue = {};
    const expectedAction = {
      type: APPLY_ELEMENT_PROP,
      elementPath,
      propName,
      propValue,
    };

    expect(
      applyElementProp(elementPath, propName, propValue)
    ).toEqual(expectedAction);
  });

  it('should create an action to remove element prop', () => {
    const elementPath = {};
    const propName = 'style';
    const expectedAction = {
      type: REMOVE_ELEMENT_PROP,
      elementPath,
      propName,
    };

    expect(
      removeElementProp(elementPath, propName)
    ).toEqual(expectedAction);
  });

  it('should create an action to undo tree action', () => {
    const expectedAction = { type: UNDO_TREE_ACTION };

    expect(
      undoTreeAction()
    ).toEqual(expectedAction);
  });

  it('should create an action to redo tree action', () => {
    const expectedAction = { type: REDO_TREE_ACTION };

    expect(
      redoTreeAction()
    ).toEqual(expectedAction);
  });
});
<commit_msg>Fixed a broken test related to the changeElementDisplayName action creator<commit_after>/* global define, it, describe */
import expect from 'expect';
import {
  addElementChild,
  removeElement,
  hideElement,
  changeElementDisplayName,
  changeElementPath,
  applyElementProp,
  removeElementProp,
  redoTreeAction,
  undoTreeAction,
} from './tree';
import {
  ADD_ELEMENT_CHILD,
  REMOVE_ELEMENT,
  HIDE_ELEMENT,
  CHANGE_ELEMENT_DISPLAY_NAME,
  CHANGE_ELEMENT_PATH,
  APPLY_ELEMENT_PROP,
  REMOVE_ELEMENT_PROP,
  REDO_TREE_ACTION,
  UNDO_TREE_ACTION,
} from '../constants/actionTypes';

describe('interface editor: tree action creators', () => {
  it('should create an action to add element child', () => {
    const elementPath = {};
    const child = {};
    const expectedAction = {
      type: ADD_ELEMENT_CHILD,
      elementPath,
      child,
    };

    expect(
      addElementChild(elementPath, child)
    ).toEqual(expectedAction);
  });

  it('should create an action to remove element', () => {
    const elementPath = {};
    const expectedAction = {
      type: REMOVE_ELEMENT,
      elementPath,
    };

    expect(
      removeElement(elementPath)
    ).toEqual(expectedAction);
  });

  it('should create an action to hide element', () => {
    const elementPath = {};
    const expectedAction = {
      type: HIDE_ELEMENT,
      elementPath,
    };

    expect(
      hideElement(elementPath)
    ).toEqual(expectedAction);
  });

  it('should create an action to change element display name', () => {
    const elementPath = {};
    const newDisplayName = 'MyView';
    const expectedAction = {
      type: CHANGE_ELEMENT_DISPLAY_NAME,
      elementPath,
      newDisplayName,
    };

    expect(
      changeElementDisplayName(elementPath, newDisplayName)
    ).toEqual(expectedAction);
  });

  it('should create an action to change element path', () => {
    const elementPath = {};
    const newElementPath = {};
    const expectedAction = {
      type: CHANGE_ELEMENT_PATH,
      elementPath,
      newElementPath,
    };

    expect(
      changeElementPath(elementPath, newElementPath)
    ).toEqual(expectedAction);
  });

  it('should create an action to apply element prop', () => {
    const elementPath = {};
    const propName = 'style';
    const propValue = {};
    const expectedAction = {
      type: APPLY_ELEMENT_PROP,
      elementPath,
      propName,
      propValue,
    };

    expect(
      applyElementProp(elementPath, propName, propValue)
    ).toEqual(expectedAction);
  });

  it('should create an action to remove element prop', () => {
    const elementPath = {};
    const propName = 'style';
    const expectedAction = {
      type: REMOVE_ELEMENT_PROP,
      elementPath,
      propName,
    };

    expect(
      removeElementProp(elementPath, propName)
    ).toEqual(expectedAction);
  });

  it('should create an action to undo tree action', () => {
    const expectedAction = { type: UNDO_TREE_ACTION };

    expect(
      undoTreeAction()
    ).toEqual(expectedAction);
  });

  it('should create an action to redo tree action', () => {
    const expectedAction = { type: REDO_TREE_ACTION };

    expect(
      redoTreeAction()
    ).toEqual(expectedAction);
  });
});
<|endoftext|>