<commit_before>import {Button} from 'widget/button'
import {Form} from 'widget/form/form'
import {Panel} from 'widget/panel/panel'
import {RecipeActions} from 'app/home/body/process/mosaic/mosaicRecipe'
import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel'
import {compose} from 'compose'
import {msg} from 'translate'
import PropTypes from 'prop-types'
import React from 'react'
import SeasonSelect from 'widget/seasonSelect'
import moment from 'moment'
import styles from './dates.module.css'

const DATE_FORMAT = 'YYYY-MM-DD'

const minStartDate = targetDate => parseDate(targetDate).subtract(1, 'year').add(1, 'days')
const maxStartDate = targetDate => parseDate(targetDate)

const minEndDate = targetDate => parseDate(targetDate).add(1, 'days')
const maxEndDate = targetDate => parseDate(targetDate).add(1, 'years')

const fields = {
    advanced: new Form.Field(),

    targetYear: new Form.Field()
        .skip((_, {advanced}) => advanced)
        .int('process.mosaic.panel.dates.form.targetDate.malformed'),

    targetDate: new Form.Field()
        .skip((_, {advanced}) => !advanced)
        .date(DATE_FORMAT, 'process.mosaic.panel.dates.form.targetDate.malformed'),

    seasonStart: new Form.Field()
        .skip((_, {advanced}) => !advanced)
        .date(DATE_FORMAT, 'process.mosaic.panel.dates.form.season.malformed')
        .predicate((date, {targetDate}) => parseDate(date).isSameOrAfter(minStartDate(targetDate)),
            'process.mosaic.panel.dates.form.season.tooEarly',
            ({targetDate}) => ({
                min: minStartDate(targetDate).format(DATE_FORMAT)
            }))
        .predicate((date, {targetDate}) => parseDate(date).isSameOrBefore(maxStartDate(targetDate)),
            'process.mosaic.panel.dates.form.season.tooLate',
            ({targetDate}) => ({
                max: maxStartDate(targetDate).format(DATE_FORMAT)
            })),

    seasonEnd: new Form.Field()
        .skip((_, {advanced}) => !advanced)
        .date(DATE_FORMAT, 'process.mosaic.panel.dates.form.season.malformed')
        .predicate((date, {targetDate}) => parseDate(date).isSameOrAfter(minEndDate(targetDate)),
            'process.mosaic.panel.dates.form.season.tooEarly',
            ({targetDate}) => ({
                min: minEndDate(targetDate).format(DATE_FORMAT)
            }))
        .predicate((date, {targetDate}) => parseDate(date).isSameOrBefore(maxEndDate(targetDate)),
            'process.mosaic.panel.dates.form.season.tooLate',
            ({targetDate}) => ({
                max: maxEndDate(targetDate).format(DATE_FORMAT)
            })),

    yearsBefore: new Form.Field(),
    yearsAfter: new Form.Field()
}

class Dates extends React.Component {
    constructor(props) {
        super(props)
        const {inputs: {targetYear, targetDate}} = props
        targetYear.onChange(yearString => this.handleYearChange(yearString))
        targetDate.onChange(dateString => this.handleDateChange(dateString))
    }

    handleYearChange(yearString) {
        const {inputs: {targetDate}} = this.props
        const yearDate = parseYear(yearString)
        if (yearDate.isValid()) {
            const targetDateMoment = parseDate(targetDate.value)
            targetDateMoment.set('year', yearDate.year())
            targetDate.set(targetDateMoment.format(DATE_FORMAT))
        }
    }

    handleDateChange(dateString) {
        const {inputs: {targetYear}} = this.props
        const date = parseDate(dateString)
        if (date.isValid())
            targetYear.set(date.year())
    }

    setAdvanced(enabled) {
        const {inputs: {advanced}} = this.props
        advanced.set(enabled)
    }

    render() {
        const {recipeId, inputs: {advanced}} = this.props
        return (
            <RecipeFormPanel
                className={advanced.value ? styles.advanced : styles.simple}
                placement='bottom-right'
                onClose={() => RecipeActions(recipeId).showPreview().dispatch()}>
                <Panel.Header
                    icon='calendar-alt'
                    title={msg('process.mosaic.panel.dates.title')}/>
                <Panel.Content>
                    {advanced.value ? this.renderAdvanced() : this.renderSimple()}
                </Panel.Content>
                <Form.PanelButtons>
                    <Button
                        label={advanced.value ? msg('button.less') : msg('button.more')}
                        onClick={() => this.setAdvanced(!advanced.value)}/>
                </Form.PanelButtons>
            </RecipeFormPanel>
        )
    }

    renderSimple() {
        const {inputs: {targetYear}} = this.props
        return (

                <Form.YearPicker
                    label={msg('process.mosaic.panel.dates.form.targetYear.label')}
                    tooltip={msg('process.mosaic.panel.dates.form.targetYear.tooltip')}
                    tooltipPlacement='top'
                    input={targetYear}
                    startYear={1982}
                    endYear={moment().year()}/>

        )
    }

    renderAdvanced() {
        const {inputs: {targetDate, seasonStart, seasonEnd, yearsBefore, yearsAfter}} = this.props
        return (

                        <Form.DatePicker
                            label={msg('process.mosaic.panel.dates.form.targetDate.label')}
                            tooltip={msg('process.mosaic.panel.dates.form.targetDate.tooltip')}
                            input={targetDate}
                            startDate={'1982-08-22'}
                            endDate={moment().format(DATE_FORMAT)}
                        />

                        <Form.Slider
                            label={msg('process.mosaic.panel.dates.form.pastSeasons.label')}
                            info={pastSeasons => pastSeasons
                                ? msg('process.mosaic.panel.dates.form.pastSeasons.info.number', {pastSeasons})
                                : msg('process.mosaic.panel.dates.form.pastSeasons.info.none')
                            }
                            alignment='left'
                            input={yearsBefore}
                            ticks={[0, 1, 2, 3, 5, 10, {value: 25, label: 'all'}]}
                            snap
                            scale='log'
                            invert
                            range='low'
                        />

                        <Form.Slider
                            label={msg('process.mosaic.panel.dates.form.futureSeasons.label')}
                            info={futureSeasons => futureSeasons
                                ? msg('process.mosaic.panel.dates.form.futureSeasons.info.number', {futureSeasons})
                                : msg('process.mosaic.panel.dates.form.futureSeasons.info.none')
                            }
                            alignment='right'
                            input={yearsAfter}
                            ticks={[0, 1, 2, 3, 5, 10, {value: 25, label: 'all'}]}
                            snap
                            scale='log'
                            range='low'
                        />

                        <SeasonSelect
                            startDate={seasonStart}
                            endDate={seasonEnd}
                            centerDate={targetDate}
                            disabled={targetDate.isInvalid()}/>

        )
    }

    componentDidMount() {
        const {recipeId} = this.props
        RecipeActions(recipeId).hidePreview().dispatch()
    }
}

const parseDate = dateString =>
    moment(dateString, 'YYYY-MM-DD', true)

const parseYear = dateString =>
    moment(dateString, 'YYYY', true)

Dates.propTypes = {
    recipeId: PropTypes.string
}

const valuesToModel = values => {
    const DATE_FORMAT = 'YYYY-MM-DD'
    if (values.advanced)
        return {
            targetDate: values.targetDate,
            seasonStart: values.seasonStart,
            seasonEnd: values.seasonEnd,
            yearsBefore: values.yearsBefore,
            yearsAfter: values.yearsAfter
        }
    else
        return {
            targetDate: moment().year(values.targetYear).month(6).date(2).format(DATE_FORMAT),
            seasonStart: moment().year(values.targetYear).startOf('year').format(DATE_FORMAT),
            seasonEnd: moment().year(values.targetYear + 1).startOf('year').format(DATE_FORMAT),
            yearsBefore: 0,
            yearsAfter: 0
        }
}

const modelToValues = (model = {}) => {
    return {
        advanced:
            moment(model.seasonStart).dayOfYear() !== 1
            || moment(model.seasonEnd).dayOfYear() !== 1
            || model.yearsBefore !== 0
            || model.yearsAfter !== 0
            || moment(model.targetDate).dayOfYear() !== 183, // 2 July
        targetYear: moment(model.targetDate).year(),
        targetDate: model.targetDate,
        seasonStart: model.seasonStart,
        seasonEnd: model.seasonEnd,
        yearsBefore: model.yearsBefore,
        yearsAfter: model.yearsAfter,
    }
}

const additionalPolicy = () => ({sceneSelection: 'allow'})

export default compose(
    Dates,
    recipeFormPanel({id: 'dates', fields, modelToValues, valuesToModel, additionalPolicy})
)
<commit_msg>Made sure simple date form is shown for leap years.<commit_after>import {RecipeActions} from 'app/home/body/process/mosaic/mosaicRecipe'
import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel'
import {compose} from 'compose'
import moment from 'moment'
import PropTypes from 'prop-types'
import React from 'react'
import {msg} from 'translate'
import {Button} from 'widget/button'
import {Form} from 'widget/form/form'
import {Panel} from 'widget/panel/panel'
import SeasonSelect from 'widget/seasonSelect'
import styles from './dates.module.css'

