<commit_before>Ext.define('AIDRFM.collection-create.controller.CollectionCreateController', {
    extend: 'Ext.app.Controller',

    views: [
        'CollectionCreatePanel'
    ],

    init: function () {
        this.control({

            'collection-create': {
                afterrender: this.afterRenderCollectionCreateView
            },

            "#collectionNameInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: 'Give a name to your collection. For example, Hurricane Sandy, Earthquake Japan.',
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionCodeInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: ' Collection code consists of alpha-numeric short code name to a collection. ' +
                            'Spaces are not allowed in the code name. For example, Sandy2012, EQJapan2013 are valid code names',
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionkeywordsInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: 'This field represents comma separated keywords to filter the Twitter stream.
' +
                            'General rules:
' +
                            '- Not case-sensitive ("bridge" matches "Bridge").
' +
                            '- Whole words match ("bridge" does not match "damagedbridge").

' +
                            'Multi-word queries:
' +
                            '- If you include two or more words on a query, all of them must be present in the tweet ("Brooklyn bridge" does not match a tweet that does not contain "Brooklyn" or does not contain "bridge")
' +
                            '- The words does not need to be consecutive or in that order ("Brooklyn bridge" will match "the bridge to Brooklyn")

' +
                            'Queries with or without hashtags:
' +
                            '- If you don\'t include \'#\', you also match hashtags ("bridge" matches "#bridge")
' +
                            '- If you do include \'#\', you only match hashtags ("#bridge" does not match "bridge")
',
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionGeoInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: 'This field represents a comma-separated pairs of longitude and latitude. A valid geo location represents a bounding box with southwest corner of the box coming first. Note that if you specify a geographical region, all messages posted from within that region will be collected, independently of whether they contain the keywords or not.',
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionFollowInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "Follow represents a comma-separated list of twitter users IDs to be followed. A valid twitter user id must be in the numeric format.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionDurationInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "Collection duration specifies the length in days after which the collection will be automatically stopped. An increase in duration up to 30days can be requested from AIDR admin.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionLangInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "This field is used to set a comma separated list of language codes to filter results only to the specified languages. The language codes must be a valid BCP 47 language identifier. Language filter is not a mandatory field, but it is strongly recommended if you intend to use the automatic tagger.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionTypeInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "Collection Type.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#crisisTypesInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "Collection type specifies a type of the crisis.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#CollectionLang":{
                change: function(field, newValue, oldValue){
                     var selectedValue = newValue;
                     if(field.value.length == 0){
                         this.CollectionCreateComponent.langNote.setText('* Note: if you want to use the automatic tagger, it is best that you collect for a specific language.', false);
                     }
                     else if(field.value.length > 1){
                         this.CollectionCreateComponent.langNote.setText('* Note: if you want to use the automatic tagger, it is best that you collect for one specific language.', false);
                     }
                    else{
                         this.CollectionCreateComponent.langNote.setText('');
                     }

                }
            },

            "#collectionCancelCreate": {
                click: function (btn, e, eOpts) {
                    document.location.href = BASE_URL + '/protected/home';
                }
            },

            "#collectionCreate": {
                click: function (btn, e, eOpts) {
                    CollectionCreateController.initNameAndCodeValidation();
                }
            },

            "#nameTextField": {
                blur: function (field, eOpts) {
                    CollectionCreateController.generateCollectionCode(field.getValue());
                }
            },

            "#CollectionType":{
                change: function(field, newValue, oldValue){
                     if(newValue === 'SMS'){
                         Ext.getCmp('keywordsPanel').hide();
                         Ext.getCmp('langPanel').hide();
                         Ext.getCmp('geoPanel').hide();
                         Ext.getCmp('followPanel').hide();
                         Ext.getCmp('durationDescription').hide();
                         Ext.getCmp('configurationsL').hide();
                         Ext.getCmp('geoDescription').hide();
                     } else if(newValue === 'Twitter'){
                         Ext.getCmp('keywordsPanel').show();
                         Ext.getCmp('langPanel').show();
                         Ext.getCmp('geoPanel').show();
                         Ext.getCmp('followPanel').show();
                         Ext.getCmp('durationDescription').show();
                         Ext.getCmp('configurationsL').show();
                         Ext.getCmp('geoDescription').show();
                     }
                }
            }
        });
    },

    afterRenderCollectionCreateView: function (component, eOpts) {
        AIDRFMFunctions.initMessageContainer();
        this.CollectionCreateComponent = component;
        CollectionCreateController = this;
    },

    saveCollection: function () {
        var me = this;

        var mask = AIDRFMFunctions.getMask(true, 'Saving collection ...');
        mask.show();

        if (AIDRFMFunctions.mandatoryFieldsEntered()) {
            var form = Ext.getCmp('collectionForm').getForm();
            Ext.Ajax.request({
                url: 'collection/save.action',
                method: 'POST',
                params: {
                    name: Ext.String.trim( form.findField('name').getValue() ),
                    code: Ext.String.trim( form.findField('code').getValue() ),
                    track: Ext.String.trim( form.findField('track').getValue() ),
                    follow: Ext.String.trim( form.findField('follow').getValue() ),
                    geo: Ext.String.trim( form.findField('geo').getValue() ),
                    langFilters: form.findField('langFilters').getValue(),
                    durationHours: form.findField('durationHours').getValue(),
                    crisisType: form.findField('crisisType').getValue(),
                    collectionType: form.findField('collectionType').getValue()
                },
                headers: {
                    'Accept': 'application/json'
                },
                success: function (response) {
                    AIDRFMFunctions.setAlert("Info", ["Collection created successfully.", "You will be redirected to Home screen."]);
                    mask.hide();

                    var maskRedirect = AIDRFMFunctions.getMask(true, 'Redirecting ...');
                    maskRedirect.show();

//                    wait for 3 sec to let user read information box
                    var isFirstRun = true;
                    Ext.TaskManager.start({
                        run: function () {
                            if (!isFirstRun) {
                                document.location.href = BASE_URL + '/protected/home';
                            }
                            isFirstRun = false;
                        },
                        interval: 3 * 1000
                    });
                }
            });
        } else {
            mask.hide();
        }
    },

    isExist: function () {
        var me = this;

        var form = Ext.getCmp('collectionForm').getForm();
        var code = form.findField('code');
        Ext.Ajax.request({
            url: 'collection/exist.action',
            method: 'GET',
            params: {
                code: code.getValue()
            },
            headers: {
                'Accept': 'application/json'
            },
            success: function (response) {
                me.checkCount--;

                var response = Ext.decode(response.responseText);
                if (response.data) {
                    AIDRFMFunctions.setAlert('Error', 'Collection Code already exist. Please select another code');
                    code.markInvalid("Collection Code already exist. Please select another code");
                } else {
                    if (me.checkCount == 0) {
                        me.saveCollection();
                    }
                }
            }
        });
    },

    isExistName: function () {
        var me = this;

        var form = Ext.getCmp('collectionForm').getForm();
        var name = form.findField('name');
        Ext.Ajax.request({
            url: 'collection/existName.action',
            method: 'GET',
            params: {
                name: name.getValue()
            },
            headers: {
                'Accept': 'application/json'
            },
            success: function (response) {
                me.checkCount--;

                var response = Ext.decode(response.responseText);
                if (response.data) {
                    AIDRFMFunctions.setAlert('Error', [
                        'The name of the collection you have selected is already taken. Please enter a more specific name for your collection indicating a more specific time, location, and/or purpose.',
                        ' ',
                        'Examples:',
                        '"Earthquake in Chile in Feb. 2014"',
                        '"Earthquake in Concepcion, Chile in 2014"',
                        '"Consequences of earthquake in Concepcion, Chile in 2014"'
                    ]);
                    name.markInvalid("Collection Name already exist. Please select another name");
                } else {
                    if (me.checkCount == 0) {
                        me.saveCollection();
                    }
                }
            }
        });
    },

    initNameAndCodeValidation: function() {
        this.checkCount = 2;
        this.isExist();
        this.isExistName();
    },

    generateCollectionCode: function(value) {
        var me = this;

        var currentCode = me.CollectionCreateComponent.codeE.getValue();
        if (currentCode != ''){
            return false;
        }

        var v = Ext.util.Format.trim(value);
        v = v.replace(/ /g, '_');
        v = Ext.util.Format.lowercase(v);

        var date = Ext.Date.format(new Date(), "Y-m-");
        date = Ext.util.Format.lowercase(date);

        var length = value.length;
        if (length > 56){
            length = 56;
        }

        var result = date + Ext.util.Format.substr(v, 0, length);
        me.isExistForGenerated(result);
    },

    isExistForGenerated: function (code, attempt) {
        var me = this;

        Ext.Ajax.request({
            url: 'collection/exist.action',
            method: 'GET',
            params: {
                code: code
            },
            headers: {
                'Accept': 'application/json'
            },
            success: function (response) {
                var response = Ext.decode(response.responseText);
                if (response.data) {
                    if (attempt) {
                        me.modifyGeneratedCode(code, attempt);
                    } else {
                        me.modifyGeneratedCode(code, 0);
                    }
                } else {
                    me.CollectionCreateComponent.codeE.setValue(code);
                }
            }
        });
    },

    modifyGeneratedCode: function(oldCode, attempt) {
        var me = this;

        var date = Ext.util.Format.substr(oldCode, oldCode.length - 7, oldCode.length),
            code = Ext.util.Format.substr(oldCode, 0, oldCode.length - 9);

        var result = code + '_' + attempt + date;
        me.isExistForGenerated(result, attempt + 1);
    }

});<commit_msg>Redirection issue fixed.<commit_after>Ext.define('AIDRFM.collection-create.controller.CollectionCreateController', {
    extend: 'Ext.app.Controller',

    views: [
        'CollectionCreatePanel'
    ],

    init: function () {
        this.control({

            'collection-create': {
                afterrender: this.afterRenderCollectionCreateView
            },

            "#collectionNameInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: 'Give a name to your collection. For example, Hurricane Sandy, Earthquake Japan.',
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionCodeInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: ' Collection code consists of alpha-numeric short code name to a collection. ' +
                            'Spaces are not allowed in the code name. For example, Sandy2012, EQJapan2013 are valid code names',
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionkeywordsInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: 'This field represents comma separated keywords to filter the Twitter stream.
' +
                            'General rules:
' +
                            '- Not case-sensitive ("bridge" matches "Bridge").
' +
                            '- Whole words match ("bridge" does not match "damagedbridge").

' +
                            'Multi-word queries:
' +
                            '- If you include two or more words on a query, all of them must be present in the tweet ("Brooklyn bridge" does not match a tweet that does not contain "Brooklyn" or does not contain "bridge")
' +
                            '- The words does not need to be consecutive or in that order ("Brooklyn bridge" will match "the bridge to Brooklyn")

' +
                            'Queries with or without hashtags:
' +
                            '- If you don\'t include \'#\', you also match hashtags ("bridge" matches "#bridge")
' +
                            '- If you do include \'#\', you only match hashtags ("#bridge" does not match "bridge")
',
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionGeoInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: 'This field represents a comma-separated pairs of longitude and latitude. A valid geo location represents a bounding box with southwest corner of the box coming first. Note that if you specify a geographical region, all messages posted from within that region will be collected, independently of whether they contain the keywords or not.',
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionFollowInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "Follow represents a comma-separated list of twitter users IDs to be followed. A valid twitter user id must be in the numeric format.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionDurationInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "Collection duration specifies the length in days after which the collection will be automatically stopped. An increase in duration up to 30days can be requested from AIDR admin.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionLangInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "This field is used to set a comma separated list of language codes to filter results only to the specified languages. The language codes must be a valid BCP 47 language identifier. Language filter is not a mandatory field, but it is strongly recommended if you intend to use the automatic tagger.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#collectionTypeInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "Collection Type.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#crisisTypesInfo": {
                render: function (infoPanel, eOpts) {
                    var tip = Ext.create('Ext.tip.ToolTip', {
                        trackMouse: true,
                        html: "Collection type specifies a type of the crisis.",
                        target: infoPanel.el,
                        dismissDelay: 0
                    });
                }
            },

            "#CollectionLang":{
                change: function(field, newValue, oldValue){
                     var selectedValue = newValue;
                     if(field.value.length == 0){
                         this.CollectionCreateComponent.langNote.setText('* Note: if you want to use the automatic tagger, it is best that you collect for a specific language.', false);
                     }
                     else if(field.value.length > 1){
                         this.CollectionCreateComponent.langNote.setText('* Note: if you want to use the automatic tagger, it is best that you collect for one specific language.', false);
                     }
                    else{
                         this.CollectionCreateComponent.langNote.setText('');
                     }

                }
            },

            "#collectionCancelCreate": {
                click: function (btn, e, eOpts) {
                    document.location.href = BASE_URL + '/protected/home';
                }
            },

            "#collectionCreate": {
                click: function (btn, e, eOpts) {
                    CollectionCreateController.initNameAndCodeValidation();
                }
            },

            "#nameTextField": {
                blur: function (field, eOpts) {
                    CollectionCreateController.generateCollectionCode(field.getValue());
                }
            },

            "#CollectionType":{
                change: function(field, newValue, oldValue){
                     if(newValue === 'SMS'){
                         Ext.getCmp('keywordsPanel').hide();
                         Ext.getCmp('langPanel').hide();
                         Ext.getCmp('geoPanel').hide();
                         Ext.getCmp('followPanel').hide();
                         Ext.getCmp('durationDescription').hide();
                         Ext.getCmp('configurationsL').hide();
                         Ext.getCmp('geoDescription').hide();
                     } else if(newValue === 'Twitter'){
                         Ext.getCmp('keywordsPanel').show();
                         Ext.getCmp('langPanel').show();
                         Ext.getCmp('geoPanel').show();
                         Ext.getCmp('followPanel').show();
                         Ext.getCmp('durationDescription').show();
                         Ext.getCmp('configurationsL').show();
                         Ext.getCmp('geoDescription').show();
                     }
                }
            }
        });
    },

    afterRenderCollectionCreateView: function (component, eOpts) {
        AIDRFMFunctions.initMessageContainer();
        this.CollectionCreateComponent = component;
        CollectionCreateController = this;
    },

    saveCollection: function () {
        var me = this;

        var mask = AIDRFMFunctions.getMask(true, 'Saving collection ...');
        mask.show();

        if (AIDRFMFunctions.mandatoryFieldsEntered()) {
            var form = Ext.getCmp('collectionForm').getForm();
            Ext.Ajax.request({
                url: 'collection/save.action',
                method: 'POST',
                params: {
                    name: Ext.String.trim( form.findField('name').getValue() ),
                    code: Ext.String.trim( form.findField('code').getValue() ),
                    track: Ext.String.trim( form.findField('track').getValue() ),
                    follow: Ext.String.trim( form.findField('follow').getValue() ),
                    geo: Ext.String.trim( form.findField('geo').getValue() ),
                    langFilters: form.findField('langFilters').getValue(),
                    durationHours: form.findField('durationHours').getValue(),
                    crisisType: form.findField('crisisType').getValue(),
                    collectionType: form.findField('collectionType').getValue()
                },
                headers: {
                    'Accept': 'application/json'
                },
                success: function (response) {
                    AIDRFMFunctions.setAlert("Info", ["Collection created successfully.", "You will be redirected to the collection details page."]);
                    mask.hide();

                    var maskRedirect = AIDRFMFunctions.getMask(true, 'Redirecting ...');
                    maskRedirect.show();

//                    wait for 3 sec to let user read information box
                    var isFirstRun = true;
                    Ext.TaskManager.start({
                        run: function () {
                            if (!isFirstRun) {
                                document.location.href = BASE_URL + '/protected/'+ form.findField('code').getValue() +'/collection-details';
                            }
                            isFirstRun = false;
                        },
                        interval: 3 * 1000
                    });
                }
            });
        } else {
            mask.hide();
        }
    },

    isExist: function () {
        var me = this;

        var form = Ext.getCmp('collectionForm').getForm();
        var code = form.findField('code');
        Ext.Ajax.request({
            url: 'collection/exist.action',
            method: 'GET',
            params: {
                code: code.getValue()
            },
            headers: {
                'Accept': 'application/json'
            },
            success: function (response) {
                me.checkCount--;

                var response = Ext.decode(response.responseText);
                if (response.data) {
                    AIDRFMFunctions.setAlert('Error', 'Collection Code already exist. Please select another code');
                    code.markInvalid("Collection Code already exist. Please select another code");
                } else {
                    if (me.checkCount == 0) {
                        me.saveCollection();
                    }
                }
            }
        });
    },

    isExistName: function () {
        var me = this;

        var form = Ext.getCmp('collectionForm').getForm();
        var name = form.findField('name');
        Ext.Ajax.request({
            url: 'collection/existName.action',
            method: 'GET',
            params: {
                name: name.getValue()
            },
            headers: {
                'Accept': 'application/json'
            },
            success: function (response) {
                me.checkCount--;

                var response = Ext.decode(response.responseText);
                if (response.data) {
                    AIDRFMFunctions.setAlert('Error', [
                        'The name of the collection you have selected is already taken. Please enter a more specific name for your collection indicating a more specific time, location, and/or purpose.',
                        ' ',
                        'Examples:',
                        '"Earthquake in Chile in Feb. 2014"',
                        '"Earthquake in Concepcion, Chile in 2014"',
                        '"Consequences of earthquake in Concepcion, Chile in 2014"'
                    ]);
                    name.markInvalid("Collection Name already exist. Please select another name");
                } else {
                    if (me.checkCount == 0) {
                        me.saveCollection();
                    }
                }
            }
        });
    },

    initNameAndCodeValidation: function() {
        this.checkCount = 2;
        this.isExist();
        this.isExistName();
    },

    generateCollectionCode: function(value) {
        var me = this;

        var currentCode = me.CollectionCreateComponent.codeE.getValue();
        if (currentCode != ''){
            return false;
        }

        var v = Ext.util.Format.trim(value);
        v = v.replace(/ /g, '_');
        v = Ext.util.Format.lowercase(v);

        var date = Ext.Date.format(new Date(), "Y-m-");
        date = Ext.util.Format.lowercase(date);

        var length = value.length;
        if (length > 56){
            length = 56;
        }

        var result = date + Ext.util.Format.substr(v, 0, length);
        me.isExistForGenerated(result);
    },

    isExistForGenerated: function (code, attempt) {
        var me = this;

        Ext.Ajax.request({
            url: 'collection/exist.action',
            method: 'GET',
            params: {
                code: code
            },
            headers: {
                'Accept': 'application/json'
            },
            success: function (response) {
                var response = Ext.decode(response.responseText);
                if (response.data) {
                    if (attempt) {
                        me.modifyGeneratedCode(code, attempt);
                    } else {
                        me.modifyGeneratedCode(code, 0);
                    }
                } else {
                    me.CollectionCreateComponent.codeE.setValue(code);
                }
            }
        });
    },

    modifyGeneratedCode: function(oldCode, attempt) {
        var me = this;

        var date = Ext.util.Format.substr(oldCode, oldCode.length - 7, oldCode.length),
            code = Ext.util.Format.substr(oldCode, 0, oldCode.length - 9);

        var result = code + '_' + attempt + date;
        me.isExistForGenerated(result, attempt + 1);
    }

});<|endoftext|>


