<commit_before>exports = function ( element, name, startingValue, onTick, onClick, label ) {
    this.name = name;
    this.onTick = onTick ? onTick : function () { return 0; };
    this.onTick.bind( this );
    this.format = function ( value ) {
        if ( value > 1000000000000000 ) {
            return this.format( value / 1000000000000000 ) + "qi";
        }
        if ( value > 1000000000000 ) {
            return this.format( value / 1000000000000 ) + "qa";
        }
        if ( value > 1000000000 ) {
            return this.format( value / 1000000000 ) + "b";
        }
        if ( value > 1000000 ) {
            return this.format( value / 1000000 ) + "m";
        }
        if ( value > 1000 ) {
            return this.format( value / 1000 ) + "k";
        }
        return Math.floor( value );
    };

    this.update = function () {
        var ticked = this.onTick();
        this.label.lastChild.innerHTML = this.format( this.value );
        this.progress.value = ( this.value * 100 ) % 100;
        this.progress.setAttribute( 'title', this.format(ticked*10) + '/s'+"\n"+ticked+"/tick" );
        this.progress.setAttribute( 'class', ticked < 0 ? 'red-bar' : ( ticked === 0 ? 'blue-bar' : 'green-bar' ) );
    };
    this.update.bind( this );
    this.value = startingValue ? startingValue : 0;

    this.baseValue = this.value;
    this.mods = [];
    this.max = 0;
    this.addMod = function ( mod ) {
        this.mods[mod.priority] = this.mods[mod.priority] ? this.mods[mod.priority] : [];
        if ( mod.early ) {
            this.mods[mod.priority].push( mod );
        } else {
            this.mods[mod.priority].unshift( mod );
        }
        this.max = Math.max( this.max, mod.priority );
    }
    this.get = function () {
        var value = this.baseValue;
        for ( var c = this.max; c >= 0; c-- ) {
            if ( this.mods[c] ) {
                for ( var d = 0; d < this.mods[c].length; d++ ) {
                    value = this.mods[c][d].modify( value, this.baseValue );
                }
            }
        }
        return value;
    }

    this.increase = function ( amount ) {
        this.value += !Number.isNaN( amount ) ? amount : 1;
    }
    this.decrease = function ( amount ) {
        if ( amount > this.value ) {
            throw "Not enough " + this.name;
        }
        this.value -= amount;
    }

    this.element = document.createElement('div');
    this.element.setAttribute('class','resource-wrapper');

    if ( onClick ) {
        this.button = document.createElement( 'button' );
        this.button.innerHTML = label ? label : name + "-action";
        this.button.onclick = onClick;
    }  else {
        this.button = document.createElement( 'div' );
    }
    this.button.setAttribute('class','button');
    this.element.appendChild( this.button );

    this.label = document.createElement( 'div' );
    this.label.setAttribute( 'class', 'resource' );
    this.label.appendChild( document.createElement( 'div' ) );
    this.label.lastChild.innerHTML = this.name.charAt(0).toUpperCase()+this.name.substr(1);
    this.label.appendChild( document.createElement( 'div' ) );
    this.label.lastChild.innerHTML = this.format( Math.floor( this.value ) );
    this.element.appendChild(this.label);

    this.progress = document.createElement( 'progress' );
    this.progress.setAttribute( 'value', 0 );
    this.progress.setAttribute( 'max', 100 );
    this.element.appendChild( this.progress );

    element.appendChild( this.element );
    return this;
}
<commit_msg>Update resource.js<commit_after>module.exports = function ( element, name, startingValue, onTick, onClick, label ) {
    this.name = name;
    this.onTick = onTick ? onTick : function () { return 0; };
    this.onTick.bind( this );
    this.format = function ( value ) {
        if ( value > 1000000000000000 ) {
            return this.format( value / 1000000000000000 ) + "qi";
        }
        if ( value > 1000000000000 ) {
            return this.format( value / 1000000000000 ) + "qa";
        }
        if ( value > 1000000000 ) {
            return this.format( value / 1000000000 ) + "b";
        }
        if ( value > 1000000 ) {
            return this.format( value / 1000000 ) + "m";
        }
        if ( value > 1000 ) {
            return this.format( value / 1000 ) + "k";
        }
        return Math.floor( value );
    };

    this.update = function () {
        var ticked = this.onTick();
        this.label.lastChild.innerHTML = this.format( this.value );
        this.progress.value = ( this.value * 100 ) % 100;
        this.progress.setAttribute( 'title', this.format(ticked*10) + '/s'+"\n"+ticked+"/tick" );
        this.progress.setAttribute( 'class', ticked < 0 ? 'red-bar' : ( ticked === 0 ? 'blue-bar' : 'green-bar' ) );
    };
    this.update.bind( this );
    this.value = startingValue ? startingValue : 0;

    this.baseValue = this.value;
    this.mods = [];
    this.max = 0;
    this.addMod = function ( mod ) {
        this.mods[mod.priority] = this.mods[mod.priority] ? this.mods[mod.priority] : [];
        if ( mod.early ) {
            this.mods[mod.priority].push( mod );
        } else {
            this.mods[mod.priority].unshift( mod );
        }
        this.max = Math.max( this.max, mod.priority );
    }
    this.get = function () {
        var value = this.baseValue;
        for ( var c = this.max; c >= 0; c-- ) {
            if ( this.mods[c] ) {
                for ( var d = 0; d < this.mods[c].length; d++ ) {
                    value = this.mods[c][d].modify( value, this.baseValue );
                }
            }
        }
        return value;
    }

    this.increase = function ( amount ) {
        this.value += !Number.isNaN( amount ) ? amount : 1;
    }
    this.decrease = function ( amount ) {
        if ( amount > this.value ) {
            throw "Not enough " + this.name;
        }
        this.value -= amount;
    }

    this.element = document.createElement('div');
    this.element.setAttribute('class','resource-wrapper');

    if ( onClick ) {
        this.button = document.createElement( 'button' );
        this.button.innerHTML = label ? label : name + "-action";
        this.button.onclick = onClick;
    }  else {
        this.button = document.createElement( 'div' );
    }
    this.button.setAttribute('class','button');
    this.element.appendChild( this.button );

    this.label = document.createElement( 'div' );
    this.label.setAttribute( 'class', 'resource' );
    this.label.appendChild( document.createElement( 'div' ) );
    this.label.lastChild.innerHTML = this.name.charAt(0).toUpperCase()+this.name.substr(1);
    this.label.appendChild( document.createElement( 'div' ) );
    this.label.lastChild.innerHTML = this.format( Math.floor( this.value ) );
    this.element.appendChild(this.label);

    this.progress = document.createElement( 'progress' );
    this.progress.setAttribute( 'value', 0 );
    this.progress.setAttribute( 'max', 100 );
    this.element.appendChild( this.progress );

    element.appendChild( this.element );
    return this;
}
<|endoftext|>


<commit_before>var spelling = function(dbot) {
    var dbot = dbot;
    var last = {};

    return {
        'listener': function(data, params) {
            var q = data.message.valMatch(/^\*([\d\w\s]*)/, 2);
            if(q) {
                var correction = q[1];
                var candidates = last[data.channel][data.user].split(' ');
                var winner = false;
                var winnerDistance = 99999999; //urgh fix later

                for(var i=0;i<candidates.length;i++) {
                    var distance = String.prototype.distance(correction, candidates[i]);
                    if(distance < winnerDistance) {
                        winner = candidates[i];
                        winnerDistance = distance;
                    }
                }

                console.log(winner + ' ' + winnerDistance);

                if(winnerDistance < 3) {
                    var fix = data.message.replace(winner, correction);
                    dbot.say(data.channel, data.user + ':' + fix);
                }
            } else {
                 if(last.hasOwnProperty(data.channel)) {
                   last[data.channel][data.user] = data.message;
                } else {
                    last[data.channel] = { };
                    last[data.channel][data.user] = data.message;
                }
            }
        },

        'on': 'PRIVMSG'
    }
}

exports.fetch = function(dbot) {
    return spelling(dbot);
};
<commit_msg>var not int jesus christ java<commit_after>var spelling = function(dbot) {
    var dbot = dbot;
    var last = {};

    return {
        'listener': function(data, params) {
            var q = data.message.valMatch(/^\*([\d\w\s]*)/, 2);
            if(q) {
                var correction = q[1];
                var candidates = last[data.channel][data.user].split(' ');
                var winner = false;
                var winnerDistance = 99999999; //urgh fix later

                for(var i=0;i<candidates.length;i++) {
                    var distance = String.prototype.distance(correction, candidates[i]);
                    if(distance < winnerDistance) {
                        winner = candidates[i];
                        winnerDistance = distance;
                    }
                }

                console.log(winner + ' ' + winnerDistance);

                if(winnerDistance < 3) {
                    var fix = last[data.channel][data.user].replace(winner, correction);
                    dbot.say(data.channel, data.user + ':' + fix);
                }
            } else {
                 if(last.hasOwnProperty(data.channel)) {
                   last[data.channel][data.user] = data.message;
                } else {
                    last[data.channel] = { };
                    last[data.channel][data.user] = data.message;
                }
            }
        },

        'on': 'PRIVMSG'
    }
}

exports.fetch = function(dbot) {
    return spelling(dbot);
};
<|endoftext|>


<commit_before>import _clone from 'lodash-es/clone';
import _extend from 'lodash-es/extend';
import _some from 'lodash-es/some';

import { dispatch as d3_dispatch } from 'd3-dispatch';

import {
    event as d3_event,
    select as d3_select
} from 'd3-selection';

import { t } from '../util/locale';
import { textDirection } from '../util/locale';
import { svgIcon } from '../svg';
import { uiFieldHelp } from './field_help';
import { uiFields } from './fields';
import { uiTagReference } from './tag_reference';
import { utilRebind } from '../util';