const DATE_FORMAT = 'YYYY-MM-DD'

const minStartDate = targetDate => parseDate(targetDate).subtract(1, 'year').add(1, 'days')
const maxStartDate = targetDate => parseDate(targetDate)

const minEndDate = targetDate => parseDate(targetDate).add(1, 'days')
const maxEndDate = targetDate => parseDate(targetDate).add(1, 'years')

const fields = {
    advanced: new Form.Field(),

    targetYear: new Form.Field()
        .skip((_, {advanced}) => advanced)
        .int('process.mosaic.panel.dates.form.targetDate.malformed'),

    targetDate: new Form.Field()
        .skip((_, {advanced}) => !advanced)
        .date(DATE_FORMAT, 'process.mosaic.panel.dates.form.targetDate.malformed'),

    seasonStart: new Form.Field()
        .skip((_, {advanced}) => !advanced)
        .date(DATE_FORMAT, 'process.mosaic.panel.dates.form.season.malformed')
        .predicate((date, {targetDate}) => parseDate(date).isSameOrAfter(minStartDate(targetDate)),
            'process.mosaic.panel.dates.form.season.tooEarly',
            ({targetDate}) => ({
                min: minStartDate(targetDate).format(DATE_FORMAT)
            }))
        .predicate((date, {targetDate}) => parseDate(date).isSameOrBefore(maxStartDate(targetDate)),
            'process.mosaic.panel.dates.form.season.tooLate',
            ({targetDate}) => ({
                max: maxStartDate(targetDate).format(DATE_FORMAT)
            })),

    seasonEnd: new Form.Field()
        .skip((_, {advanced}) => !advanced)
        .date(DATE_FORMAT, 'process.mosaic.panel.dates.form.season.malformed')
        .predicate((date, {targetDate}) => parseDate(date).isSameOrAfter(minEndDate(targetDate)),
            'process.mosaic.panel.dates.form.season.tooEarly',
            ({targetDate}) => ({
                min: minEndDate(targetDate).format(DATE_FORMAT)
            }))
        .predicate((date, {targetDate}) => parseDate(date).isSameOrBefore(maxEndDate(targetDate)),
            'process.mosaic.panel.dates.form.season.tooLate',
            ({targetDate}) => ({
                max: maxEndDate(targetDate).format(DATE_FORMAT)
            })),

    yearsBefore: new Form.Field(),
    yearsAfter: new Form.Field()
}

class Dates extends React.Component {
    constructor(props) {
        super(props)
        const {inputs: {targetYear, targetDate}} = props
        targetYear.onChange(yearString => this.handleYearChange(yearString))
        targetDate.onChange(dateString => this.handleDateChange(dateString))
    }

    handleYearChange(yearString) {
        const {inputs: {targetDate}} = this.props
        const yearDate = parseYear(yearString)
        if (yearDate.isValid()) {
            const targetDateMoment = parseDate(targetDate.value)
            targetDateMoment.set('year', yearDate.year())
            targetDate.set(targetDateMoment.format(DATE_FORMAT))
        }
    }

    handleDateChange(dateString) {
        const {inputs: {targetYear}} = this.props
        const date = parseDate(dateString)
        if (date.isValid())
            targetYear.set(date.year())
    }

    setAdvanced(enabled) {
        const {inputs: {advanced}} = this.props
        console.log('advanced.set', enabled)
        advanced.set(enabled)
    }

    render() {
        const {recipeId, inputs: {advanced}} = this.props
        return (
            <RecipeFormPanel
                className={advanced.value ? styles.advanced : styles.simple}
                placement='bottom-right'
                onClose={() => RecipeActions(recipeId).showPreview().dispatch()}>
                <Panel.Header
                    icon='calendar-alt'
                    title={msg('process.mosaic.panel.dates.title')}/>
                <Panel.Content>
                    {advanced.value ? this.renderAdvanced() : this.renderSimple()}
                </Panel.Content>
                <Form.PanelButtons>
                    <Button
                        label={advanced.value ? msg('button.less') : msg('button.more')}
                        onClick={() => this.setAdvanced(!advanced.value)}/>
                </Form.PanelButtons>
            </RecipeFormPanel>
        )
    }

    renderSimple() {
        const {inputs: {targetYear}} = this.props
        return (

                <Form.YearPicker
                    label={msg('process.mosaic.panel.dates.form.targetYear.label')}
                    tooltip={msg('process.mosaic.panel.dates.form.targetYear.tooltip')}
                    tooltipPlacement='top'
                    input={targetYear}
                    startYear={1982}
                    endYear={moment().year()}/>

        )
    }

    renderAdvanced() {
        const {inputs: {targetDate, seasonStart, seasonEnd, yearsBefore, yearsAfter}} = this.props
        return (

                        <Form.DatePicker
                            label={msg('process.mosaic.panel.dates.form.targetDate.label')}
                            tooltip={msg('process.mosaic.panel.dates.form.targetDate.tooltip')}
                            input={targetDate}
                            startDate={'1982-08-22'}
                            endDate={moment().format(DATE_FORMAT)}
                        />

                        <Form.Slider
                            label={msg('process.mosaic.panel.dates.form.pastSeasons.label')}
                            info={pastSeasons => pastSeasons
                                ? msg('process.mosaic.panel.dates.form.pastSeasons.info.number', {pastSeasons})
                                : msg('process.mosaic.panel.dates.form.pastSeasons.info.none')
                            }
                            alignment='left'
                            input={yearsBefore}
                            ticks={[0, 1, 2, 3, 5, 10, {value: 25, label: 'all'}]}
                            snap
                            scale='log'
                            invert
                            range='low'
                        />

                        <Form.Slider
                            label={msg('process.mosaic.panel.dates.form.futureSeasons.label')}
                            info={futureSeasons => futureSeasons
                                ? msg('process.mosaic.panel.dates.form.futureSeasons.info.number', {futureSeasons})
                                : msg('process.mosaic.panel.dates.form.futureSeasons.info.none')
                            }
                            alignment='right'
                            input={yearsAfter}
                            ticks={[0, 1, 2, 3, 5, 10, {value: 25, label: 'all'}]}
                            snap
                            scale='log'
                            range='low'
                        />

                        <SeasonSelect
                            startDate={seasonStart}
                            endDate={seasonEnd}
                            centerDate={targetDate}
                            disabled={targetDate.isInvalid()}/>

        )
    }

    componentDidMount() {
        const {recipeId} = this.props
        RecipeActions(recipeId).hidePreview().dispatch()
    }
}

const parseDate = dateString =>
    moment(dateString, 'YYYY-MM-DD', true)

const parseYear = dateString =>
    moment(dateString, 'YYYY', true)

Dates.propTypes = {
    recipeId: PropTypes.string
}

const valuesToModel = values => {
    const DATE_FORMAT = 'YYYY-MM-DD'
    if (values.advanced)
        return {
            targetDate: values.targetDate,
            seasonStart: values.seasonStart,
            seasonEnd: values.seasonEnd,
            yearsBefore: values.yearsBefore,
            yearsAfter: values.yearsAfter
        }
    else
        return {
            targetDate: moment().year(values.targetYear).month(6).date(2).format(DATE_FORMAT),
            seasonStart: moment().year(values.targetYear).startOf('year').format(DATE_FORMAT),
            seasonEnd: moment().year(values.targetYear + 1).startOf('year').format(DATE_FORMAT),
            yearsBefore: 0,
            yearsAfter: 0
        }
}

const modelToValues = (model = {}) => {
    return {
        advanced:
            moment(model.seasonStart).dayOfYear() !== 1
            || moment(model.seasonEnd).dayOfYear() !== 1
            || model.yearsBefore !== 0
            || model.yearsAfter !== 0
            || ![183, 184].includes(moment(model.targetDate).dayOfYear()), // 2 July
        targetYear: moment(model.targetDate).year(),
        targetDate: model.targetDate,
        seasonStart: model.seasonStart,
        seasonEnd: model.seasonEnd,
        yearsBefore: model.yearsBefore,
        yearsAfter: model.yearsAfter,
    }
}

const additionalPolicy = () => ({sceneSelection: 'allow'})

export default compose(
    Dates,
    recipeFormPanel({id: 'dates', fields, modelToValues, valuesToModel, additionalPolicy})
)
<|endoftext|>


<commit_before>var challenge_user_input;

$(document).ready(function() {
    challenge_user_input = $('#challenge-user-input');

    // Run when submit button is clicked.
    $('#submit-answer').click(function(){
        // Deactiviate button
        $(this).prop('disabled', true);

        // Get challenge number and user_answer.
        var user_answer = challenge_user_input.val();

        // If empty, display message
        if (user_answer) {
            var challenge_number = $('#challenge-pills-tabContent > .tab-pane.active').data('challenge-number');
            var result = checkAnswer(challenge_number, user_answer);
            // Display output
            if (result) {
                displayFeedback('correct');
            } else {
                displayFeedback('incorrect');
            }
            // Log to database

        } else {
            displayFeedback('empty');
        }

        // Activate button
        $(this).prop('disabled', false);
    });

    $('#challenge-pills-tab .nav-link').click(function() {
        challenge_user_input.val('');
        displayFeedback();
    });
});