<commit_before>import React from 'react'
import { storiesOf, action } from '@storybook/react'
import Input, {
  Presets,
  InvisibleInput,
  SearchInput,
} from 'fyndiq-component-input'

storiesOf('Input/Input', module)
  .addWithInfo('default', () => <Input onChange={action('onChange')} />)
  .addWithInfo('debounced', () => (
    <Input debouncedOnChange={action('debouncedOnChange')} />
  ))

storiesOf('Input/Presets', module).addWithInfo('with presets', () => (
  <Presets
    presets={['Stockholm', 'Göteborg', 'Luleå', 'Kiruna', 'Test city name']}
    onChange={action('onChange')}
  />
))

storiesOf('Input/Invisible', module).addWithInfo('default', () => (
  <InvisibleInput value="initial value" onChange={action('onChange')} />
))

storiesOf('Input/Search', module)
  .addWithInfo('default', () => <SearchInput onSearch={action('onSearch')} />)
  .addWithInfo('collapsible', () => (
    <SearchInput collapsible emptyAfterSearch />
  ))
  .addWithInfo('debounced', () => (
    <SearchInput debouncedOnChange={action('debouncedOnSearch')} />
  ))
<commit_msg>:notebook: Add disabled input example<commit_after>import React from 'react'
import { storiesOf, action } from '@storybook/react'
import Input, {
  Presets,
  InvisibleInput,
  SearchInput,
} from 'fyndiq-component-input'