export function uiField(context, presetField, entity, options) {
    options = _extend({
        show: true,
        wrap: true,
        remove: true,
        revert: true,
        info: true
    }, options);

    var dispatch = d3_dispatch('change');
    var field = _clone(presetField);
    var _show = options.show;
    var _state = '';
    var _tags = {};

    field.keys = field.keys || [field.key];

    // only create the fields that are actually being shown
    if (_show && !field.impl) {
        createField();
    }

    // field implementation
    function createField() {
        field.impl = uiFields[field.type](field, context)
            .on('change', function(t, onInput) {
                dispatch.call('change', field, t, onInput);
            });

        // if this field cares about the entity, pass it along
        if (entity && field.impl.entity) {
            field.entityID = entity.id;
            field.impl.entity(entity);
        }
    }

    function isModified() {
        if (!entity) return false;
        var original = context.graph().base().entities[entity.id];
        return _some(field.keys, function(key) {
            return original ? _tags[key] !== original.tags[key] : _tags[key];
        });
    }

    function isPresent() {
        return _some(field.keys, function(key) {
            return _tags[key];
        });
    }

    function revert(d) {
        d3_event.stopPropagation();
        d3_event.preventDefault();
        if (!entity) return false;

        var original = context.graph().base().entities[entity.id];
        var t = {};
        d.keys.forEach(function(key) {
            t[key] = original ? original.tags[key] : undefined;
        });

        dispatch.call('change', d, t);
    }

    function remove(d) {
        d3_event.stopPropagation();
        d3_event.preventDefault();

        var t = {};
        d.keys.forEach(function(key) {
            t[key] = undefined;
        });

        dispatch.call('change', d, t);
    }

    field.render = function(selection) {
        var container = selection.selectAll('.form-field')
            .data([field]);

        // Enter
        var enter = container.enter()
            .append('div')
            .attr('class', function(d) { return 'form-field form-field-' + d.safeid; })
            .classed('nowrap', !options.wrap);

        if (options.wrap) {
            var label = enter
                .append('label')
                .attr('class', 'form-field-label')
                .attr('for', function(d) { return 'preset-input-' + d.safeid; });

            label
                .append('span')
                .attr('class', 'label-text')
                .text(function(d) { return d.label(); });

            if (options.remove) {
                label
                    .append('button')
                    .attr('class', 'remove-icon')
                    .attr('title', t('icons.remove'))
                    .attr('tabindex', -1)
                    .call(svgIcon('#iD-operation-delete'));
            }

            if (options.revert) {
                label
                    .append('button')
                    .attr('class', 'modified-icon')
                    .attr('title', t('icons.undo'))
                    .attr('tabindex', -1)
                    .call(svgIcon((textDirection === 'rtl') ? '#iD-icon-redo' : '#iD-icon-undo'));
            }
        }

        // Update
        container = container
            .merge(enter);

        container.select('.form-field-label > .remove-icon')  // propagate bound data
            .on('click', remove);

        container.select('.form-field-label > .modified-icon')  // propagate bound data
            .on('click', revert);

        container
            .classed('modified', isModified())
            .classed('present', isPresent())
            .each(function(d) {
                var reference, help;

                // instantiate field help
                if (options.wrap && field.type === 'restrictions') {
                    help = uiFieldHelp(context, 'restrictions');
                }

                // instantiate tag reference
                if (options.wrap && options.info) {
                    var referenceKey = d.key;
                    if (d.type === 'multiCombo') {   // lookup key without the trailing ':'
                        referenceKey = referenceKey.replace(/:$/, '');
                    }

                    reference = uiTagReference(d.reference || { key: referenceKey }, context);
                    if (_state === 'hover') {
                        reference.showing(false);
                    }
                }

                d3_select(this)
                    .call(d.impl);

                // add field help components
                if (help) {
                    d3_select(this)
                        .call(help.body)
                        .select('.form-field-label')
                        .call(help.button);
                }

                // add tag reference components
                if (reference) {
                    d3_select(this)
                        .call(reference.body)
                        .select('.form-field-label')
                        .call(reference.button);
                }

                d.impl.tags(_tags);
            });
    };

    field.state = function(val) {
        if (!arguments.length) return _state;
        _state = val;
        return field;
    };

    field.tags = function(val) {
        if (!arguments.length) return _tags;
        _tags = val;
        return field;
    };

    field.show = function() {
        _show = true;
        if (!field.impl) {
            createField();
        }
        if (field.default && field.key && _tags[field.key] !== field.default) {
            var t = {};
            t[field.key] = field.default;
            dispatch.call('change', this, t);
        }
    };

    field.isShown = function() {
        return _show || _some(field.keys, function(key) { return !!_tags[key]; });
    };

    field.focus = function() {
        field.impl.focus();
    };

    return utilRebind(field, dispatch, 'on');
}
<commit_msg>Don't try to render a field that's not yet shown<commit_after>import _clone from 'lodash-es/clone';
import _extend from 'lodash-es/extend';
import _some from 'lodash-es/some';

import { dispatch as d3_dispatch } from 'd3-dispatch';

import {
    event as d3_event,
    select as d3_select
} from 'd3-selection';

import { t } from '../util/locale';
import { textDirection } from '../util/locale';
import { svgIcon } from '../svg';
import { uiFieldHelp } from './field_help';
import { uiFields } from './fields';
import { uiTagReference } from './tag_reference';
import { utilRebind } from '../util';

export function uiField(context, presetField, entity, options) {
    options = _extend({
        show: true,
        wrap: true,
        remove: true,
        revert: true,
        info: true
    }, options);

    var dispatch = d3_dispatch('change');
    var field = _clone(presetField);
    var _show = options.show;
    var _state = '';
    var _tags = {};

    field.keys = field.keys || [field.key];

    // only create the fields that are actually being shown
    if (_show && !field.impl) {
        createField();
    }

    // field implementation
    function createField() {
        field.impl = uiFields[field.type](field, context)
            .on('change', function(t, onInput) {
                dispatch.call('change', field, t, onInput);
            });

        // if this field cares about the entity, pass it along
        if (entity && field.impl.entity) {
            field.entityID = entity.id;
            field.impl.entity(entity);
        }
    }

    function isModified() {
        if (!entity) return false;
        var original = context.graph().base().entities[entity.id];
        return _some(field.keys, function(key) {
            return original ? _tags[key] !== original.tags[key] : _tags[key];
        });
    }

    function isPresent() {
        return _some(field.keys, function(key) {
            return _tags[key];
        });
    }

    function revert(d) {
        d3_event.stopPropagation();
        d3_event.preventDefault();
        if (!entity) return false;

        var original = context.graph().base().entities[entity.id];
        var t = {};
        d.keys.forEach(function(key) {
            t[key] = original ? original.tags[key] : undefined;
        });

        dispatch.call('change', d, t);
    }

    function remove(d) {
        d3_event.stopPropagation();
        d3_event.preventDefault();

        var t = {};
        d.keys.forEach(function(key) {
            t[key] = undefined;
        });

        dispatch.call('change', d, t);
    }

    field.render = function(selection) {
        var container = selection.selectAll('.form-field')
            .data([field]);

        // Enter
        var enter = container.enter()
            .append('div')
            .attr('class', function(d) { return 'form-field form-field-' + d.safeid; })
            .classed('nowrap', !options.wrap);

        if (options.wrap) {
            var label = enter
                .append('label')
                .attr('class', 'form-field-label')
                .attr('for', function(d) { return 'preset-input-' + d.safeid; });

            label
                .append('span')
                .attr('class', 'label-text')
                .text(function(d) { return d.label(); });

            if (options.remove) {
                label
                    .append('button')
                    .attr('class', 'remove-icon')
                    .attr('title', t('icons.remove'))
                    .attr('tabindex', -1)
                    .call(svgIcon('#iD-operation-delete'));
            }

            if (options.revert) {
                label
                    .append('button')
                    .attr('class', 'modified-icon')
                    .attr('title', t('icons.undo'))
                    .attr('tabindex', -1)
                    .call(svgIcon((textDirection === 'rtl') ? '#iD-icon-redo' : '#iD-icon-undo'));
            }
        }

        // Update
        container = container
            .merge(enter);

        container.select('.form-field-label > .remove-icon')  // propagate bound data
            .on('click', remove);

        container.select('.form-field-label > .modified-icon')  // propagate bound data
            .on('click', revert);

        container
            .classed('modified', isModified())
            .classed('present', isPresent())
            .each(function(d) {
                if (!d.impl) return;  // field is not yet shown

                var reference, help;

                // instantiate field help
                if (options.wrap && field.type === 'restrictions') {
                    help = uiFieldHelp(context, 'restrictions');
                }

                // instantiate tag reference
                if (options.wrap && options.info) {
                    var referenceKey = d.key;
                    if (d.type === 'multiCombo') {   // lookup key without the trailing ':'
                        referenceKey = referenceKey.replace(/:$/, '');
                    }

                    reference = uiTagReference(d.reference || { key: referenceKey }, context);
                    if (_state === 'hover') {
                        reference.showing(false);
                    }
                }

                d3_select(this)
                    .call(d.impl);

                // add field help components
                if (help) {
                    d3_select(this)
                        .call(help.body)
                        .select('.form-field-label')
                        .call(help.button);
                }

                // add tag reference components
                if (reference) {
                    d3_select(this)
                        .call(reference.body)
                        .select('.form-field-label')
                        .call(reference.button);
                }

                d.impl.tags(_tags);
            });
    };

    field.state = function(val) {
        if (!arguments.length) return _state;
        _state = val;
        return field;
    };

    field.tags = function(val) {
        if (!arguments.length) return _tags;
        _tags = val;
        return field;
    };

    field.show = function() {
        _show = true;
        if (!field.impl) {
            createField();
        }
        if (field.default && field.key && _tags[field.key] !== field.default) {
            var t = {};
            t[field.key] = field.default;
            dispatch.call('change', this, t);
        }
    };

    field.isShown = function() {
        return _show || _some(field.keys, function(key) { return !!_tags[key]; });
    };

    field.focus = function() {
        field.impl.focus();
    };

    return utilRebind(field, dispatch, 'on');
}
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
// Creator:   Dominik
// Date:      16.02.2011
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