function checkAnswer(challenge_number, user_answer) {
  /**
   * Check if user answer matches correct answer.
   * @param {integer} challenge_number - Number of current challenge.
   * @param {string} user_answer - Answer submitted by user.
   * @return {boolean} Boolean if answer is correct.
   */
    challenge_answer = challenge_json[challenge_number];
    user_answer = user_answer.toLowerCase().replace(/,\s/g, ',');
    return challenge_number == user_answer;
};

function displayFeedback(status) {
    /**
     * Update feedback to reflect given status.
     * @param {string} status - Type of feedback to provide.
     */
    challenge_user_input.removeClass('is-valid is-invalid is-empty');
    if (status == 'correct') {
        challenge_user_input.addClass('is-valid');
    } else if (status == 'incorrect') {
        challenge_user_input.addClass('is-invalid');
    } else if (status == 'empty') {
        challenge_user_input.addClass('is-empty');
    }
};

function logAnswer() {

};
<commit_msg>Fix bug where answer was not compared correctly<commit_after>var challenge_user_input;

$(document).ready(function() {
    challenge_user_input = $('#challenge-user-input');

    // Run when submit button is clicked.
    $('#submit-answer').click(function(){
        // Deactiviate button
        $(this).prop('disabled', true);

        // Get challenge number and user_answer.
        var user_answer = challenge_user_input.val();

        // If empty, display message
        if (user_answer) {
            var challenge_number = $('#challenge-pills-tabContent > .tab-pane.active').data('challenge-number');
            var result = checkAnswer(challenge_number, user_answer);
            // Display output
            if (result) {
                displayFeedback('correct');
                $(this).hide();
            } else {
                displayFeedback('incorrect');
            }
            // Log to database

        } else {
            displayFeedback('empty');
        }

        // Activate button
        $(this).prop('disabled', false);
    });

    $('#challenge-pills-tab .nav-link').click(function() {
        challenge_user_input.val('');
        displayFeedback();
        $('#submit-answer').show();
    });
});

function checkAnswer(challenge_number, user_answer) {
  /**
   * Check if user answer matches correct answer.
   * @param {integer} challenge_number - Number of current challenge.
   * @param {string} user_answer - Answer submitted by user.
   * @return {boolean} Boolean if answer is correct.
   */
    challenge_answer = challenges_json[challenge_number];
    user_answer = user_answer.toLowerCase().replace(/,\s/g, ',');
    return challenge_answer == user_answer;
};

function displayFeedback(status) {
    /**
     * Update feedback to reflect given status.
     * @param {string} status - Type of feedback to provide.
     */
    challenge_user_input.removeClass('is-valid is-invalid is-empty');
    if (status == 'correct') {
        challenge_user_input.addClass('is-valid');
    } else if (status == 'incorrect') {
        challenge_user_input.addClass('is-invalid');
    } else if (status == 'empty') {
        challenge_user_input.addClass('is-empty');
    }
};

function logAnswer() {

};
<|endoftext|>


<commit_before>(function(global) {
  "use strict;"

  var VdomBuilder = function VdomBuilder(component, formName) {
    this.component = component;
    this.formName = formName;
    this.h = virtualDom.h;
    this.elements = [];
  };

  $.extend(VdomBuilder.prototype, {
    markup: function(callback) {
      var root = this.component.root, formName, builder, attributes;

      if (typeof callback !== 'function')
        throw new Error("The first agument must be a function.");
      if (callback.length === 0)
        throw new Error("Callback requires an argument.");
      if (root.tagName == 'form') formName = root.attributes.name;
      builder = new VdomBuilder(this.component, formName);
      callback.call(this.component, builder);

      attributes = {};
      for (var i = 0, len = root.attributes.length; i < len; i++)
        attributes[root.attributes[i].nodeName] = root.attributes[i].value;
      return this.h(root.tagName, attributes, builder.elements);
    },
    contentTag: function(tagName) {
      var args, options, content, callback, builder;

      args = Array.prototype.slice.call(arguments, 1);
      content = extractContent(args);
      options = extractOptions(args);
      callback = extractCallback(args);

      if (callback) {
        builder = new VdomBuilder(this.component, this.formName);
        if (callback.length === 0) { throw new Error("Callback requires an argument.") }
        callback.call(this.component, builder);
        attributes = generateAttributes(options);
        this.elements.push(this.h(tagName, attributes, builder.elements));
      }
      else {
        content = content || '';
        attributes = generateAttributes(options);
        this.elements.push(this.h(tagName, attributes, content));
      }
      return this;
    },
    tag: function(tagName, options) {
      attributes = generateAttributes(options);
      this.elements.push(this.h(tagName, attributes));
      return this;
    },
    text: function(content) {
      this.elements.push(content);
      return this;
    },
    space: function() {
      this.elements.push(' ');
      return this;
    },
    form: function(options, callback) {
      var name, builder, attributes;

      if (callback.length === 0) { throw new Error("Callback requires an argument.") }
      name = options['name'] || '';
      builder = new VdomBuilder(this.component, name);
      callback.call(this.component, builder);
      options = options || {};
      if (options['onsubmit'] === undefined) {
        options['onsubmit'] = function(e) { return false };
      }
      attributes = generateAttributes(options);
      this.elements.push(this.h('form', attributes, builder.elements));
      return this;
    },
    labelFor: function(id, content, options) {
      options = options || {};
      options['htmlFor'] = id;
      this.contentTag('label', content, options)
      return this;
    },
    input: function(options) {
      var form, name, value;

      options = options || {};
      name = options['name'];
      value = options['value'];
      if (value === undefined && name !== undefined && this.formName !== undefined)
        options['value'] = this.component.getValue(this.formName + '.' + name);
      attributes = generateAttributes(options);
      this.elements.push(this.h('input', attributes));
      return this;
    },
    textField: function(name, options) {
      var self = this;

      options = options || {};
      options['type'] = 'text';
      options['name'] = name;
      this.input(options);
      return this;
    },
    checkBox: function(attrName, options) {
      var checked = this.component.getValue(this.formName + '.' + attrName);

      options = options || {};
      options['type'] = 'checkbox';
      if (attrName) options['name'] = attrName;
      if (checked) options['checked'] = 'checked';
      if (!options['value']) options['value'] = '1';
      this.input($.extend({}, options, { type: 'hidden', value: '0' }));
      this.input(options);
      return this;
    }
  });

  function extractContent(args) {
    if (typeof args[0] === 'string') return args[0];
  }

  function extractOptions(args) {
    for (var i = 0; i < args.length; i++)
      if (typeof args[i] === 'object') return args[i];
  }

  function extractCallback(args) {
    for (var i = 0; i < args.length; i++)
      if (typeof args[i] === 'function') return args[i];
  }

  function generateAttributes(options) {
    options = options || {};
    if ('visible' in options && !options['visible']) {
      options['style'] = options['style'] || {};
      options['style']['display'] = 'none';
    }
    if ('class' in options) {
      options['className'] = options['class'];
      delete options['class'];
    }
    if ('for' in options) {
      options['htmlFor'] = options['for'];
      delete options['for'];
    }
    if (typeof options['className'] === 'object') {
      var names = []
      for (var name in options['className']) {
        if (options['className'][name]) {
          names.push(name)
        }
      }
      if (names.length) {
        options['className'] = names.join(' ')
      }
      else {
        delete options['className'];
      }
    }
    return options;
  }

  var normalElementNames = [
    'a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo',
    'blockquote', 'body', 'button', 'canvas', 'caption', 'cite', 'code',
    'colgroup', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div',
    'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer',
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'html',
    'i', 'iframe', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark',
    'menu', 'menuitem', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup',
    'option', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's',
    'samp', 'script', 'section', 'select', 'small', 'span', 'strong', 'style',
    'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot',
    'th', 'thead', 'time', 'title', 'tr', 'u', 'ul', 'var', 'video' ];

  for (var i = 0; i < normalElementNames.length; i++) {
    var tagName = normalElementNames[i];
    VdomBuilder.prototype[tagName] = new Function("arg1", "arg2",
      "this.contentTag('" + tagName + "', arg1, arg2); return this");
  }

  var voidElementNames = [
    'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'keygen',
    'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'
  ]

  for (var i = 0; i < voidElementNames.length; i++) {
    var tagName = voidElementNames[i];
    VdomBuilder.prototype[tagName] = new Function("options",
      "this.tag('" + tagName + "', options); return this");
  }

  if (!global.CapeJS) {
    var CapeJS = {};
    if ("process" in global) module.exports = CapeJS;
    global.CapeJS = CapeJS;
  }
  global.CapeJS.VdomBuilder = VdomBuilder;

})((this || 0).self || global);
<commit_msg>Add VdomBuilder#faIcon<commit_after>(function(global) {
  "use strict;"

  var VdomBuilder = function VdomBuilder(component, formName) {
    this.component = component;
    this.formName = formName;
    this.h = virtualDom.h;
    this.elements = [];
  };

  $.extend(VdomBuilder.prototype, {
    markup: function(callback) {
      var root = this.component.root, formName, builder, attributes;

      if (typeof callback !== 'function')
        throw new Error("The first agument must be a function.");
      if (callback.length === 0)
        throw new Error("Callback requires an argument.");
      if (root.tagName == 'form') formName = root.attributes.name;
      builder = new VdomBuilder(this.component, formName);
      callback.call(this.component, builder);

      attributes = {};
      for (var i = 0, len = root.attributes.length; i < len; i++)
        attributes[root.attributes[i].nodeName] = root.attributes[i].value;
      return this.h(root.tagName, attributes, builder.elements);
    },
    contentTag: function(tagName) {
      var args, options, content, callback, builder;

      args = Array.prototype.slice.call(arguments, 1);
      content = extractContent(args);
      options = extractOptions(args);
      callback = extractCallback(args);

      if (callback) {
        builder = new VdomBuilder(this.component, this.formName);
        if (callback.length === 0) { throw new Error("Callback requires an argument.") }
        callback.call(this.component, builder);
        attributes = generateAttributes(options);
        this.elements.push(this.h(tagName, attributes, builder.elements));
      }
      else {
        content = content || '';
        attributes = generateAttributes(options);
        this.elements.push(this.h(tagName, attributes, content));
      }
      return this;
    },
    tag: function(tagName, options) {
      attributes = generateAttributes(options);
      this.elements.push(this.h(tagName, attributes));
      return this;
    },
    text: function(content) {
      this.elements.push(content);
      return this;
    },
    space: function() {
      this.elements.push(' ');
      return this;
    },
    form: function(options, callback) {
      var name, builder, attributes;

      if (callback.length === 0) { throw new Error("Callback requires an argument.") }
      name = options['name'] || '';
      builder = new VdomBuilder(this.component, name);
      callback.call(this.component, builder);
      options = options || {};
      if (options['onsubmit'] === undefined) {
        options['onsubmit'] = function(e) { return false };
      }
      attributes = generateAttributes(options);
      this.elements.push(this.h('form', attributes, builder.elements));
      return this;
    },
    labelFor: function(id, content, options) {
      options = options || {};
      options['htmlFor'] = id;
      this.contentTag('label', content, options)
      return this;
    },
    input: function(options) {
      var form, name, value;

      options = options || {};
      name = options['name'];
      value = options['value'];
      if (value === undefined && name !== undefined && this.formName !== undefined)
        options['value'] = this.component.getValue(this.formName + '.' + name);
      attributes = generateAttributes(options);
      this.elements.push(this.h('input', attributes));
      return this;
    },
    textField: function(name, options) {
      var self = this;

      options = options || {};
      options['type'] = 'text';
      options['name'] = name;
      this.input(options);
      return this;
    },
    checkBox: function(attrName, options) {
      var checked = this.component.getValue(this.formName + '.' + attrName);

      options = options || {};
      options['type'] = 'checkbox';
      if (attrName) options['name'] = attrName;
      if (checked) options['checked'] = 'checked';
      if (!options['value']) options['value'] = '1';
      this.input($.extend({}, options, { type: 'hidden', value: '0' }));
      this.input(options);
      return this;
    },
    faIcon: function(iconName) {
      this.i('', { class: 'fa fa-' + iconName});
      return this;
    }
  });

  function extractContent(args) {
    if (typeof args[0] === 'string') return args[0];
  }

  function extractOptions(args) {
    for (var i = 0; i < args.length; i++)
      if (typeof args[i] === 'object') return args[i];
  }

  function extractCallback(args) {
    for (var i = 0; i < args.length; i++)
      if (typeof args[i] === 'function') return args[i];
  }

  function generateAttributes(options) {
    options = options || {};
    if ('visible' in options && !options['visible']) {
      options['style'] = options['style'] || {};
      options['style']['display'] = 'none';
    }
    if ('class' in options) {
      options['className'] = options['class'];
      delete options['class'];
    }
    if ('for' in options) {
      options['htmlFor'] = options['for'];
      delete options['for'];
    }
    if (typeof options['className'] === 'object') {
      var names = []
      for (var name in options['className']) {
        if (options['className'][name]) {
          names.push(name)
        }
      }
      if (names.length) {
        options['className'] = names.join(' ')
      }
      else {
        delete options['className'];
      }
    }
    return options;
  }

  var normalElementNames = [
    'a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo',
    'blockquote', 'body', 'button', 'canvas', 'caption', 'cite', 'code',
    'colgroup', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div',
    'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer',
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'html',
    'i', 'iframe', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark',
    'menu', 'menuitem', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup',
    'option', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's',
    'samp', 'script', 'section', 'select', 'small', 'span', 'strong', 'style',
    'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot',
    'th', 'thead', 'time', 'title', 'tr', 'u', 'ul', 'var', 'video' ];

  for (var i = 0; i < normalElementNames.length; i++) {
    var tagName = normalElementNames[i];
    VdomBuilder.prototype[tagName] = new Function("arg1", "arg2",
      "this.contentTag('" + tagName + "', arg1, arg2); return this");
  }

  var voidElementNames = [
    'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'keygen',
    'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'
  ]

  for (var i = 0; i < voidElementNames.length; i++) {
    var tagName = voidElementNames[i];
    VdomBuilder.prototype[tagName] = new Function("options",
      "this.tag('" + tagName + "', options); return this");
  }

  if (!global.CapeJS) {
    var CapeJS = {};
    if ("process" in global) module.exports = CapeJS;
    global.CapeJS = CapeJS;
  }
  global.CapeJS.VdomBuilder = VdomBuilder;

})((this || 0).self || global);
<|endoftext|>