storiesOf('Input/Input', module)
  .addWithInfo('default', () => <Input onChange={action('onChange')} />)
  .addWithInfo('debounced', () => (
    <Input debouncedOnChange={action('debouncedOnChange')} />
  ))
  .addWithInfo('disabled', () => <Input disabled value="I'm disabled" />)

storiesOf('Input/Presets', module).addWithInfo('with presets', () => (
  <Presets
    presets={['Stockholm', 'Göteborg', 'Luleå', 'Kiruna', 'Test city name']}
    onChange={action('onChange')}
  />
))

storiesOf('Input/Invisible', module).addWithInfo('default', () => (
  <InvisibleInput value="initial value" onChange={action('onChange')} />
))

storiesOf('Input/Search', module)
  .addWithInfo('default', () => <SearchInput onSearch={action('onSearch')} />)
  .addWithInfo('collapsible', () => (
    <SearchInput collapsible emptyAfterSearch />
  ))
  .addWithInfo('debounced', () => (
    <SearchInput debouncedOnChange={action('debouncedOnSearch')} />
  ))
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var expect = chai.expect;
var rewire = require('rewire');
var mode = rewire('../../lib/core/mode.js');

describe('mode module', function() {

  describe('#set()', function() {

    it('should correctly set the mode.', function() {
      expect(mode.set('cli')).to.equal('cli');
      expect(mode.get()).to.equal('cli');
    });

    it('should validate the mode being set.', function() {
      var fn = function(modeToSet) {
        return function() {
          mode.clear();
          mode.set(modeToSet);
        };
      };
      expect(fn('cli')).to.not.throw(Error);
      expect(fn('gui')).to.not.throw(Error);
      expect(fn('foo')).to.throw(Error, 'Invalid mode: foo');
      expect(fn('bar')).to.throw(Error, 'Invalid mode: bar');
    });

    it('should throw an error if it has already been set.', function() {
      mode.clear();
      mode.set('cli');
      expect(function() { mode.set('gui'); }).to.throw('Mode has already been set: cli');
    });

  });

});
<commit_msg>#164: no idea about this one<commit_after>'use strict';

var chai = require('chai');
var expect = chai.expect;
var rewire = require('rewire');
var mode = rewire('../../lib/core/mode.js');

describe('mode module', function() {

  describe('#set()', function() {

    it('should correctly set the mode.', function() {
      expect(mode.set('cli')).to.equal('cli');
      expect(mode.get()).to.equal('cli');
    });

    it('should validate the mode being set.', function() {
      var fn = function(modeToSet) {
        return function() {
          mode.clear();
          mode.set(modeToSet);
        };
      };
      expect(fn('cli')).to.not.throw(Error);
      expect(fn('gui')).to.not.throw(Error);
      expect(fn('foo')).to.throw(Error, 'Invalid mode: foo');
      expect(fn('bar')).to.throw(Error, 'Invalid mode: bar');
    });

    it('should throw an error if it has already been set.', function() {
      mode.clear();
      mode.set('cli');
      expect(function() { mode.set('gui'); }).to.throw('Mode has already been set: cli');
    });

  });

});
<|endoftext|>


<commit_before>import {shallowMount} from "@vue/test-utils";
import Linkable from '@inkline/inkline/src/components/Linkable';

const RouterLink = {
    name: 'RouterLink',
    render() {}
};

describe('Components', () => {
    describe('Linkable', () => {
        let wrapper;

        beforeEach(() => {
            wrapper = shallowMount({
                name: 'LinkableComponent',
                template: '<div/>',
                extends: Linkable
            }, {
                components: {
                    RouterLink
                }
            });
        });

        it('should be named correctly', () => {
            expect(Linkable.name).toEqual('ILinkable');
        });

        describe('props', () => {
            describe('tag', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.tag).toBeDefined();
                    expect(wrapper.vm.tag).toEqual('a');
                });
            });

            describe('tabindex', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.tabindex).toBeDefined();
                    expect(wrapper.vm.tabindex).toEqual(-1);
                });
            });
        });

        describe('data()', () => {
            describe('routerComponent', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.routerComponent).toBeDefined();
                });

                it('should equal router-link', () => {
                    expect(wrapper.vm.routerComponent).toEqual('router-link');
                });

                it('should equal nuxt-link if nuxt is defined', () => {
                    wrapper = shallowMount({
                        name: 'LinkableComponent',
                        template: '<div/>',
                        extends: Linkable
                    }, {
                        components: {
                            RouterLink
                        },
                        mocks: {
                            $nuxt: true
                        }
                    });

                    expect(wrapper.vm.routerComponent).toEqual('nuxt-link');
                });
            });
        });

        describe('computed', () => {
            describe('isTag', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.isTag).toBeDefined();
                });

                it('should be <span> tag by default', () => {
                    expect(wrapper.vm.isTag).toEqual('a');
                });

                it('should be <a> tag if "href" attribute is provided', () => {
                    wrapper.vm.$attrs.href = true;

                    expect(wrapper.vm.isTag).toEqual('a');
                });

                it('should be <router-link> tag if "to" attribute is provided', () => {
                    wrapper.vm.$attrs.to = true;

                    expect(wrapper.vm.isTag).toEqual('router-link');
                });
            });

            describe('isComponent', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.isComponent).toBeDefined();
                });

                it('should return true if tag is equal to routerComponent', () => {
                    wrapper.setProps({ tag: 'router-link' });

                    expect(wrapper.vm.isComponent).toEqual(true);
                });

                it('should return false if tag is not equal to routerComponent', () => {
                    wrapper.setProps({ tag: 'div' });

                    expect(wrapper.vm.isComponent).toEqual(false);
                });
            });
        });
    });
});
<commit_msg>Added tests for onClick method for Linkable.<commit_after>import {shallowMount} from "@vue/test-utils";
import Linkable from '@inkline/inkline/src/components/Linkable';

const RouterLink = {
    name: 'RouterLink',
    render() {}
};