/**
 * @class
 *
 * This defines the prototype for any button view. A button is a view element that is
 * typically.........
 *
 * @extends M.View
 */
M.SplitView = M.View.extend(
/** @scope M.SplitView.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.SplitView',

    menu: null,

    content: null,

    isInitialized: NO,

    selectedItem: null,

    orientation: null,

    headerheight: null,

    footerheight: null,

    itemheight: null,

    contentLoaded: NO,

    scrollviewsInitialized: NO,

    hasMenuScrollview: NO,

    shouldHaveScrollview: YES,

    /**
     * Renders a split view.
     *
     * @private
     * @returns {String} The split view's html representation.
     */
    render: function() {
        this.html += '
';

        this.renderChildViews();

        this.html += '
';

        return this.html;
    },

    /**
     * Render child views.
     *
     * @private
     */
    renderChildViews: function() {
        if (this.childViews || this.contentBinding) {
            var childViews = this.getChildViewsAsArray();
            if (childViews.length > 0 || this.contentBinding) {
                this.menu = M.ScrollView.design({
                    childViews: 'menu',
                    menu: M.ListView.design({})
                });
                this.menu.parentView = this;
                this.menu.menu.parentView = this.menu;
                this.menu.cssClass = this.menu.cssClass ? this.menu.cssClass + ' tmp-splitview-menu' : 'tmp-splitview-menu';
                this.html += this.menu.render();

                this.content = M.ScrollView.design({});
                this.content.parentView = this;
                this.content.cssClass = this.content.cssClass ? this.content.cssClass + ' tmp-splitview-content' : 'tmp-splitview-content';
                this.html += this.content.render();

                return this.html;
            } else {
                M.Logger.log('You need to provide at least one child view for M.SplitView of the type M.SplitItemView.', M.ERROR);
            }
        }
    },

    /**
     * Render update.
     *
     * @private
     */
    renderUpdate: function() {
        var content = null;

        if (this.contentBinding) {
            content = this.value;
        } else if (this.childViews) {
            var childViews = this.getChildViewsAsArray();
            content = [];
            for (var i = 0; i < childViews.length; i++) {
                content.push(this[childViews[i]]);
            }
        }

        if (content) {
            if (content.length > 0) {

                /* reset menu list before filling it up again */
                this.menu.menu.removeAllItems();

                var entryItem = null;
                var currentItem = 0;
                for (var i in content) {
                    if (content[i] && content[i].type === 'M.SplitItemView') {
                        /* add item to list */
                        var item = M.ListItemView.design({
                            childViews: 'label',
                            parentView: this.menu.menu,
                            splitViewItem: content[i],
                            label: M.LabelView.design({
                                value: content[i].value
                            }),
                            events: {
                                tap: {
                                    target: this,
                                    action: 'listItemSelected'
                                }
                            }
                        });
                        this.menu.menu.addItem(item.render());

                        /* register events for item */
                        item.registerEvents();

                        /* save id of the current item if it is either the first item or isActive is set */
                        if (currentItem === 0 || content[i].isActive) {
                            entryItem = item.id;
                        }

                        /* increase item counter */
                        currentItem++;
                    } else {
                        M.Logger.log('Invalid child view passed! The child views of M.SplitView need to be of type M.ListView.', M.ERROR);
                    }
                }

                /* theme the list */
                this.menu.menu.themeUpdate();

                /* now set the active list item */
                this.menu.menu.setActiveListItem(entryItem);

                /* finally show the active list item's content */
                this.listItemSelected(entryItem);
            } else {
                M.Logger.log('You need to provide at least one child view for M.SplitView of the type M.SplitItemView.', M.ERROR);
            }
        }
    },

    /**
     * Theme.
     *
     * @private
     */
    theme: function() {
        this.renderUpdate();
        this.themeUpdate();
    },

    themeUpdate: function() {
        var size = M.Environment.getSize();
        var width = size[0];
        var height = size[1];

        /* landscape mode */
        if (M.Environment.getWidth() > M.Environment.getHeight()) {
            $('#' + this.menu.id).css('width', Math.ceil(width * 0.3) - 2 * (parseInt($('#' + this.menu.id).css('border-right-width'))) + 'px');
            $('#' + this.content.id).css('width', Math.floor(width * 0.7) - 2 * (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) + 'px');
            $('#' + this.content.id).css('left', Math.ceil(width * 0.3) + (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) - parseInt($('#' + this.menu.id).css('border-right-width')) + 'px');

            $('.tmp-splitview-menu-toolbar').css('width', Math.ceil(width * 0.3) + (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) - parseInt($('.tmp-splitview-menu-toolbar').css('border-right-width')) + 'px');
            $('.tmp-splitview-content-toolbar').css('width', Math.floor(width * 0.7) - (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) + 'px');

            this.orientation = 'landscape';
            /* portrait mode */
        } else {
            $('#' + this.content.id).css('width', width - (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) + 'px');
            $('#' + this.content.id).css('left', '0px');

            $('.tmp-splitview-content-toolbar').css('width', width + 'px');

            this.orientation = 'portait';
        }

        /* register for DOMContentLoaded event to initialize the split view once its in DOM */
        if (!this.contentLoaded) {
            var that = this;
            $(document).bind('DOMContentLoaded', function() {
                that.initializeVar();
            });
            /* if DOMContent is loaded, apply some heights/widths */
        } else {
            var page = M.ViewManager.getCurrentPage() || M.ViewManager.getPage(M.Application.entryPage);

            /* set the min height of the page based on if there's a footer or not */
            if ($('#' + page.id).hasClass('tmp-splitview-no-footer')) {
                $('#' + page.id).css('min-height', height + 'px');
            } else {
                $('#' + page.id).css('min-height', height - this.footerheight + 'px !important');
            }

            /* set the height of the menu based on header/footer */
            if ($('#' + page.id + ' .ui-footer').length === 0) {
                $('#' + this.menu.menu.id).css('height', M.Environment.getHeight() - this.headerheight);
            } else {
                $('#' + this.menu.menu.id).css('height', M.Environment.getHeight() - this.headerheight - this.footerheight);
            }

            /* initialize the scrolling stuff (if not done yet) */
            if (!this.scrollviewsInitialized) {
                $('#' + this.content.id).scrollview({
                    direction: 'y'
                });

                /* check whether scrolling is required or not for the menu */
                if (this.orientation === 'landscape') {
                    this.itemheight = $('#' + this.menu.menu.id).find('li:first').outerHeight();
                    var itemCount = $('#' + this.menu.menu.id).find('li').length;

                    if (this.itemheight !== 0) {
                        var menuHeight = M.Environment.getHeight();
                        var itemListHeight = itemCount * this.itemheight;
                        if (menuHeight < itemListHeight) {
                            $('#' + this.menu.menu.id).scrollview({
                                direction: 'y'
                            });
                            this.hasMenuScrollview = YES;
                        } else {
                            this.shouldHaveScrollview = NO;
                        }
                    }
                    this.scrollviewsInitialized = YES;
                }

            }
        }
    },

    /**
     * Called when Dom Content Loaded event arrived, to calculate height of header and footer
     * and set the contentLoaded, call theme update, in order to check out if a scrollview for menu is needed
     */
    initializeVar: function() {
        this.headerheight = $('#' + M.ViewManager.getCurrentPage().id + ' .ui-header').height();
        this.footerheight = $('#' + M.ViewManager.getCurrentPage().id + ' .ui-footer').height();
        this.contentLoaded = YES;
        this.themeUpdate();
    },

    registerEvents: function() {
        /* register for orientation change events of the current page */
        var page = M.ViewManager.getCurrentPage() || M.ViewManager.getPage(M.Application.entryPage);
        M.EventDispatcher.registerEvent(
            'orientationdidchange',
            page.id,
            {
                target: this,
                action:  function() {
                    /* trigger re-theming with a little delay to make sure, the orientation change did finish */
                    var that = this;
                    window.setTimeout(function() {
                        that.orientationDidChange();
                    }, 100);
                }
            },
            ['orientationdidchange'],
            null,
            NO,
            YES
        );
    },

    listItemSelected: function(id) {
        var contentView = M.ViewManager.getViewById(id) && M.ViewManager.getViewById(id).splitViewItem ? M.ViewManager.getViewById(id).splitViewItem.view : null;

        if (!contentView) {
            return;
        }

        this.selectedItem = M.ViewManager.getViewById(id).splitViewItem;

        if (!this.isInitialized) {
            if (contentView.html) {
                $('#' + this.content.id).html(contentView.html);
            } else {
                $('#' + this.content.id).html(contentView.render());
                contentView.theme();
                contentView.registerEvents();
            }
            this.isInitialized = YES;
        } else {
            if (contentView.html) {
                $('#' + this.content.id + ' div:first').html(contentView.html);
            } else {
                $('#' + this.content.id + ' div:first').html(contentView.render());
                contentView.theme();
                contentView.registerEvents();
            }
            $('#' + this.content.id).scrollview('scrollTo', 0, 0);
        }

        /* check if there is a split toolbar view on the page and update its label to show the value of the selected item */
        var page = M.ViewManager.getCurrentPage() || M.ViewManager.getPage(M.Application.entryPage);
        var that = this;
        if (page) {
            $('#' + page.id + ' .tmp-splitview-content-toolbar').each(function() {
                var toolbar = M.ViewManager.getViewById($(this).attr('id'));
                if (toolbar.parentView && toolbar.parentView.showSelectedItemInMainHeader) {
                    toolbar.value = M.ViewManager.getViewById(id).splitViewItem.value;
                    $('#' + toolbar.id + ' h1').html(toolbar.value);

                    /* now link the menu with the toolbar if not yet done */
                    if (!toolbar.parentView.splitview) {
                        toolbar.parentView.splitview = that;
                    }
                }
            });

            /* add special css class if there is no footer */
            if ($('#' + page.id + ' .ui-footer').length === 0) {
                page.addCssClass('tmp-splitview-no-footer');
            }

            /* add special css class if there is no header */
            if ($('#' + page.id + ' .tmp-splitview-content-toolbar').length === 0) {
                page.addCssClass('tmp-splitview-no-header');
            }
        }
    },

    orientationDidChange: function() {
        var orientation = M.Environment.getOrientation();
        var that = this;
        var page = M.ViewManager.getCurrentPage() || M.ViewManager.getPage(M.Application.entryPage);

        /* portrait */
        if (M.Environment.getHeight() > M.Environment.getWidth()) {
            $('html').removeClass('landscape');
            $('html').addClass('portrait');
        /* landscape */
        } else {
            $('html').removeClass('portrait');
            $('html').addClass('landscape');

            /* hide the popover */
            var toolbar;
            if (page) {
                $('#' + page.id + ' .tmp-splitview-menu-toolbar').each(function() {
                    toolbar = M.ViewManager.getViewById($(this).attr('id'));
                    if (toolbar && toolbar.parentView && toolbar.parentView.popover) {
                        toolbar.parentView.popover.hide();
                    }
                });
            }

            /* update the menu */
            var id;
            $('#' + this.menu.id).find('li').each(function() {
                if (M.ViewManager.getViewById($(this).attr('id')).splitViewItem.id === that.selectedItem.id) {
                    id = $(this).attr('id');
                }
            });

            /* activate the current item */
            if (id) {
                this.menu.menu.setActiveListItem(id);
            }

            /* set the selected item */
            this.selectedItem = M.ViewManager.getViewById(id).splitViewItem;

            /* scroll the menu so we def. see the selected item */
            this.scrollListToRightPosition(id);
        }

        /* scroll content to top */
        $('#' + this.content.id).scrollview('scrollTo', 0, 0);

        /* call theme update */
        this.themeUpdate();

        /* fix the toolbars */
        $.mobile.fixedToolbars.show();
    },

    scrollListToRightPosition: function(id) {
        var itemHeight = $('#' + this.menu.menu.id + ' li:first-child').outerHeight();
        var y = ($('#' + id).index() + 1) * itemHeight;
        var menuHeight = M.Environment.getHeight() - this.headerheight - this.footerheight;
        var middle = menuHeight / 2;
        var distanceToListEnd = $('#' + this.menu.menu.id).find('li').length * itemHeight - y;
        var yScroll = 0;

        /* if y coordinate of item is greater than menu height, we need to scroll down */
        if (y > menuHeight) {
            if (distanceToListEnd < middle) {
                yScroll = -(y - menuHeight + distanceToListEnd);
            } else {
                yScroll = -(y - middle);
            }
            /* if y coordinate of item is less than menu height, we need to scroll up */
        } else if (y < menuHeight) {
            if (y < middle) {
                yScroll = 0;
            } else {
                yScroll = -(y - middle);
            }
        }

        /* if there already is a scroll view, just scroll */
        if (!this.hasMenuScrollview && this.shouldHaveScrollview) {
            $('#' + this.menu.menu.id).scrollview({
                direction: 'y'
            });
        }
        $('#' + this.menu.menu.id).scrollview('scrollTo', 0, yScroll);
    }

});
<commit_msg>fixed some type and removing of orientation class<commit_after>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
// Creator:   Dominik
// Date:      16.02.2011
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