<commit_before>var http   = require('http'),
    https  = require('https'),
    common = require('../common'),
    passes = exports;

/*!
 * Array of passes.
 *
 * A `pass` is just a function that is executed on `req, socket, options`
 * so that you can easily add new checks while still keeping the base
 * flexible.
 */

/*
 * Websockets Passes
 *
 */

var passes = exports;

[
/**
 * WebSocket requests must have the `GET` method and
 * the `upgrade:websocket` header
 */

function checkMethodAndHeader (req, socket) {
  if (req.method !== 'GET' || !req.headers.upgrade) {
    socket.destroy();  return true;
  }

  if (req.headers.upgrade.toLowerCase() !== 'websocket') {
    socket.destroy();  return true;
  }
},

/**
 * Setup socket
 *
 */

function setupSocket(req, socket) {
  socket.setTimeout(0);
  socket.setNoDelay(true);

  socket.setKeepAlive(true, 0);
},

/**
 * Sets `x-forwarded-*` headers if specified in config.
 *
 */

function XHeaders(req, socket, options) {
  if(!options.xfwd) return;

  var values = {
    for  : req.connection.remoteAddsockets || req.socket.remoteAddsockets,
    port : req.connection.remotePort || req.socket.remotePort,
    proto: req.connection.pair ? 'wss' : 'ws'
  };

  ['for', 'port', 'proto'].forEach(function(header) {
    req.headers['x-forwarded-' + header] =
      (req.headers['x-forwarded-' + header] || '') +
      (req.headers['x-forwarded-' + header] ? ',' : '') +
      values[header]
  });
},

/**
 *
 *
 */
function stream(req, socket, options, head) {
  common.setupSocket(socket);

  var proxyReq = (options.ssl ? https : http).request(
    common.setupOutgoing(options.ssl || {}, options, req)
  );

  proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
    common.setupSocket(proxySocket);

    if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);

    socket.write('HTTP/1.1 101 Switching Protocols\r\n');
    socket.write(Object.keys(proxyRes.headers).map(function(i) {
      return i + ": " + proxyRes.headers[i];
    }).join('\r\n') + '\r\n\r\n');
    proxySocket.pipe(socket).pipe(proxySocket);
  });

  proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
}

] // <--
  .forEach(function(func) {
    passes[func.name] = func;
  });
<commit_msg>[fix] proxy to http(s)<commit_after>var http   = require('http'),
    https  = require('https'),
    common = require('../common'),
    passes = exports;

/*!
 * Array of passes.
 *
 * A `pass` is just a function that is executed on `req, socket, options`
 * so that you can easily add new checks while still keeping the base
 * flexible.
 */

/*
 * Websockets Passes
 *
 */

var passes = exports;