describe('Components', () => {
    describe('Linkable', () => {
        let wrapper;

        beforeEach(() => {
            wrapper = shallowMount({
                name: 'LinkableComponent',
                template: '<div/>',
                extends: Linkable
            }, {
                components: {
                    RouterLink
                }
            });
        });

        it('should be named correctly', () => {
            expect(Linkable.name).toEqual('ILinkable');
        });

        describe('props', () => {
            describe('tag', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.tag).toBeDefined();
                    expect(wrapper.vm.tag).toEqual('a');
                });
            });

            describe('tabindex', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.tabindex).toBeDefined();
                    expect(wrapper.vm.tabindex).toEqual(-1);
                });
            });
        });

        describe('data()', () => {
            describe('routerComponent', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.routerComponent).toBeDefined();
                });

                it('should equal router-link', () => {
                    expect(wrapper.vm.routerComponent).toEqual('router-link');
                });

                it('should equal nuxt-link if nuxt is defined', () => {
                    wrapper = shallowMount({
                        name: 'LinkableComponent',
                        template: '<div/>',
                        extends: Linkable
                    }, {
                        components: {
                            RouterLink
                        },
                        mocks: {
                            $nuxt: true
                        }
                    });

                    expect(wrapper.vm.routerComponent).toEqual('nuxt-link');
                });
            });
        });

        describe('computed', () => {
            describe('isTag', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.isTag).toBeDefined();
                });

                it('should be <span> tag by default', () => {
                    expect(wrapper.vm.isTag).toEqual('a');
                });

                it('should be <a> tag if "href" attribute is provided', () => {
                    wrapper.vm.$attrs.href = true;

                    expect(wrapper.vm.isTag).toEqual('a');
                });

                it('should be <router-link> tag if "to" attribute is provided', () => {
                    wrapper.vm.$attrs.to = true;

                    expect(wrapper.vm.isTag).toEqual('router-link');
                });
            });

            describe('isComponent', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.isComponent).toBeDefined();
                });

                it('should return true if tag is equal to routerComponent', () => {
                    wrapper.setProps({ tag: 'router-link' });

                    expect(wrapper.vm.isComponent).toEqual(true);
                });

                it('should return false if tag is not equal to routerComponent', () => {
                    wrapper.setProps({ tag: 'div' });

                    expect(wrapper.vm.isComponent).toEqual(false);
                });
            });
        });

        describe('methods', () => {
            describe('onClick', () => {
                it('should be defined', () => {
                    expect(wrapper.vm.onClick).toBeDefined();
                });

                it('should emit click event', () => {
                    const spy = jest.spyOn(wrapper.vm, '$emit');
                    const e = {};

                    wrapper.vm.onClick(e);

                    expect(spy).toHaveBeenCalledWith('click', e);
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>/* globals getAvatarUrlFromUsername */

const URL = Npm.require('url');
const QueryString = Npm.require('querystring');
const recursiveRemove =
	(message, deep = 0) => {
        if(message) {
    		if('attachments' in message && deep < RocketChat.settings.get('Message_QuoteChainLimit')) {
	            message.attachments.map((msg) => recursiveRemove(msg, deep + 1));
	        } else {
	            delete(message.attachments);
	        }
	    }
        return message;
    }

RocketChat.callbacks.add('beforeSaveMessage', (msg) => {
	if (msg && msg.urls) {
		msg.urls.forEach((item) => {
			if (item.url.indexOf(Meteor.absoluteUrl()) === 0) {
				const urlObj = URL.parse(item.url);
				if (urlObj.query) {
					const queryString = QueryString.parse(urlObj.query);
					if (_.isString(queryString.msg)) { // Jump-to query param
						const jumpToMessage = recursiveRemove(RocketChat.models.Messages.findOneById(queryString.msg));
						if (jumpToMessage) {
							msg.attachments = msg.attachments || [];
							msg.attachments.push({
								'text' : jumpToMessage.msg,
								'translations': jumpToMessage.translations,
								'author_name' : jumpToMessage.alias || jumpToMessage.u.username,
								'author_icon' : getAvatarUrlFromUsername(jumpToMessage.u.username),
								'message_link' : item.url,
								'attachments' : jumpToMessage.attachments || [],
								'ts': jumpToMessage.ts
							});
							item.ignoreParse = true;
						}
					}
				}
			}
		});
	}
	return msg;
}, RocketChat.callbacks.priority.LOW, 'jumpToMessage');
<commit_msg>codacy bot hates me<commit_after>/* globals getAvatarUrlFromUsername */

const URL = Npm.require('url');
const QueryString = Npm.require('querystring');
const recursiveRemove = (message, deep = 0) => {
	if (message) {
		if ('attachments' in message && deep < RocketChat.settings.get('Message_QuoteChainLimit')) {
			message.attachments.map((msg) => recursiveRemove(msg, deep + 1));
		} else {
			delete(message.attachments);
		}
	}
	return message;
}

RocketChat.callbacks.add('beforeSaveMessage', (msg) => {
	if (msg && msg.urls) {
		msg.urls.forEach((item) => {
			if (item.url.indexOf(Meteor.absoluteUrl()) === 0) {
				const urlObj = URL.parse(item.url);
				if (urlObj.query) {
					const queryString = QueryString.parse(urlObj.query);
					if (_.isString(queryString.msg)) { // Jump-to query param
						const jumpToMessage = recursiveRemove(RocketChat.models.Messages.findOneById(queryString.msg));
						if (jumpToMessage) {
							msg.attachments = msg.attachments || [];
							msg.attachments.push({
								'text' : jumpToMessage.msg,
								'translations': jumpToMessage.translations,
								'author_name' : jumpToMessage.alias || jumpToMessage.u.username,
								'author_icon' : getAvatarUrlFromUsername(jumpToMessage.u.username),
								'message_link' : item.url,
								'attachments' : jumpToMessage.attachments || [],
								'ts': jumpToMessage.ts
							});
							item.ignoreParse = true;
						}
					}
				}
			}
		});
	}
	return msg;
}, RocketChat.callbacks.priority.LOW, 'jumpToMessage');
<|endoftext|>


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

import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight
} from 'react-native';

var appVer = "v0.1";
var buildVer = "2017.03.14#6";

// ♬♪♫🎶🎵🎼

export default class Menu extends Component {

static navigationOptions = {
    title: "♬♪",
  };

  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([
        {
          title: 'Note to play',
          rowId: 0
        },
        {
          title: 'Flash cards',
          rowId: 1
        }
      ])
    };
  }

_pressRow(rowId){
  console.log('rowId: ', rowId);

  const { navigate } = this.props.navigation;

  if(rowId == 0){
      navigate('Note', { data: '' });
  }
  else if(rowId == 1){
    navigate('Flashcard', { data: '' });
  }
}

  render() {

    return (

      <View style = {styles.container}>
      <ListView
          style = {styles.menuList}
          dataSource={this.state.dataSource}
          renderRow={(rowData) => {
            return (
              <TouchableHighlight onPress={() => {
                    this._pressRow(rowData.rowId);
                  }}>
              <View>
                <View style={styles.row}>
                  <Text style={styles.text}>
                    {rowData.title}
                  </Text>
                </View>
              </View>
            </TouchableHighlight>

              )
          }
        }
        />
        <Text style={styles.version}>{appVer} ({buildVer})</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',

    },

    menuList:{
      padding: 20,
    },

     row: {
      // flexDirection: 'row',
      justifyContent: 'center',
      padding: 10,
      backgroundColor: '#F6F6F6',
      margin: 4,
    },

    thumb: {
      width: 64,
      height: 64,
    },

    text: {
      flex: 1,
    },

    version:{
      fontSize: 10,
      color: 'gray',
      padding:6,
    }

});

<commit_msg>version updated to #7<commit_after>
import React, { Component } from 'react';

import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight
} from 'react-native';

var appVer = "v0.1";
var buildVer = "2017.03.14#7";

// ♬♪♫🎶🎵🎼

export default class Menu extends Component {

static navigationOptions = {
    title: "♬♪",
  };

  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([
        {
          title: 'Note to play',
          rowId: 0
        },
        {
          title: 'Flash cards',
          rowId: 1
        }
      ])
    };
  }

_pressRow(rowId){
  console.log('rowId: ', rowId);

  const { navigate } = this.props.navigation;

  if(rowId == 0){
      navigate('Note', { data: '' });
  }
  else if(rowId == 1){
    navigate('Flashcard', { data: '' });
  }
}

  render() {

    return (

      <View style = {styles.container}>
      <ListView
          style = {styles.menuList}
          dataSource={this.state.dataSource}
          renderRow={(rowData) => {
            return (
              <TouchableHighlight onPress={() => {
                    this._pressRow(rowData.rowId);
                  }}>
              <View>
                <View style={styles.row}>
                  <Text style={styles.text}>
                    {rowData.title}
                  </Text>
                </View>
              </View>
            </TouchableHighlight>

              )
          }
        }
        />
        <Text style={styles.version}>{appVer} ({buildVer})</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',

    },

    menuList:{
      padding: 20,
    },

     row: {
      // flexDirection: 'row',
      justifyContent: 'center',
      padding: 10,
      backgroundColor: '#F6F6F6',
      margin: 4,
    },

    thumb: {
      width: 64,
      height: 64,
    },

    text: {
      flex: 1,
    },

    version:{
      fontSize: 10,
      color: 'gray',
      padding:6,
    }

});