/**
 * @class
 *
 * This defines the prototype for any button view. A button is a view element that is
 * typically.........
 *
 * @extends M.View
 */
M.SplitView = M.View.extend(
/** @scope M.SplitView.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.SplitView',

    menu: null,

    content: null,

    isInitialized: NO,

    selectedItem: null,

    orientation: null,

    headerheight: null,

    footerheight: null,

    itemheight: null,

    contentLoaded: NO,

    scrollviewsInitialized: NO,

    hasMenuScrollview: NO,

    shouldHaveScrollview: YES,

    /**
     * Renders a split view.
     *
     * @private
     * @returns {String} The split view's html representation.
     */
    render: function() {
        this.html += '
';

        this.renderChildViews();

        this.html += '
';

        return this.html;
    },

    /**
     * Render child views.
     *
     * @private
     */
    renderChildViews: function() {
        if (this.childViews || this.contentBinding) {
            var childViews = this.getChildViewsAsArray();
            if (childViews.length > 0 || this.contentBinding) {
                this.menu = M.ScrollView.design({
                    childViews: 'menu',
                    menu: M.ListView.design({})
                });
                this.menu.parentView = this;
                this.menu.menu.parentView = this.menu;
                this.menu.cssClass = this.menu.cssClass ? this.menu.cssClass + ' tmp-splitview-menu' : 'tmp-splitview-menu';
                this.html += this.menu.render();

                this.content = M.ScrollView.design({});
                this.content.parentView = this;
                this.content.cssClass = this.content.cssClass ? this.content.cssClass + ' tmp-splitview-content' : 'tmp-splitview-content';
                this.html += this.content.render();

                return this.html;
            } else {
                M.Logger.log('You need to provide at least one child view for M.SplitView of the type M.SplitItemView.', M.ERROR);
            }
        }
    },

    /**
     * Render update.
     *
     * @private
     */
    renderUpdate: function() {
        var content = null;

        if (this.contentBinding) {
            content = this.value;
        } else if (this.childViews) {
            var childViews = this.getChildViewsAsArray();
            content = [];
            for (var i = 0; i < childViews.length; i++) {
                content.push(this[childViews[i]]);
            }
        }

        if (content) {
            if (content.length > 0) {

                /* reset menu list before filling it up again */
                this.menu.menu.removeAllItems();

                var entryItem = null;
                var currentItem = 0;
                for (var i in content) {
                    if (content[i] && content[i].type === 'M.SplitItemView') {
                        /* add item to list */
                        var item = M.ListItemView.design({
                            childViews: 'label',
                            parentView: this.menu.menu,
                            splitViewItem: content[i],
                            label: M.LabelView.design({
                                value: content[i].value
                            }),
                            events: {
                                tap: {
                                    target: this,
                                    action: 'listItemSelected'
                                }
                            }
                        });
                        this.menu.menu.addItem(item.render());

                        /* register events for item */
                        item.registerEvents();

                        /* save id of the current item if it is either the first item or isActive is set */
                        if (currentItem === 0 || content[i].isActive) {
                            entryItem = item.id;
                        }

                        /* increase item counter */
                        currentItem++;
                    } else {
                        M.Logger.log('Invalid child view passed! The child views of M.SplitView need to be of type M.ListView.', M.ERROR);
                    }
                }

                /* theme the list */
                this.menu.menu.themeUpdate();

                /* now set the active list item */
                this.menu.menu.setActiveListItem(entryItem);

                /* finally show the active list item's content */
                this.listItemSelected(entryItem);
            } else {
                M.Logger.log('You need to provide at least one child view for M.SplitView of the type M.SplitItemView.', M.ERROR);
            }
        }
    },

    /**
     * Theme.
     *
     * @private
     */
    theme: function() {
        this.renderUpdate();

        /* register for DOMContentLoaded event to initialize the split view once its in DOM */
        if (!this.contentLoaded) {
            var that = this;
            $(document).bind('DOMContentLoaded', function() {
                that.initializeVar();
            });
        }
    },

    themeUpdate: function() {
        var size = M.Environment.getSize();
        var width = size[0];
        var height = size[1];

        /* landscape mode */
        if (M.Environment.getWidth() > M.Environment.getHeight()) {
            this.orientation = 'landscape';
            $('html').addClass(this.orientation);

            $('#' + this.menu.id).css('width', Math.ceil(width * 0.3) - 2 * (parseInt($('#' + this.menu.id).css('border-right-width'))) + 'px');
            $('#' + this.content.id).css('width', Math.floor(width * 0.7) - 2 * (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) + 'px');
            $('#' + this.content.id).css('left', Math.ceil(width * 0.3) + (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) - parseInt($('#' + this.menu.id).css('border-right-width')) + 'px');

            $('.tmp-splitview-menu-toolbar').css('width', Math.ceil(width * 0.3) + (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) - parseInt($('.tmp-splitview-menu-toolbar').css('border-right-width')) + 'px');
            $('.tmp-splitview-content-toolbar').css('width', Math.floor(width * 0.7) - (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) + 'px');
        /* portrait mode */
        } else {
            this.orientation = 'portrait';
            $('html').addClass(this.orientation);

            $('#' + this.content.id).css('width', width - (parseInt($('#' + this.content.id).css('padding-right')) + parseInt($('#' + this.content.id).css('padding-left'))) + 'px');
            $('#' + this.content.id).css('left', '0px');

            $('.tmp-splitview-content-toolbar').css('width', width + 'px');
        }

        var page = M.ViewManager.getCurrentPage() || M.ViewManager.getPage(M.Application.entryPage);

        /* set the min height of the page based on if there's a footer or not */
        if ($('#' + page.id).hasClass('tmp-splitview-no-footer')) {
            $('#' + page.id).css('min-height', height + 'px');
        } else {
            $('#' + page.id).css('min-height', height - this.footerheight + 'px !important');
        }

        /* set the height of the menu based on header/footer */
        if ($('#' + page.id + ' .ui-footer').length === 0) {
            $('#' + this.menu.menu.id).css('height', M.Environment.getHeight() - this.headerheight);
        } else {
            $('#' + this.menu.menu.id).css('height', M.Environment.getHeight() - this.headerheight - this.footerheight);
        }

        /* initialize the scrolling stuff (if not done yet) */
        if (!this.scrollviewsInitialized) {
            $('#' + this.content.id).scrollview({
                direction: 'y'
            });

            /* check whether scrolling is required or not for the menu */
            if (this.orientation === 'landscape') {
                this.itemheight = $('#' + this.menu.menu.id).find('li:first').outerHeight();
                var itemCount = $('#' + this.menu.menu.id).find('li').length;

                if (this.itemheight !== 0) {
                    var menuHeight = M.Environment.getHeight();
                    var itemListHeight = itemCount * this.itemheight;
                    if (menuHeight < itemListHeight) {
                        $('#' + this.menu.menu.id).scrollview({
                            direction: 'y'
                        });
                        this.hasMenuScrollview = YES;
                    } else {
                        this.shouldHaveScrollview = NO;
                    }
                }
                this.scrollviewsInitialized = YES;
            }

        }
    },

    /**
     * Called when Dom Content Loaded event arrived, to calculate height of header and footer
     * and set the contentLoaded, call theme update, in order to check out if a scrollview for menu is needed
     */
    initializeVar: function() {
        this.headerheight = $('#' + M.ViewManager.getCurrentPage().id + ' .ui-header').height();
        this.footerheight = $('#' + M.ViewManager.getCurrentPage().id + ' .ui-footer').height();
        this.contentLoaded = YES;
        this.themeUpdate();
    },

    registerEvents: function() {
        /* register for orientation change events of the current page */
        var page = M.ViewManager.getCurrentPage() || M.ViewManager.getPage(M.Application.entryPage);
        M.EventDispatcher.registerEvent(
            'orientationdidchange',
            page.id,
            {
                target: this,
                action:  function() {
                    /* trigger re-theming with a little delay to make sure, the orientation change did finish */
                    var that = this;
                    window.setTimeout(function() {
                        that.orientationDidChange();
                    }, 100);
                }
            },
            ['orientationdidchange'],
            null,
            NO,
            YES
        );
    },

    listItemSelected: function(id) {
        var contentView = M.ViewManager.getViewById(id) && M.ViewManager.getViewById(id).splitViewItem ? M.ViewManager.getViewById(id).splitViewItem.view : null;

        if (!contentView) {
            return;
        }

        this.selectedItem = M.ViewManager.getViewById(id).splitViewItem;

        if (!this.isInitialized) {
            if (contentView.html) {
                $('#' + this.content.id).html(contentView.html);
            } else {
                $('#' + this.content.id).html(contentView.render());
                contentView.theme();
                contentView.registerEvents();
            }
            this.isInitialized = YES;
        } else {
            if (contentView.html) {
                $('#' + this.content.id + ' div:first').html(contentView.html);
            } else {
                $('#' + this.content.id + ' div:first').html(contentView.render());
                contentView.theme();
                contentView.registerEvents();
            }
            $('#' + this.content.id).scrollview('scrollTo', 0, 0);
        }

        /* check if there is a split toolbar view on the page and update its label to show the value of the selected item */
        var page = M.ViewManager.getCurrentPage() || M.ViewManager.getPage(M.Application.entryPage);
        var that = this;
        if (page) {
            $('#' + page.id + ' .tmp-splitview-content-toolbar').each(function() {
                var toolbar = M.ViewManager.getViewById($(this).attr('id'));
                if (toolbar.parentView && toolbar.parentView.showSelectedItemInMainHeader) {
                    toolbar.value = M.ViewManager.getViewById(id).splitViewItem.value;
                    $('#' + toolbar.id + ' h1').html(toolbar.value);

                    /* now link the menu with the toolbar if not yet done */
                    if (!toolbar.parentView.splitview) {
                        toolbar.parentView.splitview = that;
                    }
                }
            });

            /* add special css class if there is no footer */
            if ($('#' + page.id + ' .ui-footer').length === 0) {
                page.addCssClass('tmp-splitview-no-footer');
            }

            /* add special css class if there is no header */
            if ($('#' + page.id + ' .tmp-splitview-content-toolbar').length === 0) {
                page.addCssClass('tmp-splitview-no-header');
            }
        }
    },

    orientationDidChange: function() {
        var orientation = M.Environment.getOrientation();
        var that = this;
        var page = M.ViewManager.getCurrentPage() || M.ViewManager.getPage(M.Application.entryPage);

        /* portrait */
        if (M.Environment.getHeight() > M.Environment.getWidth()) {
            $('html').removeClass('landscape');
            $('html').addClass('portrait');
        /* landscape */
        } else {
            $('html').removeClass('portrait');
            $('html').addClass('landscape');

            /* hide the popover */
            var toolbar;
            if (page) {
                $('#' + page.id + ' .tmp-splitview-menu-toolbar').each(function() {
                    toolbar = M.ViewManager.getViewById($(this).attr('id'));
                    if (toolbar && toolbar.parentView && toolbar.parentView.popover) {
                        toolbar.parentView.popover.hide();
                    }
                });
            }

            /* update the menu */
            var id;
            $('#' + this.menu.id).find('li').each(function() {
                if (M.ViewManager.getViewById($(this).attr('id')).splitViewItem.id === that.selectedItem.id) {
                    id = $(this).attr('id');
                }
            });

            /* activate the current item */
            if (id) {
                this.menu.menu.setActiveListItem(id);
            }

            /* set the selected item */
            this.selectedItem = M.ViewManager.getViewById(id).splitViewItem;

            /* scroll the menu so we def. see the selected item */
            this.scrollListToRightPosition(id);
        }

        /* scroll content to top */
        $('#' + this.content.id).scrollview('scrollTo', 0, 0);

        /* call theme update */
        this.themeUpdate();

        /* fix the toolbars */
        $.mobile.fixedToolbars.show();
    },

    scrollListToRightPosition: function(id) {
        var itemHeight = $('#' + this.menu.menu.id + ' li:first-child').outerHeight();
        var y = ($('#' + id).index() + 1) * itemHeight;
        var menuHeight = M.Environment.getHeight() - this.headerheight - this.footerheight;
        var middle = menuHeight / 2;
        var distanceToListEnd = $('#' + this.menu.menu.id).find('li').length * itemHeight - y;
        var yScroll = 0;

        /* if y coordinate of item is greater than menu height, we need to scroll down */
        if (y > menuHeight) {
            if (distanceToListEnd < middle) {
                yScroll = -(y - menuHeight + distanceToListEnd);
            } else {
                yScroll = -(y - middle);
            }
            /* if y coordinate of item is less than menu height, we need to scroll up */
        } else if (y < menuHeight) {
            if (y < middle) {
                yScroll = 0;
            } else {
                yScroll = -(y - middle);
            }
        }

        /* if there already is a scroll view, just scroll */
        if (!this.hasMenuScrollview && this.shouldHaveScrollview) {
            $('#' + this.menu.menu.id).scrollview({
                direction: 'y'
            });
        }
        $('#' + this.menu.menu.id).scrollview('scrollTo', 0, yScroll);
    }

});
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2011 panacoda GmbH. All rights reserved.
// Creator:   dominik
// Date:      05.12.11
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