[
/**
 * WebSocket requests must have the `GET` method and
 * the `upgrade:websocket` header
 */

function checkMethodAndHeader (req, socket) {
  if (req.method !== 'GET' || !req.headers.upgrade) {
    socket.destroy();  return true;
  }

  if (req.headers.upgrade.toLowerCase() !== 'websocket') {
    socket.destroy();  return true;
  }
},

/**
 * Setup socket
 *
 */

function setupSocket(req, socket) {
  socket.setTimeout(0);
  socket.setNoDelay(true);

  socket.setKeepAlive(true, 0);
},

/**
 * Sets `x-forwarded-*` headers if specified in config.
 *
 */

function XHeaders(req, socket, options) {
  if(!options.xfwd) return;

  var values = {
    for  : req.connection.remoteAddsockets || req.socket.remoteAddsockets,
    port : req.connection.remotePort || req.socket.remotePort,
    proto: req.connection.pair ? 'wss' : 'ws'
  };

  ['for', 'port', 'proto'].forEach(function(header) {
    req.headers['x-forwarded-' + header] =
      (req.headers['x-forwarded-' + header] || '') +
      (req.headers['x-forwarded-' + header] ? ',' : '') +
      values[header]
  });
},

/**
 *
 *
 */
function stream(req, socket, options, head) {
  common.setupSocket(socket);

  var proxyReq = (~['https:', 'wss:'].indexOf(options.target.protocol) ? https : http).request(
    common.setupOutgoing(options.ssl || {}, options, req)
  );

  proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
    common.setupSocket(proxySocket);

    if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);

    socket.write('HTTP/1.1 101 Switching Protocols\r\n');
    socket.write(Object.keys(proxyRes.headers).map(function(i) {
      return i + ": " + proxyRes.headers[i];
    }).join('\r\n') + '\r\n\r\n');
    proxySocket.pipe(socket).pipe(proxySocket);
  });

  proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
}

] // <--
  .forEach(function(func) {
    passes[func.name] = func;
  });
<|endoftext|>


<commit_before>var support = {
  searchParams: 'URLSearchParams' in self,
  iterable: 'Symbol' in self && 'iterator' in Symbol,
  blob:
    'FileReader' in self &&
    'Blob' in self &&
    (function() {
      try {
        new Blob()
        return true
      } catch (e) {
        return false
      }
    })(),
  formData: 'FormData' in self,
  arrayBuffer: 'ArrayBuffer' in self
}

function isDataView(obj) {
  return obj && DataView.prototype.isPrototypeOf(obj)
}

if (support.arrayBuffer) {
  var viewClasses = [
    '[object Int8Array]',
    '[object Uint8Array]',
    '[object Uint8ClampedArray]',
    '[object Int16Array]',
    '[object Uint16Array]',
    '[object Int32Array]',
    '[object Uint32Array]',
    '[object Float32Array]',
    '[object Float64Array]'
  ]

  var isArrayBufferView =
    ArrayBuffer.isView ||
    function(obj) {
      return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
    }
}

function normalizeName(name) {
  if (typeof name !== 'string') {
    name = String(name)
  }
  if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {
    throw new TypeError('Invalid character in header field name')
  }
  return name.toLowerCase()
}

function normalizeValue(value) {
  if (typeof value !== 'string') {
    value = String(value)
  }
  return value
}

// Build a destructive iterator for the value list
function iteratorFor(items) {
  var iterator = {
    next: function() {
      var value = items.shift()
      return {done: value === undefined, value: value}
    }
  }

  if (support.iterable) {
    iterator[Symbol.iterator] = function() {
      return iterator
    }
  }

  return iterator
}

export function Headers(headers) {
  this.map = {}

  if (headers instanceof Headers) {
    headers.forEach(function(value, name) {
      this.append(name, value)
    }, this)
  } else if (Array.isArray(headers)) {
    headers.forEach(function(header) {
      this.append(header[0], header[1])
    }, this)
  } else if (headers) {
    Object.getOwnPropertyNames(headers).forEach(function(name) {
      this.append(name, headers[name])
    }, this)
  }
}

Headers.prototype.append = function(name, value) {
  name = normalizeName(name)
  value = normalizeValue(value)
  var oldValue = this.map[name]
  this.map[name] = oldValue ? oldValue + ', ' + value : value
}

Headers.prototype['delete'] = function(name) {
  delete this.map[normalizeName(name)]
}

Headers.prototype.get = function(name) {
  name = normalizeName(name)
  return this.has(name) ? this.map[name] : null
}

Headers.prototype.has = function(name) {
  return this.map.hasOwnProperty(normalizeName(name))
}

Headers.prototype.set = function(name, value) {
  this.map[normalizeName(name)] = normalizeValue(value)
}

Headers.prototype.forEach = function(callback, thisArg) {
  for (var name in this.map) {
    if (this.map.hasOwnProperty(name)) {
      callback.call(thisArg, this.map[name], name, this)
    }
  }
}

Headers.prototype.keys = function() {
  var items = []
  this.forEach(function(value, name) {
    items.push(name)
  })
  return iteratorFor(items)
}

Headers.prototype.values = function() {
  var items = []
  this.forEach(function(value) {
    items.push(value)
  })
  return iteratorFor(items)
}

Headers.prototype.entries = function() {
  var items = []
  this.forEach(function(value, name) {
    items.push([name, value])
  })
  return iteratorFor(items)
}

if (support.iterable) {
  Headers.prototype[Symbol.iterator] = Headers.prototype.entries
}

function consumed(body) {
  if (body.bodyUsed) {
    return Promise.reject(new TypeError('Already read'))
  }
  body.bodyUsed = true
}

function fileReaderReady(reader) {
  return new Promise(function(resolve, reject) {
    reader.onload = function() {
      resolve(reader.result)
    }
    reader.onerror = function() {
      reject(reader.error)
    }
  })
}

function readBlobAsArrayBuffer(blob) {
  var reader = new FileReader()
  var promise = fileReaderReady(reader)
  reader.readAsArrayBuffer(blob)
  return promise
}

function readBlobAsText(blob) {
  var reader = new FileReader()
  var promise = fileReaderReady(reader)
  reader.readAsText(blob)
  return promise
}

function readArrayBufferAsText(buf) {
  var view = new Uint8Array(buf)
  var chars = new Array(view.length)

  for (var i = 0; i < view.length; i++) {
    chars[i] = String.fromCharCode(view[i])
  }
  return chars.join('')
}

function bufferClone(buf) {
  if (buf.slice) {
    return buf.slice(0)
  } else {
    var view = new Uint8Array(buf.byteLength)
    view.set(new Uint8Array(buf))
    return view.buffer
  }
}

function Body() {
  this.bodyUsed = false

  this._initBody = function(body) {
    /*
      fetch-mock wraps the Response object in an ES6 Proxy to
      provide useful test harness features such as flush. However, on
      ES5 browsers without fetch or Proxy support pollyfills must be used;
      the proxy-pollyfill is unable to proxy an attribute unless it exists
      on the object before the Proxy is created. This change ensures
      Response.bodyUsed exists on the instance, while maintaining the
      semantic of setting Request.bodyUsed in the constructor before
      _initBody is called.
    */
    this.bodyUsed = this.bodyUsed
    this._bodyInit = body
    if (!body) {
      this._bodyText = ''
    } else if (typeof body === 'string') {
      this._bodyText = body
    } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
      this._bodyBlob = body
    } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
      this._bodyFormData = body
    } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
      this._bodyText = body.toString()
    } else if (support.arrayBuffer && support.blob && isDataView(body)) {
      this._bodyArrayBuffer = bufferClone(body.buffer)
      // IE 10-11 can't handle a DataView body.
      this._bodyInit = new Blob([this._bodyArrayBuffer])
    } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
      this._bodyArrayBuffer = bufferClone(body)
    } else {
      this._bodyText = body = Object.prototype.toString.call(body)
    }

    if (!this.headers.get('content-type')) {
      if (typeof body === 'string') {
        this.headers.set('content-type', 'text/plain;charset=UTF-8')
      } else if (this._bodyBlob && this._bodyBlob.type) {
        this.headers.set('content-type', this._bodyBlob.type)
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
      }
    }
  }

  if (support.blob) {
    this.blob = function() {
      var rejected = consumed(this)
      if (rejected) {
        return rejected
      }

      if (this._bodyBlob) {
        return Promise.resolve(this._bodyBlob)
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(new Blob([this._bodyArrayBuffer]))
      } else if (this._bodyFormData) {
        throw new Error('could not read FormData body as blob')
      } else {
        return Promise.resolve(new Blob([this._bodyText]))
      }
    }

    this.arrayBuffer = function() {
      if (this._bodyArrayBuffer) {
        return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
      } else {
        return this.blob().then(readBlobAsArrayBuffer)
      }
    }
  }

  this.text = function() {
    var rejected = consumed(this)
    if (rejected) {
      return rejected
    }

    if (this._bodyBlob) {
      return readBlobAsText(this._bodyBlob)
    } else if (this._bodyArrayBuffer) {
      return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
    } else if (this._bodyFormData) {
      throw new Error('could not read FormData body as text')
    } else {
      return Promise.resolve(this._bodyText)
    }
  }

  if (support.formData) {
    this.formData = function() {
      return this.text().then(decode)
    }
  }

  this.json = function() {
    return this.text().then(JSON.parse)
  }

  return this
}

// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

function normalizeMethod(method) {
  var upcased = method.toUpperCase()
  return methods.indexOf(upcased) > -1 ? upcased : method
}