<|endoftext|>


<commit_before>/*jshint node:true, es3:false, regexp:false, evil:true*/

'use strict';

var fs        = require('fs');
var rjs       = require('requirejs');
var UglifyJS  = require('uglify-js');
var cleanCSS  = require('clean-css');
var gzip      = require('gzip-js');
var mout      = require('mout');

module.exports = function (task) {
    task
    .id('build')
    .name('Build')
    .author('Indigo United')
    .description('Build project')
    .option('env', 'The environment to build', 'prod')

    .setup(function (opts, ctx, next) {
        // Validate environment
        if (opts.env === 'dev') {
            return next(new Error('dev environment can\'t be built'));
        }

        var cwd = process.cwd();

        // Expose the version in the opts
        // Convert from decimal base to base36 to decrease the size of the number
        opts.version = Date.now().toString(36);

        // Set some necessary vars to be used bellow
        opts.targetDir = cwd  + '/web/' + opts.env;
        opts.tempDir = cwd + '/tmp';
        opts.projectDir = cwd;

        ctx.log.writeln('Will build version ' + opts.version.green);

        next();
    })

    .do('rm', {
        description: 'Clean up previous build',
        options: {
            files: ['{{tempDir}}', '{{targetDir}}']
        }
    })
    .do('mkdir', {
        description: 'Create build folder',
        options: {
            dirs: ['{{tempDir}}', '{{targetDir}}']
        }
    })
    .do('cp', {
        description: 'Copy necessary files to temporary folder',
        options: {
            files: {
                '{{projectDir}}/app/**/*': '{{tempDir}}/app/',
                '{{projectDir}}/src/**/*': '{{tempDir}}/src/',
                '{{projectDir}}/bower_components/**/*': '{{tempDir}}/bower_components/',
                '{{projectDir}}/*': '{{tempDir}}/'
            }
        }
    })
    .do(function (opts, ctx, next) {
        var loaderFile = opts.tempDir + '/app/loader.js';

        fs.readFile(loaderFile, function (err, contents) {
            var start,
                end,
                config;

            if (err) {
                return next(err);
            }

            contents = contents.toString();
            start = contents.indexOf('({');
            end = contents.indexOf('});');

            if (start === -1 || end === -1) {
                return next(new Error('Could not locate start/end of loader config'));
            }

            start += 1;
            end += 1;

            try {
                eval('config = ' + contents.slice(start, end));
            } catch (err) {
                return next(err);
            }

            // Pass config bellow
            opts.loader = {
                start: start,
                end: end,
                contents: contents,
                config: config
            };

            next();
        });
    }, {
        description: 'Read loader config'
    })
    .do(function (opts, ctx, next) {
        var loader = opts.loader,
            config = loader.config,
            configStr = loader.contents,
            pkg;

        // Change baseUrl
        config.baseUrl = '/' + opts.env + '/src',

        // Change app-config path to point to the correct environment
        config.map['*']['app-config'] = '../app/config/config_' + opts.env;

        // Replace css package location to use require-css
        // We use curl-css in dev because it works on IE9 but it's not
        // compatible with r.js builder
        pkg = config.packages && mout.array.find(config.packages, function (pkg) {
            return pkg.name === 'css';
        });
        if (pkg) {
            pkg.location = '../bower_components/require-css';
            pkg.main = 'css';
        }

        // Set cache busting
        config.urlArgs = opts.version;

        // Write back config
        configStr = configStr.slice(0, loader.start) + JSON.stringify(config, null, '    ') + configStr.substr(loader.end);
        fs.writeFile(opts.tempDir + '/app/loader.js', configStr, next);
    }, {
        description: 'Transform loader config'
    })
    // TODO: create automaton task for this (requirejs)
    .do(function (opts, ctx, next) {
        var config;

        config = mout.object.deepMixIn(opts.loader.config, {
            baseUrl: opts.tempDir + '/src',                  // Point to the tmp folder
            name: '../bower_components/requirejs/require',   // Include require.js (you can switch to almond if compatible)
            include: ['../app/loader', '../app/bootstrap'],  // Include main files
            out: opts.tempDir + '/app.js',
            has: {
                debug: false
            },
            optimize: 'none',
            separateCSS: true,
            stubModules: ['has', 'text', 'css', 'css/css', 'css/normalize']
        });

        rjs.optimize(config, function (log) {
            ctx.log.info(log);
            next();
        }, function (err) {
            next(err);
        });
    }, {
        description: 'Run r.js optimizer'
    })
    // TODO: create automaton task for this (requirejs)
    .do(function (opts, ctx, next) {
        rjs.optimize({
            optimizeCss: 'standard.keepLines',
            cssIn: opts.tempDir + '/app.css',
            out: opts.tempDir + '/app.css',
            preserveLicenseComments: opts.licenses
        }, function (log) {
            ctx.log.write(log);

            // Replace trailing css from loader defs
            fs.readFile(opts.tempDir + '/app.js', function (err, contents) {
                if (err) {
                    return next(err);
                }

                contents = contents.toString().replace(/css!(.*?)\.css/g, 'css!$1');
                fs.writeFile(opts.tempDir + '/app.js', contents, next);
            });
        }, function (err) {
            next(err);
        });
    }, {
        description: 'Expand css files'
    })
    .do('mv', {
        description: 'Move assets to the build folder',
        options: {
            files: {
                '{{tempDir}}/src/**/assets/!(css|tmpl)/**/*': '{{targetDir}}/src/',
                '{{tempDir}}/app.js': '{{targetDir}}/app.js',
                '{{tempDir}}/app.css': '{{targetDir}}/app.css'
            }
        }
    })
    // TODO. create automaton task for cache busting or use scaffolding-replace with regexp support
    .do(function (opts, ctx, next) {
        var index = opts.projectDir + '/web/index_' + opts.env + '.html',
            css = opts.targetDir + '/app.css';

        // Update index file
        fs.readFile(index, function (err, contents) {
            if (err) {
                return next(err);
            }

            contents = contents
                .toString()
                .replace(/(app(?:\.min)?\.(?:css|js))(?:\?\w+)?/g, function (all, match) {
                    return match + '?' + opts.version;
                });

            fs.writeFile(index, contents, function (err) {
                if (err) {
                    return next(err);
                }

                // Update css file
                fs.readFile(css, function (err, contents) {
                    if (err) {
                        return next(err);
                    }

                    contents = contents
                        .toString()
                        .replace(/(url\s*\(["']?)(.*?)(["']?\))/ig, function (match, start, url, end) {
                            url = start + url.split('?', 2)[0] + '?' + opts.version + end;
                            return url;
                        });

                    fs.writeFile(css, contents, next);
                });
            });
        });
    }, {
        description: 'Apply cache busting'
    })
    // TODO: create automaton task for this (minjs)
    .do(function (opts, ctx, next) {
        // TODO: minified also contains a .map with the source mappings
        //       investigate how to integrate it!
        var minified = UglifyJS.minify(opts.targetDir + '/app.js'),
            minifiedSize = String(minified.code.length),
            gzipSize = String(gzip.zip(minified.code, {}).length);

        ctx.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + minifiedSize.green + ' bytes minified).');

        fs.writeFile(opts.targetDir + '/app.min.js', minified.code, next);
    }, {
        description: 'Minify js file'
    })
    // TODO: create automaton task for this (mincss)
    .do(function (opts, ctx, next) {
        fs.readFile(opts.targetDir + '/app.css', function (err, contents) {
            if (err) {
                return next(err);
            }

            var minified = cleanCSS.process(contents.toString(), opts),
                minifiedSize = String(minified.length),
                gzipSize = String(gzip.zip(minified, {}).length);

            ctx.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + minifiedSize.green + ' bytes minified).');

            fs.writeFile(opts.targetDir + '/app.min.css', minified, next);
        });
    }, {
        description: 'Minify css file'
    })
    .do('rm', {
        description: 'Clean up temporary files',
        options: {
            files: '{{tempDir}}'
        }
    });
};
<commit_msg>Do not cache bust data uris.<commit_after>/*jshint node:true, es3:false, regexp:false, evil:true*/

'use strict';

var fs        = require('fs');
var rjs       = require('requirejs');
var UglifyJS  = require('uglify-js');
var cleanCSS  = require('clean-css');
var gzip      = require('gzip-js');
var mout      = require('mout');