/**
 * @class
 *
 * The M.TableView renders a default HTML table, that can be dynamically filled via
 * content binding. Depending on the table's configuration, there will be a static
 * table header, that is visible even if there is no content. It is also possible
 * to always update the header, when applying content binding, too.
 *
 * @extends M.View
 */
M.TableView = M.View.extend(
/** @scope M.TableView.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.TableView',

    /**
     * Determines whether to remove all content rows if the table is updated or not.
     *
     * @type Boolean
     */
    removeContentRowsOnUpdate: YES,

    /**
     * Determines whether to remove the header rows if the table is updated or not.
     *
     * @type Boolean
     */
    removeHeaderRowOnUpdate: NO,

    /**
     * Determines whether the table was initialized. If this flag is set to YES,
     * the table's header and colgroup was rendered. Depending on the table's
     * configuration (e.g. the removeHeaderRowOnUpdate property), this flag might
     * change dynamically at runtime.
     *
     * @private
     * @type Boolean
     */
    isInitialized: NO,

    /**
     * This property can be used to specify the table's header and cols, independent
     * from dynamically loaded table content. It can be provided with the table's
     * definition within a page component. The table's content, in contrast, can only
     * be applied via content binding.
     *
     * Note: If the removeHeaderRowOnUpdate property is set to YES, the header will
     * be removed whenever a content binding is applied. So if the header shall be
     * statically specified by the view component, do not set that property to YES!
     *
     * This property should look something like the following:
     *
     *   {
     *     data: ['col1', 'col2', 'col3'],
     *     cols: ['20%', '10%', '70%']
     *   }
     *
     * Note: the cols property of this object is optional. You can also let CSS take
     * care of the columns arrangement or simply let the browser do all the work
     * automatically.
     *
     * @type Object
     */
    header: null,

    /**
     * Renders a table view as a table element within a div box.
     *
     * @private
     * @returns {String} The table view's html representation.
     */
    render: function() {
        this.html += '

';

        return this.html;
    },

    /**
     * Applies some style-attributes to the table.
     *
     * @private
     * @returns {String} The table's styling as html representation.
     */
    style: function() {
        var html = ' class="tmp-table';
        if(this.cssClass) {
            html += ' ' + this.cssClass;
        }
        html += '"'
        return html;
    },

    /**
     * This method is called once the initial rendering was applied to the
     * DOM. So this is where we will add the table's header (if there is
     * one specified)
     */
    theme: function() {
        if(this.header) {
            this.renderHeader();
        }
    },

    /**
     * This method renders the table's header. Based on the table's configuration,
     * this can either happen right at the first rendering or on every content
     * binding update.
     *
     * @private
     */
    renderHeader: function() {
        /* render the table header (if there is one) and define the cols */
        if(this.header && this.header.data) {

            /* render the colgroup element (define the columns) */
            if(this.header.cols && this.header.cols.length > 0) {
                html = '<colgroup>';
                _.each(this.header.cols, function(col) {
                    html += '<col width="' + col + '">';
                });
                html += '</colgroup>';
                $('#' + this.id).prepend(html);
            }

            /* render the table header */
            html = '
';
            _.each(this.header.data, function(col) {
                html += '' + (col && col.toString() ? col.toString() : '') + '	 ';
            });
            html += '
';
            this.addRow(html, YES);
        }
    },

    /**
     * Updates the table based on its content binding. This should look like the following:
     *
     *   {
     *     header: {
     *       data: ['col1', 'col2', 'col3'],
     *       cols: ['20%', '10%', '70%']
     *     },
     *     content: [
     *       [25, 'Y, 'Lorem Ipsum'],
     *       [25, 46, 'Dolor Sit'],
     *       [25, 46, 'Amet']
     *     ]
     *   }
     *
     * Note: If the content binding specifies a header object, any previously rendered
     * header (and the col definition) will be overwritten!
     *
     * @private
     */
    renderUpdate: function() {
        var html;
        var content = this.value;

        /* clear the table before filling it up again */
        if(this.removeHeaderRowOnUpdate && this.removeContentRowsOnUpdate) {
            this.removeAllRows();
        } else if(this.removeContentRowsOnUpdate) {
            this.removeContentRows();
        }

        if(content && content.content && content.content.length > 0) {

            /* render the table header (if there is one) */
            if(content.header && content.header.data) {
                this.header = content.header;
                this.renderHeader();
            }

            /* render the table's content (row by row) */
            if(content.content && content.content.length > 0) {
                var that = this;
                var zebraFlag = 0;
                _.each(content.content, function(row) {
                    zebraFlag = (zebraFlag === 0 ? 1 : 0);
                    html = '
';
                    _.each(row, function(col) {
                        html += '' + (col && col.toString() ? col.toString() : '') + '	 ';
                    });
                    html += '
';
                    that.addRow(html);
                });
            }

        }
        else {
            M.Logger.log('The specified content binding for the table view (' + this.id + ') is invalid!', M.WARN);
        }
    },

    /**
     * This method adds a new row to the table view by simply appending its html representation
     * to the table view inside the DOM. This method is based on jQuery's append().
     *
     * @param {String} row The html representation of a table row to be added.
     * @param {Boolean} addToTableHeader Determines whether or not to add the row to the table's header.
     */
    addRow: function(row, addToTableHeader) {
        if(addToTableHeader) {
            $('#' + this.id + ' thead').append(row);
        } else {
            $('#' + this.id + ' tbody').append(row);
        }
    },

    /**
     * This method removes all of the table view's rows by removing all of its content in the DOM. This
     * method is based on jQuery's empty().
     */
    removeAllRows: function() {
        $('#' + this.id).empty();
    },

    /**
     * This method removes all content rows of the table view by removing the corresponding
     * html in the DOM. This method is based on jQuery's remove().
     */
    removeContentRows: function() {
        $('#' + 'm_3' + ' tr td').parent().remove();
    }

});<commit_msg>Fixed the hard code id<commit_after>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2011 panacoda GmbH. All rights reserved.
// Creator:   dominik
// Date:      05.12.11
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