export function Request(input, options) {
  options = options || {}
  var body = options.body

  if (input instanceof Request) {
    if (input.bodyUsed) {
      throw new TypeError('Already read')
    }
    this.url = input.url
    this.credentials = input.credentials
    if (!options.headers) {
      this.headers = new Headers(input.headers)
    }
    this.method = input.method
    this.mode = input.mode
    this.signal = input.signal
    if (!body && input._bodyInit != null) {
      body = input._bodyInit
      input.bodyUsed = true
    }
  } else {
    this.url = String(input)
  }

  this.credentials = options.credentials || this.credentials || 'same-origin'
  if (options.headers || !this.headers) {
    this.headers = new Headers(options.headers)
  }
  this.method = normalizeMethod(options.method || this.method || 'GET')
  this.mode = options.mode || this.mode || null
  this.signal = options.signal || this.signal
  this.referrer = null

  if ((this.method === 'GET' || this.method === 'HEAD') && body) {
    throw new TypeError('Body not allowed for GET or HEAD requests')
  }
  this._initBody(body)
}

Request.prototype.clone = function() {
  return new Request(this, {body: this._bodyInit})
}

function decode(body) {
  var form = new FormData()
  body
    .trim()
    .split('&')
    .forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
  return form
}

function parseHeaders(rawHeaders) {
  var headers = new Headers()
  // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
  // https://tools.ietf.org/html/rfc7230#section-3.2
  var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ')
  preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
    var parts = line.split(':')
    var key = parts.shift().trim()
    if (key) {
      var value = parts.join(':').trim()
      headers.append(key, value)
    }
  })
  return headers
}

Body.call(Request.prototype)

export function Response(bodyInit, options) {
  if (!options) {
    options = {}
  }

  this.type = 'default'
  this.status = options.status === undefined ? 200 : options.status
  this.ok = this.status >= 200 && this.status < 300
  this.statusText = 'statusText' in options ? options.statusText : ''
  this.headers = new Headers(options.headers)
  this.url = options.url || ''
  this._initBody(bodyInit)
}

Body.call(Response.prototype)

Response.prototype.clone = function() {
  return new Response(this._bodyInit, {
    status: this.status,
    statusText: this.statusText,
    headers: new Headers(this.headers),
    url: this.url
  })
}

Response.error = function() {
  var response = new Response(null, {status: 0, statusText: ''})
  response.type = 'error'
  return response
}

var redirectStatuses = [301, 302, 303, 307, 308]

Response.redirect = function(url, status) {
  if (redirectStatuses.indexOf(status) === -1) {
    throw new RangeError('Invalid status code')
  }

  return new Response(null, {status: status, headers: {location: url}})
}

export var DOMException = self.DOMException
try {
  new DOMException()
} catch (err) {
  DOMException = function(message, name) {
    this.message = message
    this.name = name
    var error = Error(message)
    this.stack = error.stack
  }
  DOMException.prototype = Object.create(Error.prototype)
  DOMException.prototype.constructor = DOMException
}

export function fetch(input, init) {
  return new Promise(function(resolve, reject) {
    var request = new Request(input, init)

    if (request.signal && request.signal.aborted) {
      return reject(new DOMException('Aborted', 'AbortError'))
    }

    var xhr = new XMLHttpRequest()

    function abortXhr() {
      xhr.abort()
    }

    xhr.onload = function() {
      var options = {
        status: xhr.status,
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders() || '')
      }
      options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
      var body = 'response' in xhr ? xhr.response : xhr.responseText
      setTimeout(function() {
        resolve(new Response(body, options))
      }, 0)
    }

    xhr.onerror = function() {
      setTimeout(function() {
        reject(new TypeError('Network request failed'))
      }, 0)
    }

    xhr.ontimeout = function() {
      setTimeout(function() {
        reject(new TypeError('Network request failed'))
      }, 0)
    }

    xhr.onabort = function() {
      setTimeout(function() {
        reject(new DOMException('Aborted', 'AbortError'))
      }, 0)
    }

    function fixUrl(url) {
      try {
        return url === '' && self.location.href ? self.location.href : url
      } catch (e) {
        return url
      }
    }

    xhr.open(request.method, fixUrl(request.url), true)

    if (request.credentials === 'include') {
      xhr.withCredentials = true
    } else if (request.credentials === 'omit') {
      xhr.withCredentials = false
    }

    if ('responseType' in xhr) {
      if (support.blob) {
        xhr.responseType = 'blob'
      } else if (
        support.arrayBuffer &&
        request.headers.get('Content-Type') &&
        request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1
      ) {
        xhr.responseType = 'arraybuffer'
      }
    }

    request.headers.forEach(function(value, name) {
      xhr.setRequestHeader(name, value)
    })

    if (request.signal) {
      request.signal.addEventListener('abort', abortXhr)

      xhr.onreadystatechange = function() {
        // DONE (success or failure)
        if (xhr.readyState === 4) {
          request.signal.removeEventListener('abort', abortXhr)
        }
      }
    }

    xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
  })
}

fetch.polyfill = true