module.exports = function (task) {
    task
    .id('build')
    .name('Build')
    .author('Indigo United')
    .description('Build project')
    .option('env', 'The environment to build', 'prod')

    .setup(function (opts, ctx, next) {
        // Validate environment
        if (opts.env === 'dev') {
            return next(new Error('dev environment can\'t be built'));
        }

        var cwd = process.cwd();

        // Expose the version in the opts
        // Convert from decimal base to base36 to decrease the size of the number
        opts.version = Date.now().toString(36);

        // Set some necessary vars to be used bellow
        opts.targetDir = cwd  + '/web/' + opts.env;
        opts.tempDir = cwd + '/tmp';
        opts.projectDir = cwd;

        ctx.log.writeln('Will build version ' + opts.version.green);

        next();
    })

    .do('rm', {
        description: 'Clean up previous build',
        options: {
            files: ['{{tempDir}}', '{{targetDir}}']
        }
    })
    .do('mkdir', {
        description: 'Create build folder',
        options: {
            dirs: ['{{tempDir}}', '{{targetDir}}']
        }
    })
    .do('cp', {
        description: 'Copy necessary files to temporary folder',
        options: {
            files: {
                '{{projectDir}}/app/**/*': '{{tempDir}}/app/',
                '{{projectDir}}/src/**/*': '{{tempDir}}/src/',
                '{{projectDir}}/bower_components/**/*': '{{tempDir}}/bower_components/',
                '{{projectDir}}/*': '{{tempDir}}/'
            }
        }
    })
    .do(function (opts, ctx, next) {
        var loaderFile = opts.tempDir + '/app/loader.js';

        fs.readFile(loaderFile, function (err, contents) {
            var start,
                end,
                config;

            if (err) {
                return next(err);
            }

            contents = contents.toString();
            start = contents.indexOf('({');
            end = contents.indexOf('});');

            if (start === -1 || end === -1) {
                return next(new Error('Could not locate start/end of loader config'));
            }

            start += 1;
            end += 1;

            try {
                eval('config = ' + contents.slice(start, end));
            } catch (err) {
                return next(err);
            }

            // Pass config bellow
            opts.loader = {
                start: start,
                end: end,
                contents: contents,
                config: config
            };

            next();
        });
    }, {
        description: 'Read loader config'
    })
    .do(function (opts, ctx, next) {
        var loader = opts.loader,
            config = loader.config,
            configStr = loader.contents,
            pkg;

        // Change baseUrl
        config.baseUrl = '/' + opts.env + '/src',

        // Change app-config path to point to the correct environment
        config.map['*']['app-config'] = '../app/config/config_' + opts.env;

        // Replace css package location to use require-css
        // We use curl-css in dev because it works on IE9 but it's not
        // compatible with r.js builder
        pkg = config.packages && mout.array.find(config.packages, function (pkg) {
            return pkg.name === 'css';
        });
        if (pkg) {
            pkg.location = '../bower_components/require-css';
            pkg.main = 'css';
        }

        // Set cache busting
        config.urlArgs = opts.version;

        // Write back config
        configStr = configStr.slice(0, loader.start) + JSON.stringify(config, null, '    ') + configStr.substr(loader.end);
        fs.writeFile(opts.tempDir + '/app/loader.js', configStr, next);
    }, {
        description: 'Transform loader config'
    })
    // TODO: create automaton task for this (requirejs)
    .do(function (opts, ctx, next) {
        var config;

        config = mout.object.deepMixIn(opts.loader.config, {
            baseUrl: opts.tempDir + '/src',                  // Point to the tmp folder
            name: '../bower_components/requirejs/require',   // Include require.js (you can switch to almond if compatible)
            include: ['../app/loader', '../app/bootstrap'],  // Include main files
            out: opts.tempDir + '/app.js',
            has: {
                debug: false
            },
            optimize: 'none',
            separateCSS: true,
            stubModules: ['has', 'text', 'css', 'css/css', 'css/normalize']
        });

        rjs.optimize(config, function (log) {
            ctx.log.info(log);
            next();
        }, function (err) {
            next(err);
        });
    }, {
        description: 'Run r.js optimizer'
    })
    // TODO: create automaton task for this (requirejs)
    .do(function (opts, ctx, next) {
        rjs.optimize({
            optimizeCss: 'standard.keepLines',
            cssIn: opts.tempDir + '/app.css',
            out: opts.tempDir + '/app.css',
            preserveLicenseComments: opts.licenses
        }, function (log) {
            ctx.log.write(log);

            // Replace trailing css from loader defs
            fs.readFile(opts.tempDir + '/app.js', function (err, contents) {
                if (err) {
                    return next(err);
                }

                contents = contents.toString().replace(/css!(.*?)\.css/g, 'css!$1');
                fs.writeFile(opts.tempDir + '/app.js', contents, next);
            });
        }, function (err) {
            next(err);
        });
    }, {
        description: 'Expand css files'
    })
    .do('mv', {
        description: 'Move assets to the build folder',
        options: {
            files: {
                '{{tempDir}}/src/**/assets/!(css|tmpl)/**/*': '{{targetDir}}/src/',
                '{{tempDir}}/app.js': '{{targetDir}}/app.js',
                '{{tempDir}}/app.css': '{{targetDir}}/app.css'
            }
        }
    })
    // TODO. create automaton task for cache busting or use scaffolding-replace with regexp support
    .do(function (opts, ctx, next) {
        var index = opts.projectDir + '/web/index_' + opts.env + '.html',
            css = opts.targetDir + '/app.css';

        // Update index file
        fs.readFile(index, function (err, contents) {
            if (err) {
                return next(err);
            }

            contents = contents
                .toString()
                .replace(/(app(?:\.min)?\.(?:css|js))(?:\?\w+)?/g, function (all, match) {
                    return match + '?' + opts.version;
                });

            fs.writeFile(index, contents, function (err) {
                if (err) {
                    return next(err);
                }

                // Update css file
                fs.readFile(css, function (err, contents) {
                    var dataUriRegExp;

                    if (err) {
                        return next(err);
                    }

                    dataUriRegExp = /^data:/;

                    contents = contents
                        .toString()
                        .replace(/(url\s*\(["']?)(.*?)(["']?\))/ig, function (match, start, url, end) {
                            // Ignore data URIs
                            if (dataUriRegExp.test(url)) {
                                return start + url + end;
                            }

                            url = start + url.split('?', 2)[0] + '?' + opts.version + end;
                            return url;
                        });

                    fs.writeFile(css, contents, next);
                });
            });
        });
    }, {
        description: 'Apply cache busting'
    })
    // TODO: create automaton task for this (minjs)
    .do(function (opts, ctx, next) {
        // TODO: minified also contains a .map with the source mappings
        //       investigate how to integrate it!
        var minified = UglifyJS.minify(opts.targetDir + '/app.js'),
            minifiedSize = String(minified.code.length),
            gzipSize = String(gzip.zip(minified.code, {}).length);

        ctx.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + minifiedSize.green + ' bytes minified).');

        fs.writeFile(opts.targetDir + '/app.min.js', minified.code, next);
    }, {
        description: 'Minify js file'
    })
    // TODO: create automaton task for this (mincss)
    .do(function (opts, ctx, next) {
        fs.readFile(opts.targetDir + '/app.css', function (err, contents) {
            if (err) {
                return next(err);
            }

            var minified = cleanCSS.process(contents.toString(), opts),
                minifiedSize = String(minified.length),
                gzipSize = String(gzip.zip(minified, {}).length);

            ctx.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + minifiedSize.green + ' bytes minified).');

            fs.writeFile(opts.targetDir + '/app.min.css', minified, next);
        });
    }, {
        description: 'Minify css file'
    })
    .do('rm', {
        description: 'Clean up temporary files',
        options: {
            files: '{{tempDir}}'
        }
    });
};
<|endoftext|>