/**
 * @class
 *
 * The M.TableView renders a default HTML table, that can be dynamically filled via
 * content binding. Depending on the table's configuration, there will be a static
 * table header, that is visible even if there is no content. It is also possible
 * to always update the header, when applying content binding, too.
 *
 * @extends M.View
 */
M.TableView = M.View.extend(
/** @scope M.TableView.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.TableView',

    /**
     * Determines whether to remove all content rows if the table is updated or not.
     *
     * @type Boolean
     */
    removeContentRowsOnUpdate: YES,

    /**
     * Determines whether to remove the header rows if the table is updated or not.
     *
     * @type Boolean
     */
    removeHeaderRowOnUpdate: NO,

    /**
     * Determines whether the table was initialized. If this flag is set to YES,
     * the table's header and colgroup was rendered. Depending on the table's
     * configuration (e.g. the removeHeaderRowOnUpdate property), this flag might
     * change dynamically at runtime.
     *
     * @private
     * @type Boolean
     */
    isInitialized: NO,

    /**
     * This property can be used to specify the table's header and cols, independent
     * from dynamically loaded table content. It can be provided with the table's
     * definition within a page component. The table's content, in contrast, can only
     * be applied via content binding.
     *
     * Note: If the removeHeaderRowOnUpdate property is set to YES, the header will
     * be removed whenever a content binding is applied. So if the header shall be
     * statically specified by the view component, do not set that property to YES!
     *
     * This property should look something like the following:
     *
     *   {
     *     data: ['col1', 'col2', 'col3'],
     *     cols: ['20%', '10%', '70%']
     *   }
     *
     * Note: the cols property of this object is optional. You can also let CSS take
     * care of the columns arrangement or simply let the browser do all the work
     * automatically.
     *
     * @type Object
     */
    header: null,

    /**
     * Renders a table view as a table element within a div box.
     *
     * @private
     * @returns {String} The table view's html representation.
     */
    render: function() {
        this.html += '

';

        return this.html;
    },

    /**
     * Applies some style-attributes to the table.
     *
     * @private
     * @returns {String} The table's styling as html representation.
     */
    style: function() {
        var html = ' class="tmp-table';
        if(this.cssClass) {
            html += ' ' + this.cssClass;
        }
        html += '"'
        return html;
    },

    /**
     * This method is called once the initial rendering was applied to the
     * DOM. So this is where we will add the table's header (if there is
     * one specified)
     */
    theme: function() {
        if(this.header) {
            this.renderHeader();
        }
    },

    /**
     * This method renders the table's header. Based on the table's configuration,
     * this can either happen right at the first rendering or on every content
     * binding update.
     *
     * @private
     */
    renderHeader: function() {
        /* render the table header (if there is one) and define the cols */
        if(this.header && this.header.data) {

            /* render the colgroup element (define the columns) */
            if(this.header.cols && this.header.cols.length > 0) {
                html = '<colgroup>';
                _.each(this.header.cols, function(col) {
                    html += '<col width="' + col + '">';
                });
                html += '</colgroup>';
                $('#' + this.id).prepend(html);
            }

            /* render the table header */
            html = '
';
            _.each(this.header.data, function(col) {
                html += '' + (col && col.toString() ? col.toString() : '') + '	 ';
            });
            html += '
';
            this.addRow(html, YES);
        }
    },

    /**
     * Updates the table based on its content binding. This should look like the following:
     *
     *   {
     *     header: {
     *       data: ['col1', 'col2', 'col3'],
     *       cols: ['20%', '10%', '70%']
     *     },
     *     content: [
     *       [25, 'Y, 'Lorem Ipsum'],
     *       [25, 46, 'Dolor Sit'],
     *       [25, 46, 'Amet']
     *     ]
     *   }
     *
     * Note: If the content binding specifies a header object, any previously rendered
     * header (and the col definition) will be overwritten!
     *
     * @private
     */
    renderUpdate: function() {
        var html;
        var content = this.value;

        /* clear the table before filling it up again */
        if(this.removeHeaderRowOnUpdate && this.removeContentRowsOnUpdate) {
            this.removeAllRows();
        } else if(this.removeContentRowsOnUpdate) {
            this.removeContentRows();
        }

        if(content && content.content && content.content.length > 0) {

            /* render the table header (if there is one) */
            if(content.header && content.header.data) {
                this.header = content.header;
                this.renderHeader();
            }

            /* render the table's content (row by row) */
            if(content.content && content.content.length > 0) {
                var that = this;
                var zebraFlag = 0;
                _.each(content.content, function(row) {
                    zebraFlag = (zebraFlag === 0 ? 1 : 0);
                    html = '
';
                    _.each(row, function(col) {
                        html += '' + (col && col.toString() ? col.toString() : '') + '	 ';
                    });
                    html += '
';
                    that.addRow(html);
                });
            }

        }
        else {
            M.Logger.log('The specified content binding for the table view (' + this.id + ') is invalid!', M.WARN);
        }
    },

    /**
     * This method adds a new row to the table view by simply appending its html representation
     * to the table view inside the DOM. This method is based on jQuery's append().
     *
     * @param {String} row The html representation of a table row to be added.
     * @param {Boolean} addToTableHeader Determines whether or not to add the row to the table's header.
     */
    addRow: function(row, addToTableHeader) {
        if(addToTableHeader) {
            $('#' + this.id + ' thead').append(row);
        } else {
            $('#' + this.id + ' tbody').append(row);
        }
    },

    /**
     * This method removes all of the table view's rows by removing all of its content in the DOM. This
     * method is based on jQuery's empty().
     */
    removeAllRows: function() {
        $('#' + this.id).empty();
    },

    /**
     * This method removes all content rows of the table view by removing the corresponding
     * html in the DOM. This method is based on jQuery's remove().
     */
    removeContentRows: function() {
        $('#' + this.id + ' tr td').parent().remove();
    }

});<|endoftext|>


<commit_before>var esprima = require('esprima'),
    escodegen = require('escodegen');