if (!self.fetch) {
  self.fetch = fetch
  self.Headers = Headers
  self.Request = Request
  self.Response = Response
}
<commit_msg>use `this` if `self` is not defined<commit_after>(function(self) {
  var support = {
    searchParams: 'URLSearchParams' in self,
    iterable: 'Symbol' in self && 'iterator' in Symbol,
    blob:
      'FileReader' in self &&
      'Blob' in self &&
      (function() {
        try {
          new Blob()
          return true
        } catch (e) {
          return false
        }
      })(),
    formData: 'FormData' in self,
    arrayBuffer: 'ArrayBuffer' in self
  }

  function isDataView(obj) {
    return obj && DataView.prototype.isPrototypeOf(obj)
  }

  if (support.arrayBuffer) {
    var viewClasses = [
      '[object Int8Array]',
      '[object Uint8Array]',
      '[object Uint8ClampedArray]',
      '[object Int16Array]',
      '[object Uint16Array]',
      '[object Int32Array]',
      '[object Uint32Array]',
      '[object Float32Array]',
      '[object Float64Array]'
    ]

    var isArrayBufferView =
      ArrayBuffer.isView ||
      function(obj) {
        return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
      }
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = String(name)
    }
    if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = String(value)
    }
    return value
  }

  // Build a destructive iterator for the value list
  function iteratorFor(items) {
    var iterator = {
      next: function() {
        var value = items.shift()
        return {done: value === undefined, value: value}
      }
    }

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      }
    }

    return iterator
  }

  export function Headers(headers) {
    this.map = {}

    if (headers instanceof Headers) {
      headers.forEach(function(value, name) {
        this.append(name, value)
      }, this)
    } else if (Array.isArray(headers)) {
      headers.forEach(function(header) {
        this.append(header[0], header[1])
      }, this)
    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        this.append(name, headers[name])
      }, this)
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name)
    value = normalizeValue(value)
    var oldValue = this.map[name]
    this.map[name] = oldValue ? oldValue + ', ' + value : value
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)]
  }

  Headers.prototype.get = function(name) {
    name = normalizeName(name)
    return this.has(name) ? this.map[name] : null
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  }

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = normalizeValue(value)
  }

  Headers.prototype.forEach = function(callback, thisArg) {
    for (var name in this.map) {
      if (this.map.hasOwnProperty(name)) {
        callback.call(thisArg, this.map[name], name, this)
      }
    }
  }

  Headers.prototype.keys = function() {
    var items = []
    this.forEach(function(value, name) {
      items.push(name)
    })
    return iteratorFor(items)
  }

  Headers.prototype.values = function() {
    var items = []
    this.forEach(function(value) {
      items.push(value)
    })
    return iteratorFor(items)
  }

  Headers.prototype.entries = function() {
    var items = []
    this.forEach(function(value, name) {
      items.push([name, value])
    })
    return iteratorFor(items)
  }

  if (support.iterable) {
    Headers.prototype[Symbol.iterator] = Headers.prototype.entries
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    var promise = fileReaderReady(reader)
    reader.readAsArrayBuffer(blob)
    return promise
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    var promise = fileReaderReady(reader)
    reader.readAsText(blob)
    return promise
  }

  function readArrayBufferAsText(buf) {
    var view = new Uint8Array(buf)
    var chars = new Array(view.length)

    for (var i = 0; i < view.length; i++) {
      chars[i] = String.fromCharCode(view[i])
    }
    return chars.join('')
  }

  function bufferClone(buf) {
    if (buf.slice) {
      return buf.slice(0)
    } else {
      var view = new Uint8Array(buf.byteLength)
      view.set(new Uint8Array(buf))
      return view.buffer
    }
  }

  function Body() {
    this.bodyUsed = false

    this._initBody = function(body) {
      /*
        fetch-mock wraps the Response object in an ES6 Proxy to
        provide useful test harness features such as flush. However, on
        ES5 browsers without fetch or Proxy support pollyfills must be used;
        the proxy-pollyfill is unable to proxy an attribute unless it exists
        on the object before the Proxy is created. This change ensures
        Response.bodyUsed exists on the instance, while maintaining the
        semantic of setting Request.bodyUsed in the constructor before
        _initBody is called.
      */
      this.bodyUsed = this.bodyUsed
      this._bodyInit = body
      if (!body) {
        this._bodyText = ''
      } else if (typeof body === 'string') {
        this._bodyText = body
      } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
        this._bodyBlob = body
      } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
        this._bodyFormData = body
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this._bodyText = body.toString()
      } else if (support.arrayBuffer && support.blob && isDataView(body)) {
        this._bodyArrayBuffer = bufferClone(body.buffer)
        // IE 10-11 can't handle a DataView body.
        this._bodyInit = new Blob([this._bodyArrayBuffer])
      } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
        this._bodyArrayBuffer = bufferClone(body)
      } else {
        this._bodyText = body = Object.prototype.toString.call(body)
      }

      if (!this.headers.get('content-type')) {
        if (typeof body === 'string') {
          this.headers.set('content-type', 'text/plain;charset=UTF-8')
        } else if (this._bodyBlob && this._bodyBlob.type) {
          this.headers.set('content-type', this._bodyBlob.type)
        } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
          this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
        }
      }
    }

    if (support.blob) {
      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyArrayBuffer) {
          return Promise.resolve(new Blob([this._bodyArrayBuffer]))
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        if (this._bodyArrayBuffer) {
          return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
        } else {
          return this.blob().then(readBlobAsArrayBuffer)
        }
      }
    }

    this.text = function() {
      var rejected = consumed(this)
      if (rejected) {
        return rejected
      }

      if (this._bodyBlob) {
        return readBlobAsText(this._bodyBlob)
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
      } else if (this._bodyFormData) {
        throw new Error('could not read FormData body as text')
      } else {
        return Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return methods.indexOf(upcased) > -1 ? upcased : method
  }

  export function Request(input, options) {
    options = options || {}
    var body = options.body

    if (input instanceof Request) {
      if (input.bodyUsed) {
        throw new TypeError('Already read')
      }
      this.url = input.url
      this.credentials = input.credentials
      if (!options.headers) {
        this.headers = new Headers(input.headers)
      }
      this.method = input.method
      this.mode = input.mode
      this.signal = input.signal
      if (!body && input._bodyInit != null) {
        body = input._bodyInit
        input.bodyUsed = true
      }
    } else {
      this.url = String(input)
    }

    this.credentials = options.credentials || this.credentials || 'same-origin'
    if (options.headers || !this.headers) {
      this.headers = new Headers(options.headers)
    }
    this.method = normalizeMethod(options.method || this.method || 'GET')
    this.mode = options.mode || this.mode || null
    this.signal = options.signal || this.signal
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(body)
  }

  Request.prototype.clone = function() {
    return new Request(this, {body: this._bodyInit})
  }

  function decode(body) {
    var form = new FormData()
    body
      .trim()
      .split('&')
      .forEach(function(bytes) {
        if (bytes) {
          var split = bytes.split('=')
          var name = split.shift().replace(/\+/g, ' ')
          var value = split.join('=').replace(/\+/g, ' ')
          form.append(decodeURIComponent(name), decodeURIComponent(value))
        }
      })
    return form
  }

  function parseHeaders(rawHeaders) {
    var headers = new Headers()
    // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
    // https://tools.ietf.org/html/rfc7230#section-3.2
    var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ')
    preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
      var parts = line.split(':')
      var key = parts.shift().trim()
      if (key) {
        var value = parts.join(':').trim()
        headers.append(key, value)
      }
    })
    return headers
  }

  Body.call(Request.prototype)

  export function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this.type = 'default'
    this.status = options.status === undefined ? 200 : options.status
    this.ok = this.status >= 200 && this.status < 300
    this.statusText = 'statusText' in options ? options.statusText : ''
    this.headers = new Headers(options.headers)
    this.url = options.url || ''
    this._initBody(bodyInit)
  }

  Body.call(Response.prototype)

  Response.prototype.clone = function() {
    return new Response(this._bodyInit, {
      status: this.status,
      statusText: this.statusText,
      headers: new Headers(this.headers),
      url: this.url
    })
  }

  Response.error = function() {
    var response = new Response(null, {status: 0, statusText: ''})
    response.type = 'error'
    return response
  }

  var redirectStatuses = [301, 302, 303, 307, 308]

  Response.redirect = function(url, status) {
    if (redirectStatuses.indexOf(status) === -1) {
      throw new RangeError('Invalid status code')
    }

    return new Response(null, {status: status, headers: {location: url}})
  }

  export var DOMException = self.DOMException
  try {
    new DOMException()
  } catch (err) {
    DOMException = function(message, name) {
      this.message = message
      this.name = name
      var error = Error(message)
      this.stack = error.stack
    }
    DOMException.prototype = Object.create(Error.prototype)
    DOMException.prototype.constructor = DOMException
  }

  export function fetch(input, init) {
    return new Promise(function(resolve, reject) {
      var request = new Request(input, init)

      if (request.signal && request.signal.aborted) {
        return reject(new DOMException('Aborted', 'AbortError'))
      }

      var xhr = new XMLHttpRequest()

      function abortXhr() {
        xhr.abort()
      }

      xhr.onload = function() {
        var options = {
          status: xhr.status,
          statusText: xhr.statusText,
          headers: parseHeaders(xhr.getAllResponseHeaders() || '')
        }
        options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
        var body = 'response' in xhr ? xhr.response : xhr.responseText
        setTimeout(function() {
          resolve(new Response(body, options))
        }, 0)
      }

      xhr.onerror = function() {
        setTimeout(function() {
          reject(new TypeError('Network request failed'))
        }, 0)
      }

      xhr.ontimeout = function() {
        setTimeout(function() {
          reject(new TypeError('Network request failed'))
        }, 0)
      }

      xhr.onabort = function() {
        setTimeout(function() {
          reject(new DOMException('Aborted', 'AbortError'))
        }, 0)
      }

      function fixUrl(url) {
        try {
          return url === '' && self.location.href ? self.location.href : url
        } catch (e) {
          return url
        }
      }

      xhr.open(request.method, fixUrl(request.url), true)

      if (request.credentials === 'include') {
        xhr.withCredentials = true
      } else if (request.credentials === 'omit') {
        xhr.withCredentials = false
      }

      if ('responseType' in xhr) {
        if (support.blob) {
          xhr.responseType = 'blob'
        } else if (
          support.arrayBuffer &&
          request.headers.get('Content-Type') &&
          request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1
        ) {
          xhr.responseType = 'arraybuffer'
        }
      }

      request.headers.forEach(function(value, name) {
        xhr.setRequestHeader(name, value)
      })

      if (request.signal) {
        request.signal.addEventListener('abort', abortXhr)

        xhr.onreadystatechange = function() {
          // DONE (success or failure)
          if (xhr.readyState === 4) {
            request.signal.removeEventListener('abort', abortXhr)
          }
        }
      }

      xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
    })
  }

  fetch.polyfill = true

  if (!self.fetch) {
    self.fetch = fetch
    self.Headers = Headers
    self.Request = Request
    self.Response = Response
  }
})(typeof self !== 'undefined' ? self : this);
<|endoftext|>


<commit_before>'use babel'

let CompositeDisposable = null
let ClangTidyCommand = null
let ClangTidy = null
let ClangArguments = null
let ClangTidyLinter = null
let ClangTidyAutocompleteProvider = null

function initialize () {
  if (!CompositeDisposable) CompositeDisposable = require('atom').CompositeDisposable
  if (!ClangTidyCommand) ClangTidyCommand = require('./clang-tidy-command')
  if (!ClangTidy) ClangTidy = require('./clang-tidy')
  if (!ClangArguments) ClangArguments = require('./clang-arguments')
  if (!ClangTidyLinter) ClangTidyLinter = require('./clang-tidy-linter')
  if (!ClangTidyAutocompleteProvider) {
    ClangTidyAutocompleteProvider = require('./clang-tidy-autocomplete-provider')
  }
}