<commit_before>$(document).ready(function() {
     var mapstraction = new mxn.Mapstraction("map_canvas", _provider);

     var minLat = 181.0;
     var maxLat = -181.0;
     var minLon = 181.0;
     var maxLon = -181.0;

     for (var i in _notices)
     {
          var n = _notices[i];

          var lat = n['geo']['coordinates'][0];
          var lon = n['geo']['coordinates'][1];

          if (lat < minLat) {
               minLat = lat;
          }

          if (lat > maxLat) {
               maxLat = lat;
          }

          if (lon < minLon) {
               minLon = lon;
          }

          if (lon > maxLon) {
               maxLon = lon;
          }

          pt = new mxn.LatLonPoint(lat, lon);
          mkr = new mxn.Marker(pt);

          mkr.setIcon(n['user']['profile_image_url']);
          mkr.setInfoBubble(n['html']);

          mapstraction.addMarker(mkr);
     }

     bounds = new mxn.BoundingBox(minLat, minLon, maxLat, maxLon);

     mapstraction.setBounds(bounds);
});
<commit_msg>add username and timestamp to map popup<commit_after>$(document).ready(function() {
     var mapstraction = new mxn.Mapstraction("map_canvas", _provider);

     var minLat = 181.0;
     var maxLat = -181.0;
     var minLon = 181.0;
     var maxLon = -181.0;

     for (var i in _notices)
     {
          var n = _notices[i];

          var lat = n['geo']['coordinates'][0];
          var lon = n['geo']['coordinates'][1];

          if (lat < minLat) {
               minLat = lat;
          }

          if (lat > maxLat) {
               maxLat = lat;
          }

          if (lon < minLon) {
               minLon = lon;
          }

          if (lon > maxLon) {
               maxLon = lon;
          }

          pt = new mxn.LatLonPoint(lat, lon);
          mkr = new mxn.Marker(pt);

          mkr.setLabel();
          mkr.setIcon(n['user']['profile_image_url']);
          mkr.setInfoBubble('' + n['user']['screen_name'] + '' + ' ' + n['html'] +
                            '
'+ n['created_at'] + '');

          mapstraction.addMarker(mkr);
     }

     bounds = new mxn.BoundingBox(minLat, minLon, maxLat, maxLon);

     mapstraction.setBounds(bounds);
});
<|endoftext|>


<commit_before>import debugModule from "debug";
const debug = debugModule("debugger:data:decode");

import {BigNumber} from "bignumber.js";

import * as memory from "./memory";
import * as storage from "./storage";
import * as utils from "./utils";
import { WORD_SIZE } from "./utils";

export function read(pointer, state) {
  if (pointer.stack != undefined && state.stack && pointer.stack < state.stack.length) {
    return state.stack[pointer.stack];
  } else if (pointer.storage != undefined && state.storage) {
    return storage.readRange(state.storage, pointer.storage);
  } else if (pointer.memory != undefined && state.memory) {
    return memory.readBytes(state.memory, pointer.memory.start, pointer.memory.length);
  } else if (pointer.literal) {
    return pointer.literal;
  }
}

export function decodeValue(definition, pointer, state, ...args) {
  let bytes = read(pointer, state);
  if (!bytes) {
    return undefined;
  }

  switch (utils.typeClass(definition)) {
    case "bool":
      return !utils.toBigNumber(bytes).isZero();

    case "uint":
      return utils.toBigNumber(bytes);

    case "int":
      return utils.toSignedBigNumber(bytes);

    case "address":
      return utils.toHexString(bytes, true);

    case "bytes":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      let length = utils.specifiedSize(definition);
      return utils.toHexString(bytes, length);

    case "string":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      return String.fromCharCode.apply(null, bytes);

    default:
      debug("Unknown value type: %s", utils.typeIdentifier(definition));
      return null;
  }
}

export function decodeMemoryReference(definition, pointer, state, ...args) {
  let rawValue = utils.toBigNumber(read(pointer, state)).toNumber();

  var bytes;
  switch (utils.typeClass(definition)) {

    case "bytes":
      bytes = read({
        memory: { start: rawValue, length: WORD_SIZE }
      }, state); // bytes contain length

      return decodeValue(definition, {
        memory: { start: rawValue + WORD_SIZE, length: bytes }
      }, state, ...args);

    case "string":
      bytes = read({
        memory: { start: rawValue, length: WORD_SIZE}
      }, state); // bytes contain length

      return decodeValue(definition, {
        memory: { start: rawValue + WORD_SIZE, length: bytes }
      }, state, ...args);

    case "array":
      bytes = utils.toBigNumber(read({
        memory: { start: rawValue, length: WORD_SIZE },
      }, state)).toNumber();  // bytes contain array length

      bytes = read({ memory: {
        start: rawValue + WORD_SIZE, length: bytes * WORD_SIZE
      }}, state); // now bytes contain items

      return memory.chunk(bytes, WORD_SIZE)
        .map(
          (chunk) => decode(utils.baseDefinition(definition), {
            literal: chunk
          }, state, ...args)
        )

    case "struct":
      let [refs] = args;
      let structDefinition = refs[definition.typeName.referencedDeclaration];
      let structVariables = structDefinition.variables || [];

      return Object.assign(
        {}, ...structVariables
          .map(
            ({name, id}, i) => {
              let memberDefinition = refs[id].definition;
              let memberPointer = {
                memory: { start: rawValue + i * WORD_SIZE, length: WORD_SIZE }
              };
              // let memberPointer = memory.read(state.memory, pointer + i * WORD_SIZE);

              // HACK
              memberDefinition = {
                ...memberDefinition,

                typeDescriptions: {
                  ...memberDefinition.typeDescriptions,

                  typeIdentifier:
                    memberDefinition.typeDescriptions.typeIdentifier
                      .replace(/_storage_/g, "_memory_")
                }
              };

              return {
                [name]: decode(
                  memberDefinition, memberPointer, state, ...args
                )
              };
            }
          )
      );

    default:
      debug("Unknown memory reference type: %s", utils.typeIdentifier(definition));
      return null;

  }

}

export function decodeStorageReference(definition, pointer, state, ...args) {
  var data;
  var bytes;
  var length;
  var slot;

  switch (utils.typeClass(definition)) {
    case "array":
      debug("storage array! %o", pointer);
      data = read(pointer, state);
      if (!data) {
        return null;
      }

      length = utils.toBigNumber(data).toNumber();
      debug("length %o", length);

      let baseSize = utils.storageSize(utils.baseDefinition(definition));

      const offset = (i) => Math.floor(i * baseSize / WORD_SIZE);
      const index = (i) => i * baseSize % WORD_SIZE;

      return [...Array(length).keys()]
        .map( (i) => {
          debug("pointer: %o", pointer);
          let childFrom = pointer.storage.from.offset != undefined ?
            {
              slot: ["0x" + utils.toBigNumber(
                utils.keccak256(...pointer.storage.from.slot)
              ).plus(pointer.storage.from.offset).toString(16)],
              offset: offset(i),
              index: index(i)
            } : {
              slot: [pointer.storage.from.slot],
              offset: offset(i),
              index: index(i)
            };
          debug("childFrom %o: %o", i, childFrom);
          let lookup = read({ storage: { from: childFrom, length: baseSize }}, state);
          debug("done %o", i);
          return childFrom;
        })
        .map( (childFrom) => {
          return decode(utils.baseDefinition(definition), { storage: {
            from: childFrom,
            length: baseSize
          }}, state, ...args);
        });

    case "string":
      data = read(pointer, state);
      if (!data) {
        return null;
      }

      if (data[WORD_SIZE - 1] % 2 == 0) {
        // string lives in word, length is last byte / 2
        length = data[WORD_SIZE - 1] / 2;
        debug("in-word; length %o", length);
        if (length == 0) {
          return "";
        }

        return decodeValue(definition, { storage: {
          from: { slot: pointer.storage.from.slot, index: 0 },
          to: { slot: pointer.storage.from.slot, index: length }
        }}, state, ...args);

      } else {
        length = utils.toBigNumber(data).minus(1).div(2).toNumber();
        debug("new-word, length %o", length);

        return decodeValue(definition, { storage: {
          from: { slot: [pointer.storage.from.slot], index: 0 },
          length
        }}, state, ...args);
      }

    case "struct":
      let [refs] = args;

      return Object.assign(
        {}, ...Object.entries(pointer.storage.children)
          .map( ([id, childPointer]) => ({
            [childPointer.name]: decode(
              refs[id].definition, { storage: childPointer }, state, ...args
            )
          }))
      );

    default:
      debug("Unknown storage reference type: %s", utils.typeIdentifier(definition));
      return undefined;
  }
}

export default function decode(definition, ...args) {
  if (!utils.isReference(definition)) {
    return decodeValue(definition, ...args);
  }

  switch (utils.referenceType(definition)) {
    case "memory":
      return decodeMemoryReference(definition, ...args);
    case "storage":
      return decodeStorageReference(definition, ...args);
    default:
      debug("Unknown reference category: %s", utils.typeIdentifier(definition));
      return undefined;
  }
}

// export default function decode(definition, rawValue, state, refs) {
//   /*
//    * if reference type:
//    *   if memory:
//    *
//    * else if value type:
//    *   decodeValue(definition, valueBytes)
//    */
//   var length;
//   var bytes;

//   debug("definition: %o %o", definition.typeDescriptions, definition.typeName);
//   if (definition.typeName.referencedDeclaration) {
//     debug("referenced %o", refs[definition.typeName.referencedDeclaration]);
//   }

//   let mainType = definition.typeDescriptions.typeIdentifier
//     .match(/(t_[^$_]+)/)[0];

//   switch (mainType) {
//     case "t_string":
//       debug("rawValue: %o", rawValue.toNumber());

//       length = memory.read(state.memory, rawValue);
//       if (length == null) {
//         return null;
//       }
//       debug("length: %o", length);

//       bytes = memory.readBytes(state.memory, rawValue.plus(WORD_SIZE), length);
//       debug("bytes: %o", bytes.length);
//       return String.fromCharCode.apply(null, bytes);

//     default:
//       return rawValue.toNumber();
//   }
// }
<commit_msg>Add support for storage bytes<commit_after>import debugModule from "debug";
const debug = debugModule("debugger:data:decode");

import {BigNumber} from "bignumber.js";

import * as memory from "./memory";
import * as storage from "./storage";
import * as utils from "./utils";
import { WORD_SIZE } from "./utils";

export function read(pointer, state) {
  if (pointer.stack != undefined && state.stack && pointer.stack < state.stack.length) {
    return state.stack[pointer.stack];
  } else if (pointer.storage != undefined && state.storage) {
    return storage.readRange(state.storage, pointer.storage);
  } else if (pointer.memory != undefined && state.memory) {
    return memory.readBytes(state.memory, pointer.memory.start, pointer.memory.length);
  } else if (pointer.literal) {
    return pointer.literal;
  }
}

export function decodeValue(definition, pointer, state, ...args) {
  let bytes = read(pointer, state);
  if (!bytes) {
    return undefined;
  }

  switch (utils.typeClass(definition)) {
    case "bool":
      return !utils.toBigNumber(bytes).isZero();

    case "uint":
      return utils.toBigNumber(bytes);

    case "int":
      return utils.toSignedBigNumber(bytes);

    case "address":
      return utils.toHexString(bytes, true);

    case "bytes":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      let length = utils.specifiedSize(definition);
      return utils.toHexString(bytes, length);

    case "string":
      debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes);
      return String.fromCharCode.apply(null, bytes);

    default:
      debug("Unknown value type: %s", utils.typeIdentifier(definition));
      return null;
  }
}