var powerAssertVariableDeclaration = {
    "type": "VariableDeclaration",
    "declarations": [
        {
            "type": "VariableDeclarator",
            "id": {
                "type": "Identifier",
                "name": "passert"
            },
            "init": {
                "type": "CallExpression",
                "callee": {
                    "type": "Identifier",
                    "name": "require"
                },
                "arguments": [
                    {
                        "type": "Literal",
                        "value": "../lib/power-assert"
                    }
                ]
            }
        }
    ],
    "kind": "var"
};

// Executes visitor on the object and its children (recursively).
var traverse = function traverse(object, visitor) {
    var key, child;

    visitor.call(null, object);
    for (key in object) {
        if (object.hasOwnProperty(key)) {
            child = object[key];
            if (typeof child === 'object' && child !== null) {
                traverse(child, visitor);
            }
        }
    }
};

var powerAssertGenerator = function powerAssertGenerator(source, options) {
    options = options || {};
    var lines = source.split("\n");
    var syntax = esprima.parse(source, {tolerant: true, loc: true});

    var isAssertOkCall = function (callee) {
        if (callee.type !== 'MemberExpression' || callee.computed !== false) {
            return false;
        }
        var ob = callee.object,
            prop = callee.property;
        return ((ob.type === 'Identifier' && ob.name === 'assert') && (prop.type === 'Identifier' && prop.name === 'ok'));
    };

    var isAssertCall = function (callee) {
        return (callee.type === 'Identifier' && callee.name === 'assert');
    };

    // enclose  in __ident__
    var capture = function (target, ident) {
        return {
            "type": "CallExpression",
            "callee": {
                "type": "MemberExpression",
                "computed": false,
                "object": {
                    "type": "Identifier",
                    "name": "passert"
                },
                "property": {
                    "type": "Identifier",
                    "name": "__ident__"
                }
            },
            "arguments": [
                {
                    "type": "Literal",
                    "value": ident.name
                },
                target,
                {
                    "type": "Literal",
                    "value": ident.loc.start.column
                },
                {
                    "type": "Literal",
                    "value": ident.loc.end.column
                }
            ]
        };
    };

    var captureIdent = function (ident) {
        return capture(ident, ident);
    };

    var captureMember = function (member) {
        member.object = captureIdent(member.object);
        return capture(member, member.property);
    };

    // enclose assert expression in __expr__
    var captureFirstArgument = function (firstArgument, line) {
        return {
            "type": "CallExpression",
            "callee": {
                "type": "MemberExpression",
                "computed": false,
                "object": {
                    "type": "Identifier",
                    "name": "passert"
                },
                "property": {
                    "type": "Identifier",
                    "name": "__expr__"
                }
            },
            "arguments": [
                firstArgument,
                {
                    "type": "Literal",
                    "value": line
                }
            ]
        };
    };

    traverse(syntax, function (node) {
        if (typeof node.type === 'undefined' || node.type !== 'ExpressionStatement') {
            return;
        }
        var expression = node.expression;
        if (typeof expression.type === 'undefined' || expression.type !== 'CallExpression') {
            return;
        }
        var callee = expression.callee;
        if (!(isAssertCall(callee) || isAssertOkCall(callee))) {
            return;
        }

        var line = lines[node.loc.start.line - 1];

        var firstArgument = expression.arguments[0];

        if (firstArgument.type === 'Identifier') {
            firstArgument = captureIdent(firstArgument);
            expression.arguments[0] = captureFirstArgument(firstArgument, line);
        } else if (firstArgument.type === 'BinaryExpression') {
            var left = firstArgument.left,
                right = firstArgument.right;

            if (left.type === 'Identifier') {
                firstArgument.left = captureIdent(left);
            } else if (left.type === 'MemberExpression') {
                // ex: ary.length
                firstArgument.left = captureMember(left);
            }

            if (right.type === 'Identifier') {
                firstArgument.right = captureIdent(right);
            } else if (right.type === 'MemberExpression') {
                // ex: ary.length
                firstArgument.right = captureMember(right);
            }

            expression.arguments[0] = captureFirstArgument(firstArgument, line);
        }
    });

    if (options['module'] === 'CommonJS') {
        // insert "var passert = require('power-assert');"
        syntax.body.unshift(powerAssertVariableDeclaration);
    }

    console.log(escodegen.generate(syntax));
    //return syntax;
};

/*global exports:false*/
if (typeof exports !== 'undefined') {
    module.exports = powerAssertGenerator;
}
<commit_msg>flatten<commit_after>var esprima = require('esprima'),
    escodegen = require('escodegen');

// Executes visitor on the object and its children (recursively).
var traverse = function traverse(object, visitor) {
    var key, child;

    visitor.call(null, object);
    for (key in object) {
        if (object.hasOwnProperty(key)) {
            child = object[key];
            if (typeof child === 'object' && child !== null) {
                traverse(child, visitor);
            }
        }
    }
};

var powerAssertVariableDeclaration = {
    "type": "VariableDeclaration",
    "declarations": [
        {
            "type": "VariableDeclarator",
            "id": {
                "type": "Identifier",
                "name": "passert"
            },
            "init": {
                "type": "CallExpression",
                "callee": {
                    "type": "Identifier",
                    "name": "require"
                },
                "arguments": [
                    {
                        "type": "Literal",
                        "value": "../lib/power-assert"
                    }
                ]
            }
        }
    ],
    "kind": "var"
};

var isAssertOkCall = function (callee) {
    if (callee.type !== 'MemberExpression' || callee.computed !== false) {
        return false;
    }
    var ob = callee.object,
        prop = callee.property;
    return ((ob.type === 'Identifier' && ob.name === 'assert') && (prop.type === 'Identifier' && prop.name === 'ok'));
};

var isAssertCall = function (callee) {
    return (callee.type === 'Identifier' && callee.name === 'assert');
};

// enclose  in __ident__
var capture = function (target, ident) {
    return {
        "type": "CallExpression",
        "callee": {
            "type": "MemberExpression",
            "computed": false,
            "object": {
                "type": "Identifier",
                "name": "passert"
            },
            "property": {
                "type": "Identifier",
                "name": "__ident__"
            }
        },
        "arguments": [
            {
                "type": "Literal",
                "value": ident.name
            },
            target,
            {
                "type": "Literal",
                "value": ident.loc.start.column
            },
            {
                "type": "Literal",
                "value": ident.loc.end.column
            }
        ]
    };
};

var captureIdent = function (ident) {
    return capture(ident, ident);
};

var captureMember = function (member) {
    member.object = captureIdent(member.object);
    return capture(member, member.property);
};

// enclose assert expression in __expr__
var captureFirstArgument = function (firstArgument, line) {
    return {
        "type": "CallExpression",
        "callee": {
            "type": "MemberExpression",
            "computed": false,
            "object": {
                "type": "Identifier",
                "name": "passert"
            },
            "property": {
                "type": "Identifier",
                "name": "__expr__"
            }
        },
        "arguments": [
            firstArgument,
            {
                "type": "Literal",
                "value": line
            }
        ]
    };
};

var handleExpression = function (expression, line) {
    var firstArgument = expression.arguments[0];

    if (firstArgument.type === 'Identifier') {
        firstArgument = captureIdent(firstArgument);
        expression.arguments[0] = captureFirstArgument(firstArgument, line);
    } else if (firstArgument.type === 'BinaryExpression') {
        var left = firstArgument.left,
            right = firstArgument.right;

        if (left.type === 'Identifier') {
            firstArgument.left = captureIdent(left);
        } else if (left.type === 'MemberExpression') {
            // ex: ary.length
            firstArgument.left = captureMember(left);
        }

        if (right.type === 'Identifier') {
            firstArgument.right = captureIdent(right);
        } else if (right.type === 'MemberExpression') {
            // ex: ary.length
            firstArgument.right = captureMember(right);
        }

        expression.arguments[0] = captureFirstArgument(firstArgument, line);
    }
};

var powerAssertGenerator = function powerAssertGenerator(source, options) {
    options = options || {};
    var lines = source.split("\n");
    var syntax = esprima.parse(source, {tolerant: true, loc: true});

    traverse(syntax, function (node) {
        if (typeof node.type === 'undefined' || node.type !== 'ExpressionStatement') {
            return;
        }
        var expression = node.expression;
        if (typeof expression.type === 'undefined' || expression.type !== 'CallExpression') {
            return;
        }
        var callee = expression.callee;
        if (!(isAssertCall(callee) || isAssertOkCall(callee))) {
            return;
        }

        var line = lines[node.loc.start.line - 1];

        handleExpression(expression, line);
    });

    if (options['module'] === 'CommonJS') {
        // insert "var passert = require('power-assert');"
        syntax.body.unshift(powerAssertVariableDeclaration);
    }

    console.log(escodegen.generate(syntax));
    //return syntax;
};

/*global exports:false*/
if (typeof exports !== 'undefined') {
    module.exports = powerAssertGenerator;
}
<|endoftext|>


<commit_before>var _ = require('lodash')
var Slide = require('./slide')
var Paragraph = require('./paragraph')