export default {
  subscriptions: null,

  grammars: [
    'source.c',
    'source.cpp',
    'source.objc',
    'source.objcpp'
  ],

  config: {
    clangTidyCommand: {
      title: 'clang-tidy command',
      type: 'string',
      default: 'clang-tidy'
    },
    clangCppFlags: {
      title: 'clang flags for C++',
      type: [],
      items: { type: 'string' }
    },
    clangCFlags: {
      title: 'clang flags for C',
      type: 'array',
      default: [],
      items: { type: 'string' }
    },
    clangObjectiveCppFlags: {
      title: 'clang flags for Objective C++',
      type: 'array',
      default: [],
      items: { type: 'string' }
    },
    clangObjectiveCFlags: {
      title: 'clang flags for Objective C',
      type: 'array',
      default: [],
      items: { type: 'string' }
    },
    buildPath: {
      title: 'the build pass used in clang-tools',
      type: 'string',
      default: 'compile_commands.json'
    }
  },

  activate (state) {
    initialize()

    this.clangTidyCommand = new ClangTidyCommand(
      atom.config.get('clang-tools-extra.clangTidyCommand'),
      atom.config.get('clang-tools-extra.buildPath')
    )
    this.clangArguments = new ClangArguments({
      getClangCFlags: () => atom.config.get('clang-tools-extra.clangCFlags').split(/\s+/),
      getClangCppFlags: () => atom.config.get('clang-tools-extra.clangCppFlags').split(/\s+/),
      getClangObjectiveCFlags: () => atom.config.get('clang-tools-extra.clangObjectiveCFlags').split(/\s+/),
      getClangObjectiveCppFlags: () => atom.config.get('clang-tools-extra.clangObjectiveCppFlags').split(/\s+/)
    })

    this.clangTidy = new ClangTidy(this.clangTidyCommand, this.clangArguments)

    this.clangTidyLinter = new ClangTidyLinter(this.clangTidy)

    this.provider = new ClangTidyAutocompleteProvider(this.clangTidy)
    this.provider.selector = this.grammars.map(elem => `.${elem}`).join(','),
    this.provider.inclusionPriority = 1

    this.subscriptions = new CompositeDisposable()

    // Register the commands
    this.subscriptions.add(
      atom.commands.add('atom-text-editor', {
        'clang-tools-extra:apply-all-fixes': () => this.applyAllFixes()
      })
    )
  },

  deactivate () {
    this.subscriptions.dispose()
  },

  serialize () {
    return {}
  },

  applyAllFixes () {
    const editor = atom.workspace.getActiveTextEditor()
    if (!editor) return

    this.clangTidy.applyAllFixes(editor)
  },

  provide () {
    return this.provider
  },

  provideLinter () {
    const provider = {
      name: 'clang-tools-extra',
      grammarScopes: this.grammars,
      scope: 'file',
      lintOnFly: false,
      lint: (textEditor) => this.clangTidyLinter.lint(textEditor)
    }
    return provider
  }
}
<commit_msg>Refactor main code<commit_after>'use babel'

let CompositeDisposable = null
let ClangTidyCommand = null
let ClangTidy = null
let ClangArguments = null
let ClangTidyLinter = null
let ClangTidyAutocompleteProvider = null

function initialize () {
  if (!CompositeDisposable) CompositeDisposable = require('atom').CompositeDisposable
  if (!ClangTidyCommand) ClangTidyCommand = require('./clang-tidy-command')
  if (!ClangTidy) ClangTidy = require('./clang-tidy')
  if (!ClangArguments) ClangArguments = require('./clang-arguments')
  if (!ClangTidyLinter) ClangTidyLinter = require('./clang-tidy-linter')
  if (!ClangTidyAutocompleteProvider) {
    ClangTidyAutocompleteProvider = require('./clang-tidy-autocomplete-provider')
  }
}

export default {
  subscriptions: null,

  grammars: [
    'source.c',
    'source.cpp',
    'source.objc',
    'source.objcpp'
  ],

  config: {
    clangTidyCommand: {
      title: 'clang-tidy command',
      type: 'string',
      default: 'clang-tidy'
    },
    clangCppFlags: {
      title: 'clang flags for C++',
      type: [],
      items: { type: 'string' }
    },
    clangCFlags: {
      title: 'clang flags for C',
      type: 'array',
      default: [],
      items: { type: 'string' }
    },
    clangObjectiveCppFlags: {
      title: 'clang flags for Objective C++',
      type: 'array',
      default: [],
      items: { type: 'string' }
    },
    clangObjectiveCFlags: {
      title: 'clang flags for Objective C',
      type: 'array',
      default: [],
      items: { type: 'string' }
    },
    buildPath: {
      title: 'the build pass used in clang-tools',
      type: 'string',
      default: 'compile_commands.json'
    }
  },

  activate (state) {
    initialize()

    this.clangTidyCommand = new ClangTidyCommand(
      atom.config.get('clang-tools-extra.clangTidyCommand'),
      atom.config.get('clang-tools-extra.buildPath')
    )
    this.clangArguments = new ClangArguments({
      getClangCFlags: () => atom.config.get('clang-tools-extra.clangCFlags').split(/\s+/),
      getClangCppFlags: () => atom.config.get('clang-tools-extra.clangCppFlags').split(/\s+/),
      getClangObjectiveCFlags: () => atom.config.get('clang-tools-extra.clangObjectiveCFlags').split(/\s+/),
      getClangObjectiveCppFlags: () => atom.config.get('clang-tools-extra.clangObjectiveCppFlags').split(/\s+/)
    })

    this.clangTidy = new ClangTidy(this.clangTidyCommand, this.clangArguments)

    this.clangTidyLinter = new ClangTidyLinter(this.clangTidy)

    this.autocompleteProvider = new ClangTidyAutocompleteProvider(this.clangTidy)
    this.autocompleteProvider.selector = this.grammars.map(elem => `.${elem}`).join(','),
    this.autocompleteProvider.inclusionPriority = 1

    this.subscriptions = new CompositeDisposable()

    // Register the commands
    this.subscriptions.add(
      atom.commands.add('atom-text-editor', {
        'clang-tools-extra:apply-all-fixes': () => this.applyAllFixes()
      })
    )
  },

  deactivate () {
    this.subscriptions.dispose()
  },

  serialize () {
    return {}
  },

  applyAllFixes () {
    const editor = atom.workspace.getActiveTextEditor()
    if (!editor) return

    this.clangTidy.applyAllFixes(editor)
  },

  provide () {
    return this.autocompleteProvider
  },

  provideLinter () {
    const provider = {
      name: 'clang-tools-extra',
      grammarScopes: this.grammars,
      scope: 'file',
      lintOnFly: false,
      lint: (textEditor) => this.clangTidyLinter.lint(textEditor)
    }
    return provider
  }
}
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var GetTileAt = require('./GetTileAt');

/**
 * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting
 * faces are used internally for optimizing collisions against tiles. This method is mostly used
 * internally to optimize recalculating faces when only one tile has been changed.
 *
 * @function Phaser.Tilemaps.Components.CalculateFacesAt
 * @since 3.0.0
 *
 * @param {integer} tileX - The x coordinate.
 * @param {integer} tileY - The y coordinate.
 * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
 */
var CalculateFacesAt = function (tileX, tileY, layer)
{
    var tile = GetTileAt(tileX, tileY, true, layer);
    var above = GetTileAt(tileX, tileY - 1, true, layer);
    var below = GetTileAt(tileX, tileY + 1, true, layer);
    var left = GetTileAt(tileX - 1, tileY, true, layer);
    var right = GetTileAt(tileX + 1, tileY, true, layer);
    var tileCollides = tile && tile.collides;

    // Assume the changed tile has all interesting edges
    if (tileCollides)
    {
        tile.faceBottom = true;
        tile.faceBottom = true;
        tile.faceLeft = true;
        tile.faceRight = true;
    }

    // Reset edges that are shared between tile and its neighbors
    if (above && above.collides)
    {
        if (tileCollides) { tile.faceTop = false; }
        above.faceBottom = !tileCollides;
    }

    if (below && below.collides)
    {
        if (tileCollides) { tile.faceBottom = false; }
        below.faceTop = !tileCollides;
    }

    if (left && left.collides)
    {
        if (tileCollides) { tile.faceLeft = false; }
        left.faceRight = !tileCollides;
    }

    if (right && right.collides)
    {
        if (tileCollides) { tile.faceRight = false; }
        right.faceLeft = !tileCollides;
    }

    if (tile && !tile.collides) { tile.resetFaces(); }

    return tile;
};

module.exports = CalculateFacesAt;
<commit_msg>Fixes #3395<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var GetTileAt = require('./GetTileAt');

/**
 * Calculates interesting faces at the given tile coordinates of the specified layer. Interesting
 * faces are used internally for optimizing collisions against tiles. This method is mostly used
 * internally to optimize recalculating faces when only one tile has been changed.
 *
 * @function Phaser.Tilemaps.Components.CalculateFacesAt
 * @since 3.0.0
 *
 * @param {integer} tileX - The x coordinate.
 * @param {integer} tileY - The y coordinate.
 * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
 */
var CalculateFacesAt = function (tileX, tileY, layer)
{
    var tile = GetTileAt(tileX, tileY, true, layer);
    var above = GetTileAt(tileX, tileY - 1, true, layer);
    var below = GetTileAt(tileX, tileY + 1, true, layer);
    var left = GetTileAt(tileX - 1, tileY, true, layer);
    var right = GetTileAt(tileX + 1, tileY, true, layer);
    var tileCollides = tile && tile.collides;

    // Assume the changed tile has all interesting edges
    if (tileCollides)
    {
        tile.faceTop = true;
        tile.faceBottom = true;
        tile.faceLeft = true;
        tile.faceRight = true;
    }

    // Reset edges that are shared between tile and its neighbors
    if (above && above.collides)
    {
        if (tileCollides) { tile.faceTop = false; }
        above.faceBottom = !tileCollides;
    }

    if (below && below.collides)
    {
        if (tileCollides) { tile.faceBottom = false; }
        below.faceTop = !tileCollides;
    }

    if (left && left.collides)
    {
        if (tileCollides) { tile.faceLeft = false; }
        left.faceRight = !tileCollides;
    }

    if (right && right.collides)
    {
        if (tileCollides) { tile.faceRight = false; }
        right.faceLeft = !tileCollides;
    }

    if (tile && !tile.collides) { tile.resetFaces(); }

    return tile;
};

module.exports = CalculateFacesAt;
<|endoftext|>