export function decodeMemoryReference(definition, pointer, state, ...args) {
  let rawValue = utils.toBigNumber(read(pointer, state)).toNumber();

  var bytes;
  switch (utils.typeClass(definition)) {

    case "bytes":
    case "string":
      bytes = read({
        memory: { start: rawValue, length: WORD_SIZE}
      }, state); // bytes contain length

      return decodeValue(definition, {
        memory: { start: rawValue + WORD_SIZE, length: bytes }
      }, state, ...args);

    case "array":
      bytes = utils.toBigNumber(read({
        memory: { start: rawValue, length: WORD_SIZE },
      }, state)).toNumber();  // bytes contain array length

      bytes = read({ memory: {
        start: rawValue + WORD_SIZE, length: bytes * WORD_SIZE
      }}, state); // now bytes contain items

      return memory.chunk(bytes, WORD_SIZE)
        .map(
          (chunk) => decode(utils.baseDefinition(definition), {
            literal: chunk
          }, state, ...args)
        )

    case "struct":
      let [refs] = args;
      let structDefinition = refs[definition.typeName.referencedDeclaration];
      let structVariables = structDefinition.variables || [];

      return Object.assign(
        {}, ...structVariables
          .map(
            ({name, id}, i) => {
              let memberDefinition = refs[id].definition;
              let memberPointer = {
                memory: { start: rawValue + i * WORD_SIZE, length: WORD_SIZE }
              };
              // let memberPointer = memory.read(state.memory, pointer + i * WORD_SIZE);

              // HACK
              memberDefinition = {
                ...memberDefinition,

                typeDescriptions: {
                  ...memberDefinition.typeDescriptions,

                  typeIdentifier:
                    memberDefinition.typeDescriptions.typeIdentifier
                      .replace(/_storage_/g, "_memory_")
                }
              };

              return {
                [name]: decode(
                  memberDefinition, memberPointer, state, ...args
                )
              };
            }
          )
      );

    default:
      debug("Unknown memory reference type: %s", utils.typeIdentifier(definition));
      return null;

  }

}

export function decodeStorageReference(definition, pointer, state, ...args) {
  var data;
  var bytes;
  var length;
  var slot;

  switch (utils.typeClass(definition)) {
    case "array":
      debug("storage array! %o", pointer);
      data = read(pointer, state);
      if (!data) {
        return null;
      }

      length = utils.toBigNumber(data).toNumber();
      debug("length %o", length);

      let baseSize = utils.storageSize(utils.baseDefinition(definition));

      const offset = (i) => Math.floor(i * baseSize / WORD_SIZE);
      const index = (i) => i * baseSize % WORD_SIZE;

      return [...Array(length).keys()]
        .map( (i) => {
          debug("pointer: %o", pointer);
          let childFrom = pointer.storage.from.offset != undefined ?
            {
              slot: ["0x" + utils.toBigNumber(
                utils.keccak256(...pointer.storage.from.slot)
              ).plus(pointer.storage.from.offset).toString(16)],
              offset: offset(i),
              index: index(i)
            } : {
              slot: [pointer.storage.from.slot],
              offset: offset(i),
              index: index(i)
            };
          debug("childFrom %o: %o", i, childFrom);
          let lookup = read({ storage: { from: childFrom, length: baseSize }}, state);
          debug("done %o", i);
          return childFrom;
        })
        .map( (childFrom) => {
          return decode(utils.baseDefinition(definition), { storage: {
            from: childFrom,
            length: baseSize
          }}, state, ...args);
        });

    case "bytes":
    case "string":
      data = read(pointer, state);
      if (!data) {
        return null;
      }

      if (data[WORD_SIZE - 1] % 2 == 0) {
        // string lives in word, length is last byte / 2
        length = data[WORD_SIZE - 1] / 2;
        debug("in-word; length %o", length);
        if (length == 0) {
          return "";
        }

        return decodeValue(definition, { storage: {
          from: { slot: pointer.storage.from.slot, index: 0 },
          to: { slot: pointer.storage.from.slot, index: length }
        }}, state, ...args);

      } else {
        length = utils.toBigNumber(data).minus(1).div(2).toNumber();
        debug("new-word, length %o", length);

        return decodeValue(definition, { storage: {
          from: { slot: [pointer.storage.from.slot], index: 0 },
          length
        }}, state, ...args);
      }

    case "struct":
      let [refs] = args;

      return Object.assign(
        {}, ...Object.entries(pointer.storage.children)
          .map( ([id, childPointer]) => ({
            [childPointer.name]: decode(
              refs[id].definition, { storage: childPointer }, state, ...args
            )
          }))
      );

    default:
      debug("Unknown storage reference type: %s", utils.typeIdentifier(definition));
      return undefined;
  }
}

export default function decode(definition, ...args) {
  if (!utils.isReference(definition)) {
    return decodeValue(definition, ...args);
  }

  switch (utils.referenceType(definition)) {
    case "memory":
      return decodeMemoryReference(definition, ...args);
    case "storage":
      return decodeStorageReference(definition, ...args);
    default:
      debug("Unknown reference category: %s", utils.typeIdentifier(definition));
      return undefined;
  }
}

// export default function decode(definition, rawValue, state, refs) {
//   /*
//    * if reference type:
//    *   if memory:
//    *
//    * else if value type:
//    *   decodeValue(definition, valueBytes)
//    */
//   var length;
//   var bytes;

//   debug("definition: %o %o", definition.typeDescriptions, definition.typeName);
//   if (definition.typeName.referencedDeclaration) {
//     debug("referenced %o", refs[definition.typeName.referencedDeclaration]);
//   }

//   let mainType = definition.typeDescriptions.typeIdentifier
//     .match(/(t_[^$_]+)/)[0];

//   switch (mainType) {
//     case "t_string":
//       debug("rawValue: %o", rawValue.toNumber());

//       length = memory.read(state.memory, rawValue);
//       if (length == null) {
//         return null;
//       }
//       debug("length: %o", length);

//       bytes = memory.readBytes(state.memory, rawValue.plus(WORD_SIZE), length);
//       debug("bytes: %o", bytes.length);
//       return String.fromCharCode.apply(null, bytes);

//     default:
//       return rawValue.toNumber();
//   }
// }
<|endoftext|>


<commit_before>var should = require('should'),
disectModules = require('../lib/disect-modules');

describe('disectModules', function() {
  it('should return an object of module names and versions', function() {
    disectModules('test:3.4.5, foo: 4.5.5 ,bar :1.2.3').should.eql({test:'3.4.5', foo:'4.5.5', bar: '1.2.3'});
  });
  it('should return an object of one module', function() {
    disectModules('test:3.4.5').should.eql({test:'3.4.5'});
  });
  it('should fill out empty version with *', function() {
    disectModules('test').should.eql({test:'*'});
  });
  it('should empty versions can be in the middle', function() {
    disectModules('test:3.4.5, foo ,bar :1.2.3').should.eql({test:'3.4.5', foo:'*', bar: '1.2.3'});
  });
  it('should empty versions with :', function() {
'     disectModules('test:3.4.5, foo: ,bar :1.2.3').should.eql({test:'3.4.5', foo:'*', bar: '1.2.3'});
  });
});

<commit_msg>Fix typo in test<commit_after>var should = require('should'),
disectModules = require('../lib/disect-modules');

describe('disectModules', function() {
  it('should return an object of module names and versions', function() {
    disectModules('test:3.4.5, foo: 4.5.5 ,bar :1.2.3').should.eql({test:'3.4.5', foo:'4.5.5', bar: '1.2.3'});
  });
  it('should return an object of one module', function() {
    disectModules('test:3.4.5').should.eql({test:'3.4.5'});
  });
  it('should fill out empty version with *', function() {
    disectModules('test').should.eql({test:'*'});
  });
  it('should empty versions can be in the middle', function() {
    disectModules('test:3.4.5, foo ,bar :1.2.3').should.eql({test:'3.4.5', foo:'*', bar: '1.2.3'});
  });
  it('should empty versions with :', function() {
    disectModules('test:3.4.5, foo: ,bar :1.2.3').should.eql({test:'3.4.5', foo:'*', bar: '1.2.3'});
  });
});

<|endoftext|>