function Shape (nativeShape) {
  var shape = this

  shape.attr = function (name, value) {
    if (typeof value !== 'undefined') {
      return new Shape(nativeShape.attr({name: name, value: value}, true))
    }
    return nativeShape.attr(name, true)
  }

  // inject attr
  _.assign(shape, require('./shape.attr'))

  shape.remove = function () {
    return nativeShape.remove(null, true)
  }

  shape.duplicate = function () {
    return new Shape(nativeShape.duplicate(null, true))
  }

  shape.paragraph = function (start, length) {
    start = start || -1
    length = length || -1
    if (shape.text() === null) {
      return null
    }
    return new Paragraph(nativeShape.paragraph({'start': start, 'length': length}, true))
  }

  shape.p = shape.paragraph

  shape.addLine = function (text, pos) {
    if (typeof pos !== 'number') {
      shape.paragraph(shape.paragraph().count() + 1, -1).text(text)
      return shape
    } else {
      shape.paragraph(pos, -1).text(text)
      return shape
    }
  }

  shape.removeLine = function (pos) {
    if (typeof pos !== 'number') {
      shape.paragraph(shape.paragraph().count(), -1).remove()
      return shape
    } else {
      shape.paragraph(pos, -1).remove()
      return shape
    }
  }

  shape.textReplace = function (findString, replaceString) {
    return new Shape(nativeShape.textReplace({'find': findString, 'replace': replaceString}))
  }

  shape.exportAs = function (options) {
    if (typeof options === 'string') {
      var path = options
      options = {'path': path}
      return nativeShape.exportAs(options)
    } else if (typeof options === 'object') {
      return nativeShape.exportAs(options)
    }
  }

  shape.zIndex = function (cmd) {
    if (typeof cmd === 'string') {
      return nativeShape.setZindex(cmd, true)
    } else if (typeof cmd === 'number') {
      var command
      var index = nativeShape.getZindex(null, true)
      if (index < cmd) {
        command = 'forward'
      } else if (index > cmd) {
        command = 'back'
      }
      while (index !== cmd) {
        nativeShape.setZindex(command, true)
        index = nativeShape.getZindex(null, true)
      }
      return new Shape(nativeShape)
    } else {
      return nativeShape.getZindex(null, true)
    }
  }

  shape.z = shape.zIndex

  shape.tag = {
    get: function (name) {
      return nativeShape.tags(null, true).get(name, true)
    },
    set: function (name, value) {
      nativeShape.tags(null, true).set({name: name, value: value}, true)
      return shape
    },
    remove: function (name) {
      nativeShape.tags(null, true).remove(name, true)
      return shape
    }
  }

  shape.tags = nativeShape.tags(null, true).all(null, true)

  shape.getType = function () {
    return nativeShape.getType(null, true)
  }
}

module.exports = Shape
<commit_msg>rm unused require<commit_after>var _ = require('lodash')
var Paragraph = require('./paragraph')

function Shape (nativeShape) {
  var shape = this

  shape.attr = function (name, value) {
    if (typeof value !== 'undefined') {
      return new Shape(nativeShape.attr({name: name, value: value}, true))
    }
    return nativeShape.attr(name, true)
  }

  // inject attr
  _.assign(shape, require('./shape.attr'))

  shape.remove = function () {
    return nativeShape.remove(null, true)
  }

  shape.duplicate = function () {
    return new Shape(nativeShape.duplicate(null, true))
  }

  shape.paragraph = function (start, length) {
    start = start || -1
    length = length || -1
    if (shape.text() === null) {
      return null
    }
    return new Paragraph(nativeShape.paragraph({'start': start, 'length': length}, true))
  }

  shape.p = shape.paragraph

  shape.addLine = function (text, pos) {
    if (typeof pos !== 'number') {
      shape.paragraph(shape.paragraph().count() + 1, -1).text(text)
      return shape
    } else {
      shape.paragraph(pos, -1).text(text)
      return shape
    }
  }

  shape.removeLine = function (pos) {
    if (typeof pos !== 'number') {
      shape.paragraph(shape.paragraph().count(), -1).remove()
      return shape
    } else {
      shape.paragraph(pos, -1).remove()
      return shape
    }
  }

  shape.textReplace = function (findString, replaceString) {
    return new Shape(nativeShape.textReplace({'find': findString, 'replace': replaceString}))
  }

  shape.exportAs = function (options) {
    if (typeof options === 'string') {
      var path = options
      options = {'path': path}
      return nativeShape.exportAs(options)
    } else if (typeof options === 'object') {
      return nativeShape.exportAs(options)
    }
  }

  shape.zIndex = function (cmd) {
    if (typeof cmd === 'string') {
      return nativeShape.setZindex(cmd, true)
    } else if (typeof cmd === 'number') {
      var command
      var index = nativeShape.getZindex(null, true)
      if (index < cmd) {
        command = 'forward'
      } else if (index > cmd) {
        command = 'back'
      }
      while (index !== cmd) {
        nativeShape.setZindex(command, true)
        index = nativeShape.getZindex(null, true)
      }
      return new Shape(nativeShape)
    } else {
      return nativeShape.getZindex(null, true)
    }
  }

  shape.z = shape.zIndex

  shape.tag = {
    get: function (name) {
      return nativeShape.tags(null, true).get(name, true)
    },
    set: function (name, value) {
      nativeShape.tags(null, true).set({name: name, value: value}, true)
      return shape
    },
    remove: function (name) {
      nativeShape.tags(null, true).remove(name, true)
      return shape
    }
  }

  shape.tags = nativeShape.tags(null, true).all(null, true)

  shape.getType = function () {
    return nativeShape.getType(null, true)
  }
}

module.exports = Shape
<|endoftext|>


<commit_before>/**
 * @fileOverview Dropbox integration
 * @author Mike Grabowski (@grabbou)
 * @version 0.1
 */

'use strict';

var StorageClient = require('../client'),
	Dropbox = require('dropbox'),
	async = require('async'),
	path = require('path'),
	util = require('util'),
	fs = require('fs'),
	_ = require('underscore');

/**
 * Creates new Dropbox constructor
 * @class
 * @classdesc Dropbox integration
 * Explanation:
 * - `token` - Dropbox API token for your application
 * - `folder` - Folder app should use. If your app is limited to specific folder,
 * you can skip that field.
 * @augments StorageClient
 * @param {Object} config
 */
var DropboxClient = function DropboxClient(config) {

	var client;

	config = _.defaults(config, {
		folder: ''
	});

	this._ensureValid(['token', 'folder'], config);

	client = new Dropbox.Client({
		token: config.token
	});

	DropboxClient.super_.call(this, config, client);
};

util.inherits(DropboxClient, StorageClient);

DropboxClient.prototype.upload = function (fileSrc, fileDest, callback) {

	var folderName = this._config.folder,
		destPath = path.join(folderName, fileDest),
		destName = path.basename(fileDest),
		client = this._connection;

	async.waterfall([

		// Returns file readStream
		function (callback) {
			fs.readFile(fileSrc, callback);
		},

		// Writes file to dropbox cloud
		function (buffer, callback) {
			client.writeFile(destPath, buffer, callback);
		},

		// Makes Url
		function (stat, callback) {
			client.makeUrl(destPath, {download: true}, callback);
		},

		// Returns object
		function (file, callback) {
			callback(null, {
				container: folderName,
				path: destPath,
				filename: destName,
				url: file.url
			});
		}

	], callback);

};

DropboxClient.prototype.remove = function (fileName, callback) {

	var fileSrc = path.join(this._config.folder, fileName),
		client = this._connection;

	client.remove(fileSrc, callback);

};

DropboxClient.prototype.download = function (fileName, fileDest, callback) {

	var fileSrc = path.join(this._config.folder, fileName),
		client = this._connection;

	async.waterfall([

		// Downloads file from Dropbox
		function (callback) {
			client.readFile(fileSrc, function (err, data) {
				callback(err, data);
			});
		},

		// Saves file into local system
		function (data, callback) {
			client.writeFile(fileDest, data, callback);
		}

	], callback);

};

DropboxClient.prototype._init = function (callback) {
	callback();
};

module.exports = DropboxClient;<commit_msg>Fixed naming conventions for Dropbox API and removed few errors<commit_after>/**
 * @fileOverview Dropbox integration
 * @author Mike Grabowski (@grabbou)
 * @version 0.1
 */

'use strict';

var StorageClient = require('../client'),
	Dropbox = require('dropbox'),
	async = require('async'),
	path = require('path'),
	util = require('util'),
	fs = require('fs'),
	_ = require('underscore');

/**
 * Creates new Dropbox constructor
 * @class
 * @classdesc Dropbox integration
 * Explanation:
 * - `token` - Dropbox API token for your application
 * - `folder` - Folder app should use. If your app is limited to specific folder,
 * you can skip that field.
 * @augments StorageClient
 * @param {Object} config
 */
var DropboxClient = function DropboxClient(config) {

	var client;

	config = _.defaults(config, {
		folder: ''
	});

	this._ensureValid(['token', 'folder'], config);

	client = new Dropbox.Client({
		token: config.token
	});

	DropboxClient.super_.call(this, config, client);
};

util.inherits(DropboxClient, StorageClient);

DropboxClient.prototype.upload = function (localSrc, destSrc, callback) {

	var folderName = this._config.folder,
		destPath = path.join(folderName, destSrc),
		fileName = path.basename(destSrc),
		client = this._connection;

	async.waterfall([

		// Returns file readStream
		function (callback) {
			fs.readFile(localSrc, callback);
		},

		// Writes file to dropbox cloud
		function (buffer, callback) {
			client.writeFile(destPath, buffer, callback);
		},

		// Makes Url
		function (stat, callback) {
			client.makeUrl(destPath, {download: true}, callback);
		},

		// Returns object
		function (file, callback) {
			callback(null, {
				container: folderName,
				path: destSrc,
				filename: fileName,
				url: file.url
			});
		}

	], callback);

};

DropboxClient.prototype.remove = function (destSrc, callback) {

	var client = this._connection;

	destSrc = path.join(this._config.folder, destSrc);

	client.remove(destSrc, callback);

};

DropboxClient.prototype.download = function (destSrc, localSrc, callback) {

	var client = this._connection;

	destSrc = path.join(this._config.folder, destSrc);

	async.waterfall([

		// Downloads file from Dropbox
		function (callback) {
			client.readFile(destSrc, function (err, data) {
				callback(err, data);
			});
		},

		// Saves file into local system
		function (data, callback) {
			client.writeFile(localSrc, data, callback);
		}

	], callback);

};

DropboxClient.prototype._init = function (callback) {
	callback();
};

module.exports = DropboxClient;<|endoftext|>