function _getVisibleItem(first) {
        var result = {};
        var diff;
        var prevDiff = 10000000;
        var diffDelta = (first && this.options.alignment) ? -this._contextSizeCache[this._direction] : ((!first && !this.options.alignment) ? this._contextSizeCache[this._direction] : 0);
        var scrollOffset = this._scroll.unnormalizedScrollOffset;
        var node = this._nodes.getStartEnumNode(true);
        while (node) {
            if (!node._invalidated || (node.scrollLength === undefined)) {
                break;
            }
            if (node._viewSequence) {
                diff = Math.abs(diffDelta - (scrollOffset + (!first ? node.scrollLength : 0)));
                if (diff >= prevDiff) {
                    break;
                }
                prevDiff = diff;
                result.scrollOffset = scrollOffset;
                result._node = node;
                scrollOffset += node.scrollLength;
            }
            node = node._next;
        }
        scrollOffset = this._scroll.unnormalizedScrollOffset;
        node = this._nodes.getStartEnumNode(false);
        while (node) {
            if (!node._invalidated || (node.scrollLength === undefined)) {
                break;
            }
            if (node._viewSequence) {
                scrollOffset -= node.scrollLength;
                diff = Math.abs(diffDelta - (scrollOffset + (!first ? node.scrollLength : 0)));
                if (diff >= prevDiff) {
                    break;
                }
                prevDiff = diff;
                result.scrollOffset = scrollOffset;
                result._node = node;
            }
            node = node._prev;
        }
        if (!result._node) {
            return undefined;
        }
        result.scrollLength = result._node.scrollLength;
        if (this.options.alignment) {
            result.visiblePerc = (Math.min(result.scrollOffset + result.scrollLength, 0) - Math.max(result.scrollOffset, -this._contextSizeCache[this._direction])) / result.scrollLength;
        }
        else {
            result.visiblePerc = (Math.min(result.scrollOffset + result.scrollLength, this._contextSizeCache[this._direction]) - Math.max(result.scrollOffset, 0)) / result.scrollLength;
        }
        result.index = result._node._viewSequence.getIndex();
        result.viewSequence = result._node._viewSequence;
        result.renderNode = result._node.renderNode;
        return result;
    }

function _getVisibleItem ( first ) { var result = { } ; var diff ; var prevDiff = 10000000 ; var diffDelta = ( first && this . options . alignment ) ? - this . _contextSizeCache [ this . _direction ] : ( ( ! first && ! this . options . alignment ) ? this . _contextSizeCache [ this . _direction ] : 0 ) ; var scrollOffset = this . _scroll . unnormalizedScrollOffset ; var node = this . _nodes . getStartEnumNode ( true ) ; while ( node ) { if ( ! node . _invalidated || ( node . scrollLength === undefined ) ) { break ; } if ( node . _viewSequence ) { diff = Math . abs ( diffDelta - ( scrollOffset + ( ! first ? node . scrollLength : 0 ) ) ) ; if ( diff >= prevDiff ) { break ; } prevDiff = diff ; result . scrollOffset = scrollOffset ; result . _node = node ; scrollOffset += node . scrollLength ; } node = node . _next ; } scrollOffset = this . _scroll . unnormalizedScrollOffset ; node = this . _nodes . getStartEnumNode ( false ) ; while ( node ) { if ( ! node . _invalidated || ( node . scrollLength === undefined ) ) { break ; } if ( node . _viewSequence ) { scrollOffset -= node . scrollLength ; diff = Math . abs ( diffDelta - ( scrollOffset + ( ! first ? node . scrollLength : 0 ) ) ) ; if ( diff >= prevDiff ) { break ; } prevDiff = diff ; result . scrollOffset = scrollOffset ; result . _node = node ; } node = node . _prev ; } if ( ! result . _node ) { return undefined ; } result . scrollLength = result . _node . scrollLength ; if ( this . options . alignment ) { result . visiblePerc = ( Math . min ( result . scrollOffset + result . scrollLength , 0 ) - Math . max ( result . scrollOffset , - this . _contextSizeCache [ this . _direction ] ) ) / result . scrollLength ; } else { result . visiblePerc = ( Math . min ( result . scrollOffset + result . scrollLength , this . _contextSizeCache [ this . _direction ] ) - Math . max ( result . scrollOffset , 0 ) ) / result . scrollLength ; } result . index = result . _node . _viewSequence . getIndex ( ) ; result . viewSequence = result . _node . _viewSequence ; result . renderNode = result . _node . renderNode ; return result ; }

Get the first or last visible item in the view.

Get the first or last visible item in the view .


function _goToSequence(viewSequence, next, noAnimation) {
        if (noAnimation) {
            this._viewSequence = viewSequence;
            this._scroll.springPosition = undefined;
            _updateSpring.call(this);
            this.halt();
            this._scroll.scrollDelta = 0;
            _setParticle.call(this, 0, 0, '_goToSequence');
            this._scroll.scrollDirty = true;
        }
        else {
            this._scroll.scrollToSequence = viewSequence;
            this._scroll.scrollToRenderNode = viewSequence.get();
            this._scroll.ensureVisibleRenderNode = undefined;
            this._scroll.scrollToDirection = next;
            this._scroll.scrollDirty = true;
        }
    }

function _goToSequence ( viewSequence , next , noAnimation ) { if ( noAnimation ) { this . _viewSequence = viewSequence ; this . _scroll . springPosition = undefined ; _updateSpring . call ( this ) ; this . halt ( ) ; this . _scroll . scrollDelta = 0 ; _setParticle . call ( this , 0 , 0 , '_goToSequence' ) ; this . _scroll . scrollDirty = true ; } else { this . _scroll . scrollToSequence = viewSequence ; this . _scroll . scrollToRenderNode = viewSequence . get ( ) ; this . _scroll . ensureVisibleRenderNode = undefined ; this . _scroll . scrollToDirection = next ; this . _scroll . scrollDirty = true ; } }

Helper function that goes to a view-sequence either by scrolling
or immediately without any scrolling animation.

Helper function that goes to a view - sequence either by scrolling or immediately without any scrolling animation .


function _ensureVisibleSequence(viewSequence, next) {
        this._scroll.scrollToSequence = undefined;
        this._scroll.scrollToRenderNode = undefined;
        this._scroll.ensureVisibleRenderNode = viewSequence.get();
        this._scroll.scrollToDirection = next;
        this._scroll.scrollDirty = true;
    }

function _ensureVisibleSequence ( viewSequence , next ) { this . _scroll . scrollToSequence = undefined ; this . _scroll . scrollToRenderNode = undefined ; this . _scroll . ensureVisibleRenderNode = viewSequence . get ( ) ; this . _scroll . scrollToDirection = next ; this . _scroll . scrollDirty = true ; }

Helper function that scrolls the view towards a view-sequence node.

Helper function that scrolls the view towards a view - sequence node .


function _goToPage(amount, noAnimation) {

        // Get current scroll-position. When a previous call was made to
        // `scroll' or `scrollTo` and that node has not yet been reached, then
        // the amount is accumalated onto that scroll target.
        var viewSequence = (!noAnimation ? this._scroll.scrollToSequence : undefined) || this._viewSequence;
        if (!this._scroll.scrollToSequence && !noAnimation) {
            var firstVisibleItem = this.getFirstVisibleItem();
            if (firstVisibleItem) {
                viewSequence = firstVisibleItem.viewSequence;
                if (((amount < 0) && (firstVisibleItem.scrollOffset < 0)) ||
                    ((amount > 0) && (firstVisibleItem.scrollOffset > 0))) {
                    amount = 0;
                }
            }
        }
        if (!viewSequence) {
            return;
        }

        // Find scroll target
        for (var i = 0; i < Math.abs(amount); i++) {
            var nextViewSequence = (amount > 0) ? viewSequence.getNext() : viewSequence.getPrevious();
            if (nextViewSequence) {
                viewSequence = nextViewSequence;
            }
            else {
                break;
            }
        }
        _goToSequence.call(this, viewSequence, amount >= 0, noAnimation);
    }

Moves to the next node in the viewSequence.

@param {Number} [amount] Amount of nodes to move
@param {Bool} [noAnimation] When set to true, immediately shows the node without any scrolling animation.

Moves to the next node in the viewSequence .


function _innerRender() {
        var specs = this._specs;
        for (var i3 = 0, j3 = specs.length; i3 < j3; i3++) {
            if (specs[i3].renderNode) {
                specs[i3].target = specs[i3].renderNode.render();
            }
        }

        // Add our cleanup-registration id also to the list, so that the
        // cleanup function is called by famo.us when the LayoutController is
        // removed from the render-tree.
        if (!specs.length || (specs[specs.length-1] !== this._cleanupRegistration)) {
            specs.push(this._cleanupRegistration);
        }
        return specs;
    }


function _setPullToRefreshState(pullToRefresh, state) {
        if (pullToRefresh.state !== state) {
            pullToRefresh.state = state;
            if (pullToRefresh.node && pullToRefresh.node.setPullToRefreshStatus) {
                pullToRefresh.node.setPullToRefreshStatus(state);
            }
        }
    }

function _setPullToRefreshState ( pullToRefresh , state ) { if ( pullToRefresh . state !== state ) { pullToRefresh . state = state ; if ( pullToRefresh . node && pullToRefresh . node . setPullToRefreshStatus ) { pullToRefresh . node . setPullToRefreshStatus ( state ) ; } } }

Helper function for setting the pull-to-refresh status.

Helper function for setting the pull - to - refresh status .


function ViewStackLayout(context, options) {
        var set = {
            size: context.size,
            translate: [0, 0, 0]
        };
        this._size[0] = context.size[0];
        this._size[1] = context.size[1];
        var views = context.get('views');
        var transferables = context.get('transferables');
        var visibleCount = 0;
        for (var i = 0; i < views.length; i++) {
            var item = this._viewStack[i];
            switch (item.state) {
                case ItemState.HIDDEN:
                    context.set(views[i], {
                        size: context.size,
                        translate: [context.size[0] * 2, context.size[1] * 2, 0]
                    });
                    break;

                case ItemState.HIDE:
                case ItemState.HIDING:
                case ItemState.VISIBLE:
                case ItemState.SHOW:
                case ItemState.SHOWING:
                    if (visibleCount < 2) {
                        visibleCount++;

                        // Layout view
                        var view = views[i];
                        context.set(view, set);

                        // Layout any transferables
                        for (var j = 0; j < transferables.length; j++) {
                            for (var k = 0; k < item.transferables.length; k++) {
                                if (transferables[j].renderNode === item.transferables[k].renderNode) {
                                    context.set(transferables[j], {
                                        translate: [0, 0, set.translate[2]],
                                        size: [context.size[0], context.size[1]]
                                    });
                                }
                            }
                        }

                        // Increase z-index for next view
                        set.translate[2] += options.zIndexOffset;
                    }
                    break;
            }
        }
    }

function
ViewStackLayout
(
context
,
options
)
{
var
set
=
{
size
:
context
.
size
,
translate
:
[
0
,
0
,
0
]
}
;
this
.
_size
[
0
]
=
context
.
size
[
0
]
;
this
.
_size
[
1
]
=
context
.
size
[
1
]
;
var
views
=
context
.
get
(
'views'
)
;
var
transferables
=
context
.
get
(
'transferables'
)
;
var
visibleCount
=
0
;
for
(
var
i
=
0
;
i
<
views
.
length
;
i
++
)
{
var
item
=
this
.
_viewStack
[
i
]
;
switch
(
item
.
state
)
{
case
ItemState
.
HIDDEN
:
context
.
set
(
views
[
i
]
,
{
size
:
context
.
size
,
translate
:
[
context
.
size
[
0
]
*
2
,
context
.
size
[
1
]
*
2
,
0
]
}
)
;
break
;
case
ItemState
.
HIDE
:
case
ItemState
.
HIDING
:
case
ItemState
.
VISIBLE
:
case
ItemState
.
SHOW
:
case
ItemState
.
SHOWING
:
if
(
visibleCount
<
2
)
{
visibleCount
++
;
// Layout view
var
view
=
views
[
i
]
;
context
.
set
(
view
,
set
)
;
// Layout any transferables
for
(
var
j
=
0
;
j
<
transferables
.
length
;
j
++
)
{
for
(
var
k
=
0
;
k
<
item
.
transferables
.
length
;
k
++
)
{
if
(
transferables
[
j
]
.
renderNode
===
item
.
transferables
[
k
]
.
renderNode
)
{
context
.
set
(
transferables
[
j
]
,
{
translate
:
[
0
,
0
,
set
.
translate
[
2
]
]
,
size
:
[
context
.
size
[
0
]
,
context
.
size
[
1
]
]
}
)
;
}
}
}
// Increase z-index for next view
set
.
translate
[
2
]
+=
options
.
zIndexOffset
;
}
break
;
}
}
}

Stacks the renderables on top of each other
with a z-translation of this.options.zIndexOffset.

Stacks the renderables on top of each other with a z - translation of this . options . zIndexOffset .


function _createLayout() {
        this._renderables = {
            views: [],
            transferables: []
        };
        this._viewStack = [];
        this.layout = new LayoutController({
            layout: ViewStackLayout.bind(this),
            layoutOptions: this.options,
            dataSource: this._renderables
        });
        this.add(this.layout);
        this.layout.on('layoutend', _processAnimations.bind(this));
    }

function _createLayout ( ) { this . _renderables = { views : [ ] , transferables : [ ] } ; this . _viewStack = [ ] ; this . layout = new LayoutController ( { layout : ViewStackLayout . bind ( this ) , layoutOptions : this . options , dataSource : this . _renderables } ) ; this . add ( this . layout ) ; this . layout . on ( 'layoutend' , _processAnimations . bind ( this ) ) ; }


function _getViewSpec(item, view, id, callback) {
        if (!item.view) {
            return;
        }
        var spec = view.getSpec(id);
        if (spec && !spec.trueSizeRequested) {
            callback(spec);
        }
        else {
            Timer.after(_getViewSpec.bind(this, item, view, id, callback), 1);
        }
    }

function _getViewSpec ( item , view , id , callback ) { if ( ! item . view ) { return ; } var spec = view . getSpec ( id ) ; if ( spec && ! spec . trueSizeRequested ) { callback ( spec ) ; } else { Timer . after ( _getViewSpec . bind ( this , item , view , id , callback ) , 1 ) ; } }


function _getTransferable(item, view, id) {
        // 1. If view supports getTransferable, use that
        if (view.getTransferable) {
            return view.getTransferable(id);
        }
        // 2. If view is derived from layoutcontroller, use that
        if (view.getSpec && view.get && view.replace) {
            if (view.get(id) !== undefined) {
                return {
                    get: function() {
                        return view.get(id);
                    },
                    show: function(renderable) {
                        view.replace(id, renderable);
                    },
                    getSpec: _getViewSpec.bind(this, item, view, id)
                };
            }
        }
        // 3. If view has an embedded layout, use that as fallback
        if (view.layout) {
            return _getTransferable.call(this, item, view.layout, id);
        }
    }

Gets the transferable delegate for the given id.

Gets the transferable delegate for the given id .


function _initTransferableAnimations(item, prevItem, callback) {
        var callbackCount = 0;
        function waitForAll() {
            callbackCount--;
            if (callbackCount === 0) {
                callback();
            }
        }
        for (var sourceId in item.options.transfer.items) {
            if (_initTransferableAnimation.call(this, item, prevItem, sourceId, waitForAll)) {
                callbackCount++;
            }
        }
        if (!callbackCount) {
            callback();
        }
    }

function _initTransferableAnimations ( item , prevItem , callback ) { var callbackCount = 0 ; function waitForAll ( ) { callbackCount -- ; if ( callbackCount === 0 ) { callback ( ) ; } } for ( var sourceId in item . options . transfer . items ) { if ( _initTransferableAnimation . call ( this , item , prevItem , sourceId , waitForAll ) ) { callbackCount ++ ; } } if ( ! callbackCount ) { callback ( ) ; } }

Begins visual transfer or renderables from the previous item
to the new item.

Begins visual transfer or renderables from the previous item to the new item .


function _endTransferableAnimations(item) {
        for (var j = 0; j < item.transferables.length; j++) {
            var transferable = item.transferables[j];
            for (var i = 0; i < this._renderables.transferables.length; i++) {
                if (this._renderables.transferables[i] === transferable.renderNode) {
                    this._renderables.transferables.splice(i, 1);
                    break;
                }
            }
            transferable.source.show(transferable.originalSource);
            transferable.target.show(transferable.originalTarget);
        }
        item.transferables = [];
        this.layout.reflowLayout();
    }

function _endTransferableAnimations ( item ) { for ( var j = 0 ; j < item . transferables . length ; j ++ ) { var transferable = item . transferables [ j ] ; for ( var i = 0 ; i < this . _renderables . transferables . length ; i ++ ) { if ( this . _renderables . transferables [ i ] === transferable . renderNode ) { this . _renderables . transferables . splice ( i , 1 ) ; break ; } } transferable . source . show ( transferable . originalSource ) ; transferable . target . show ( transferable . originalTarget ) ; } item . transferables = [ ] ; this . layout . reflowLayout ( ) ; }

Called whenever the view has been shown and the
transferable animations should be ended. This returns
the renderables to their original views.

Called whenever the view has been shown and the transferable animations should be ended . This returns the renderables to their original views .


function _processAnimations(event) {
        var prevItem;
        for (var i = 0; i < this._viewStack.length; i++) {
            var item = this._viewStack[i];
            switch (item.state) {
                case ItemState.HIDE:
                    item.state = ItemState.HIDING;
                    _initHideAnimation.call(this, item, prevItem, event.size);
                    _updateState.call(this);
                    break;
                case ItemState.SHOW:
                    item.state = ItemState.SHOWING;
                    _initShowAnimation.call(this, item, prevItem, event.size);
                    _updateState.call(this);
                    break;
            }
            prevItem = item;
        }
    }

function _processAnimations ( event ) { var prevItem ; for ( var i = 0 ; i < this . _viewStack . length ; i ++ ) { var item = this . _viewStack [ i ] ; switch ( item . state ) { case ItemState . HIDE : item . state = ItemState . HIDING ; _initHideAnimation . call ( this , item , prevItem , event . size ) ; _updateState . call ( this ) ; break ; case ItemState . SHOW : item . state = ItemState . SHOWING ; _initShowAnimation . call ( this , item , prevItem , event . size ) ; _updateState . call ( this ) ; break ; } prevItem = item ; } }


function _initShowAnimation(item, prevItem, size) {
        var spec = item.options.show.animation ? item.options.show.animation.call(undefined, true, size) : {};
        item.startSpec = spec;
        item.endSpec = {
            opacity: 1,
            transform: Transform.identity
        };
        item.mod.halt();
        if (spec.transform) {
            item.mod.setTransform(spec.transform);
        }
        if (spec.opacity !== undefined) {
            item.mod.setOpacity(spec.opacity);
        }
        if (spec.align) {
            item.mod.setAlign(spec.align);
        }
        if (spec.origin) {
            item.mod.setOrigin(spec.origin);
        }
        var startShowAnimation = _startShowAnimation.bind(this, item, spec);
        var waitAndShow = item.wait ? function() {
            item.wait.then(startShowAnimation, startShowAnimation);
        } : startShowAnimation;
        if (prevItem) {
            _initTransferableAnimations.call(this, item, prevItem, waitAndShow);
        }
        else {
            waitAndShow();
        }
    }

function _initShowAnimation ( item , prevItem , size ) { var spec = item . options . show . animation ? item . options . show . animation . call ( undefined , true , size ) : { } ; item . startSpec = spec ; item . endSpec = { opacity : 1 , transform : Transform . identity } ; item . mod . halt ( ) ; if ( spec . transform ) { item . mod . setTransform ( spec . transform ) ; } if ( spec . opacity !== undefined ) { item . mod . setOpacity ( spec . opacity ) ; } if ( spec . align ) { item . mod . setAlign ( spec . align ) ; } if ( spec . origin ) { item . mod . setOrigin ( spec . origin ) ; } var startShowAnimation = _startShowAnimation . bind ( this , item , spec ) ; var waitAndShow = item . wait ? function ( ) { item . wait . then ( startShowAnimation , startShowAnimation ) ; } : startShowAnimation ; if ( prevItem ) { _initTransferableAnimations . call ( this , item , prevItem , waitAndShow ) ; } else { waitAndShow ( ) ; } }


function _startShowAnimation(item, spec) {
        if (!item.halted) {
            var callback = item.showCallback;
            if (spec.transform) {
                item.mod.setTransform(Transform.identity, item.options.show.transition, callback);
                callback = undefined;
            }
            if (spec.opacity !== undefined) {
                item.mod.setOpacity(1, item.options.show.transition, callback);
                callback = undefined;
            }
            _startTransferableAnimations.call(this, item, callback);
        }
    }

function _startShowAnimation ( item , spec ) { if ( ! item . halted ) { var callback = item . showCallback ; if ( spec . transform ) { item . mod . setTransform ( Transform . identity , item . options . show . transition , callback ) ; callback = undefined ; } if ( spec . opacity !== undefined ) { item . mod . setOpacity ( 1 , item . options . show . transition , callback ) ; callback = undefined ; } _startTransferableAnimations . call ( this , item , callback ) ; } }

Starts the show animation whenever init has completed.

Starts the show animation whenever init has completed .


function _haltItemAtFrame(item, perc) {
        item.mod.halt();
        item.halted = true;
        if (item.startSpec && (perc !== undefined)) {
            if ((item.startSpec.opacity !== undefined) && (item.endSpec.opacity !== undefined)) {
                item.mod.setOpacity(_interpolate(item.startSpec.opacity, item.endSpec.opacity, perc));
            }
            if (item.startSpec.transform && item.endSpec.transform) {
                var transform = [];
                for (var i = 0; i < item.startSpec.transform.length; i++) {
                    transform.push(_interpolate(item.startSpec.transform[i], item.endSpec.transform[i], perc));
                }
                item.mod.setTransform(transform);
            }
        }
    }

function _haltItemAtFrame ( item , perc ) { item . mod . halt ( ) ; item . halted = true ; if ( item . startSpec && ( perc !== undefined ) ) { if ( ( item . startSpec . opacity !== undefined ) && ( item . endSpec . opacity !== undefined ) ) { item . mod . setOpacity ( _interpolate ( item . startSpec . opacity , item . endSpec . opacity , perc ) ) ; } if ( item . startSpec . transform && item . endSpec . transform ) { var transform = [ ] ; for ( var i = 0 ; i < item . startSpec . transform . length ; i ++ ) { transform . push ( _interpolate ( item . startSpec . transform [ i ] , item . endSpec . transform [ i ] , perc ) ) ; } item . mod . setTransform ( transform ) ; } } }

Halts a item at a given frame. The frame is provided as a percentage
of the whole transition.

Halts a item at a given frame . The frame is provided as a percentage of the whole transition .


function _initHideAnimation(item, prevItem, size) {
        var startHideAnimation = _startHideAnimation.bind(this, item, prevItem, size);
        if (item.wait) {
            item.wait.then(startHideAnimation, startHideAnimation);
        }
        else {
            startHideAnimation();
        }
    }

function _initHideAnimation ( item , prevItem , size ) { var startHideAnimation = _startHideAnimation . bind ( this , item , prevItem , size ) ; if ( item . wait ) { item . wait . then ( startHideAnimation , startHideAnimation ) ; } else { startHideAnimation ( ) ; } }


function _startHideAnimation(item, prevItem, size) {
        var spec = item.options.hide.animation ? item.options.hide.animation.call(undefined, false, size) : {};
        item.endSpec = spec;
        item.startSpec = {
            opacity: 1,
            transform: Transform.identity
        };
        if (!item.halted) {
            item.mod.halt();
            var callback = item.hideCallback;
            if (spec.transform) {
                item.mod.setTransform(spec.transform, item.options.hide.transition, callback);
                callback = undefined;
            }
            if (spec.opacity !== undefined) {
                item.mod.setOpacity(spec.opacity, item.options.hide.transition, callback);
                callback = undefined;
            }
            if (callback) {
                callback();
            }
        }
    }

function _startHideAnimation ( item , prevItem , size ) { var spec = item . options . hide . animation ? item . options . hide . animation . call ( undefined , false , size ) : { } ; item . endSpec = spec ; item . startSpec = { opacity : 1 , transform : Transform . identity } ; if ( ! item . halted ) { item . mod . halt ( ) ; var callback = item . hideCallback ; if ( spec . transform ) { item . mod . setTransform ( spec . transform , item . options . hide . transition , callback ) ; callback = undefined ; } if ( spec . opacity !== undefined ) { item . mod . setOpacity ( spec . opacity , item . options . hide . transition , callback ) ; callback = undefined ; } if ( callback ) { callback ( ) ; } } }


function _setItemOptions(item, options, callback) {
        item.options = {
            show: {
                transition: this.options.show.transition || this.options.transition,
                animation: this.options.show.animation || this.options.animation
            },
            hide: {
                transition: this.options.hide.transition || this.options.transition,
                animation: this.options.hide.animation || this.options.animation
            },
            transfer: {
                transition: this.options.transfer.transition || this.options.transition,
                items: this.options.transfer.items || {},
                zIndex: this.options.transfer.zIndex,
                fastResize: this.options.transfer.fastResize
            }
        };
        if (options) {
            item.options.show.transition = (options.show ? options.show.transition : undefined) || options.transition || item.options.show.transition;
            if (options && options.show && (options.show.animation !== undefined)) {
                item.options.show.animation = options.show.animation;
            }
            else if (options && (options.animation !== undefined)) {
                item.options.show.animation = options.animation;
            }
            item.options.transfer.transition = (options.transfer ? options.transfer.transition : undefined) || options.transition || item.options.transfer.transition;
            item.options.transfer.items = (options.transfer ? options.transfer.items : undefined) || item.options.transfer.items;
            item.options.transfer.zIndex = (options.transfer && (options.transfer.zIndex !== undefined)) ? options.transfer.zIndex : item.options.transfer.zIndex;
            item.options.transfer.fastResize = (options.transfer && (options.transfer.fastResize !== undefined)) ? options.transfer.fastResize : item.options.transfer.fastResize;
        }
        item.showCallback = function() {
            item.showCallback = undefined;
            item.state = ItemState.VISIBLE;
            _updateState.call(this);
            _endTransferableAnimations.call(this, item);
            item.endSpec = undefined;
            item.startSpec = undefined;
            if (callback) {
                callback();
            }
        }.bind(this);
    }

function _setItemOptions ( item , options , callback ) { item . options = { show : { transition : this . options . show . transition || this . options . transition , animation : this . options . show . animation || this . options . animation } , hide : { transition : this . options . hide . transition || this . options . transition , animation : this . options . hide . animation || this . options . animation } , transfer : { transition : this . options . transfer . transition || this . options . transition , items : this . options . transfer . items || { } , zIndex : this . options . transfer . zIndex , fastResize : this . options . transfer . fastResize } } ; if ( options ) { item . options . show . transition = ( options . show ? options . show . transition : undefined ) || options . transition || item . options . show . transition ; if ( options && options . show && ( options . show . animation !== undefined ) ) { item . options . show . animation = options . show . animation ; } else if ( options && ( options . animation !== undefined ) ) { item . options . show . animation = options . animation ; } item . options . transfer . transition = ( options . transfer ? options . transfer . transition : undefined ) || options . transition || item . options . transfer . transition ; item . options . transfer . items = ( options . transfer ? options . transfer . items : undefined ) || item . options . transfer . items ; item . options . transfer . zIndex = ( options . transfer && ( options . transfer . zIndex !== undefined ) ) ? options . transfer . zIndex : item . options . transfer . zIndex ; item . options . transfer . fastResize = ( options . transfer && ( options . transfer . fastResize !== undefined ) ) ? options . transfer . fastResize : item . options . transfer . fastResize ; } item . showCallback = function ( ) { item . showCallback = undefined ; item . state = ItemState . VISIBLE ; _updateState . call ( this ) ; _endTransferableAnimations . call ( this , item ) ; item . endSpec = undefined ; item . startSpec = undefined ; if ( callback ) { callback ( ) ; } } . bind ( this ) ; }


function _updateState() {
        var prevItem;
        var invalidated = false;
        var hiddenViewCount = 0;
        var i = 0;
        while (i < this._viewStack.length) {
            if (this._viewStack[i].state === ItemState.HIDDEN) {
                hiddenViewCount++;
                for (var j = 0; j < this._viewStack.length; j++) {
                    if ((this._viewStack[j].state !== ItemState.HIDDEN) &&
                        (this._viewStack[j].view === this._viewStack[i].view)) {
                        this._viewStack[i].view = undefined;
                        this._renderables.views.splice(i, 1);
                        this._viewStack.splice(i, 1);
                        i--;
                        hiddenViewCount--;
                        break;
                    }
                }
            }
            i++;
        }
        while (hiddenViewCount > this.options.keepHiddenViewsInDOMCount) {
            this._viewStack[0].view = undefined;
            this._renderables.views.splice(0, 1);
            this._viewStack.splice(0, 1);
            hiddenViewCount--;
        }
        for (i = hiddenViewCount; i < (Math.min(this._viewStack.length - hiddenViewCount, 2) + hiddenViewCount); i++) {
            var item = this._viewStack[i];
            if (item.state === ItemState.QUEUED) {
                if (!prevItem ||
                    (prevItem.state === ItemState.VISIBLE) ||
                    (prevItem.state === ItemState.HIDING)) {
                    if (prevItem && (prevItem.state === ItemState.VISIBLE)) {
                        prevItem.state = ItemState.HIDE;
                        prevItem.wait = item.wait;
                    }
                    item.state = ItemState.SHOW;
                    invalidated = true;
                }
                break;
            }
            else if ((item.state === ItemState.VISIBLE) && item.hide) {
                item.state = ItemState.HIDE;
            }
            if ((item.state === ItemState.SHOW) || (item.state === ItemState.HIDE)) {
                this.layout.reflowLayout();
            }
            prevItem = item;
        }
        if (invalidated) {
            _updateState.call(this);
            this.layout.reflowLayout();
        }
    }

function _updateState ( ) { var prevItem ; var invalidated = false ; var hiddenViewCount = 0 ; var i = 0 ; while ( i < this . _viewStack . length ) { if ( this . _viewStack [ i ] . state === ItemState . HIDDEN ) { hiddenViewCount ++ ; for ( var j = 0 ; j < this . _viewStack . length ; j ++ ) { if ( ( this . _viewStack [ j ] . state !== ItemState . HIDDEN ) && ( this . _viewStack [ j ] . view === this . _viewStack [ i ] . view ) ) { this . _viewStack [ i ] . view = undefined ; this . _renderables . views . splice ( i , 1 ) ; this . _viewStack . splice ( i , 1 ) ; i -- ; hiddenViewCount -- ; break ; } } } i ++ ; } while ( hiddenViewCount > this . options . keepHiddenViewsInDOMCount ) { this . _viewStack [ 0 ] . view = undefined ; this . _renderables . views . splice ( 0 , 1 ) ; this . _viewStack . splice ( 0 , 1 ) ; hiddenViewCount -- ; } for ( i = hiddenViewCount ; i < ( Math . min ( this . _viewStack . length - hiddenViewCount , 2 ) + hiddenViewCount ) ; i ++ ) { var item = this . _viewStack [ i ] ; if ( item . state === ItemState . QUEUED ) { if ( ! prevItem || ( prevItem . state === ItemState . VISIBLE ) || ( prevItem . state === ItemState . HIDING ) ) { if ( prevItem && ( prevItem . state === ItemState . VISIBLE ) ) { prevItem . state = ItemState . HIDE ; prevItem . wait = item . wait ; } item . state = ItemState . SHOW ; invalidated = true ; } break ; } else if ( ( item . state === ItemState . VISIBLE ) && item . hide ) { item . state = ItemState . HIDE ; } if ( ( item . state === ItemState . SHOW ) || ( item . state === ItemState . HIDE ) ) { this . layout . reflowLayout ( ) ; } prevItem = item ; } if ( invalidated ) { _updateState . call ( this ) ; this . layout . reflowLayout ( ) ; } }


function Base(options) {
        this._eventOutput = new EventHandler();
        this._pool = [];
        EventHandler.setOutputHandler(this, this._eventOutput);
        if (options) {
            for (var key in options) {
                this[key] = options[key];
            }
        }
    }

function Base ( options ) { this . _eventOutput = new EventHandler ( ) ; this . _pool = [ ] ; EventHandler . setOutputHandler ( this , this . _eventOutput ) ; if ( options ) { for ( var key in options ) { this [ key ] = options [ key ] ; } } }


function _getDateFromScrollWheels() {
        var date = new Date(this._date);
        for (var i = 0; i < this.scrollWheels.length; i++) {
            var scrollWheel = this.scrollWheels[i];
            var component = scrollWheel.component;
            var item = scrollWheel.scrollController.getFirstVisibleItem();
            if (item && item.renderNode) {
                component.setComponent(date, component.getComponent(item.renderNode.date));
            }
        }
        return date;
    }

function _getDateFromScrollWheels ( ) { var date = new Date ( this . _date ) ; for ( var i = 0 ; i < this . scrollWheels . length ; i ++ ) { var scrollWheel = this . scrollWheels [ i ] ; var component = scrollWheel . component ; var item = scrollWheel . scrollController . getFirstVisibleItem ( ) ; if ( item && item . renderNode ) { component . setComponent ( date , component . getComponent ( item . renderNode . date ) ) ; } } return date ; }

Gets the selected date from all the scroll-wheels.

Gets the selected date from all the scroll - wheels .


function _createLayout() {
        this.container = new ContainerSurface(
            this.options.container
        );
        this.container.setClasses(this.classes);
        this.layout = new LayoutController({
            layout: ProportionalLayout,
            layoutOptions: {
                ratios: []
            },
            direction: Utility.Direction.X
        });
        this.container.add(this.layout);
        this.add(this.container);
    }

function _createLayout ( ) { this . container = new ContainerSurface ( this . options . container ) ; this . container . setClasses ( this . classes ) ; this . layout = new LayoutController ( { layout : ProportionalLayout , layoutOptions : { ratios : [ ] } , direction : Utility . Direction . X } ) ; this . container . add ( this . layout ) ; this . add ( this . container ) ; }


function _clickItem(scrollWheel, event) {
        if (scrollWheel && event && event.target) {
            scrollWheel.scrollController.goToRenderNode(event.target);
        }
    }

function _clickItem ( scrollWheel , event ) { if ( scrollWheel && event && event . target ) { scrollWheel . scrollController . goToRenderNode ( event . target ) ; } }

Called whenever an item is clicked, causes the scrollwheel to scroll to that item.

Called whenever an item is clicked causes the scrollwheel to scroll to that item .


function _createOverlay() {
        this.overlay = new LayoutController({
            layout: OverlayLayout,
            layoutOptions: {
                itemSize: this.options.wheelLayout.itemSize
            },
            dataSource: this._overlayRenderables
        });
        this.add(this.overlay);
    }

function _createOverlay ( ) { this . overlay = new LayoutController ( { layout : OverlayLayout , layoutOptions : { itemSize : this . options . wheelLayout . itemSize } , dataSource : this . _overlayRenderables } ) ; this . add ( this . overlay ) ; }


function _setSelectedItem(index) {
        if (index !== this._selectedItemIndex) {
            var oldIndex = this._selectedItemIndex;
            this._selectedItemIndex = index;
            this.layout.setLayoutOptions({
                selectedItemIndex: index
            });
            if ((oldIndex >= 0) && this._renderables.items[oldIndex].removeClass){
                this._renderables.items[oldIndex].removeClass('selected');
            }
            if (this._renderables.items[index].addClass) {
                this._renderables.items[index].addClass('selected');
            }
            if (oldIndex >= 0) {
                this._eventOutput.emit('tabchange', {
                    target: this,
                    index: index,
                    oldIndex: oldIndex,
                    item: this._renderables.items[index],
                    oldItem: ((oldIndex >= 0) && (oldIndex < this._renderables.items.length)) ? this._renderables.items[oldIndex] : undefined
                });
            }
        }
    }

function _setSelectedItem ( index ) { if ( index !== this . _selectedItemIndex ) { var oldIndex = this . _selectedItemIndex ; this . _selectedItemIndex = index ; this . layout . setLayoutOptions ( { selectedItemIndex : index } ) ; if ( ( oldIndex >= 0 ) && this . _renderables . items [ oldIndex ] . removeClass ) { this . _renderables . items [ oldIndex ] . removeClass ( 'selected' ) ; } if ( this . _renderables . items [ index ] . addClass ) { this . _renderables . items [ index ] . addClass ( 'selected' ) ; } if ( oldIndex >= 0 ) { this . _eventOutput . emit ( 'tabchange' , { target : this , index : index , oldIndex : oldIndex , item : this . _renderables . items [ index ] , oldItem : ( ( oldIndex >= 0 ) && ( oldIndex < this . _renderables . items . length ) ) ? this . _renderables . items [ oldIndex ] : undefined } ) ; } } }

Helper function that is called whenever a new item is selected


function _setListeners() {
        this.tabBar.on('tabchange', function(event) {
            _updateView.call(this, event);
            this._eventOutput.emit('tabchange', {
                target: this,
                index: event.index,
                oldIndex: event.oldIndex,
                item: this._items[event.index],
                oldItem: ((event.oldIndex >= 0) && (event.oldIndex < this._items.length)) ? this._items[event.oldIndex] : undefined
            });
        }.bind(this));
    }

function _setListeners ( ) { this . tabBar . on ( 'tabchange' , function ( event ) { _updateView . call ( this , event ) ; this . _eventOutput . emit ( 'tabchange' , { target : this , index : event . index , oldIndex : event . oldIndex , item : this . _items [ event . index ] , oldItem : ( ( event . oldIndex >= 0 ) && ( event . oldIndex < this . _items . length ) ) ? this . _items [ event . oldIndex ] : undefined } ) ; } . bind ( this ) ) ; }


function _updateView(event) {
        var index = this.tabBar.getSelectedItemIndex();
        this.animationController.halt();
        if (index >= 0) {
            this.animationController.show(this._items[index].view);
        }
        else {
            this.animationController.hide();
        }
    }

function _updateView ( event ) { var index = this . tabBar . getSelectedItemIndex ( ) ; this . animationController . halt ( ) ; if ( index >= 0 ) { this . animationController . show ( this . _items [ index ] . view ) ; } else { this . animationController . hide ( ) ; } }

Updates the view-container with the selected view.

Updates the view - container with the selected view .


function _resolveNodeSize(node) {
        var localItemSize = itemSize;
        if (getItemSize) {
            localItemSize = getItemSize(node.renderNode, size);
        }
        if ((localItemSize[0] === true) || (localItemSize[1] === true)) {
            var result = context.resolveSize(node, size);
            if (localItemSize[0] !== true) {
                result[0] = itemSize[0];
            }
            if (localItemSize[1] !== true) {
                result[1] = itemSize[1];
            }
            return result;
        }
        else {
            return localItemSize;
        }
    }

function _resolveNodeSize ( node ) { var localItemSize = itemSize ; if ( getItemSize ) { localItemSize = getItemSize ( node . renderNode , size ) ; } if ( ( localItemSize [ 0 ] === true ) || ( localItemSize [ 1 ] === true ) ) { var result = context . resolveSize ( node , size ) ; if ( localItemSize [ 0 ] !== true ) { result [ 0 ] = itemSize [ 0 ] ; } if ( localItemSize [ 1 ] !== true ) { result [ 1 ] = itemSize [ 1 ] ; } return result ; } else { return localItemSize ; } }

Helper function to resolving the size of a node.

Helper function to resolving the size of a node .


function FontLayout(context, options) {

        // Prepare
        size = context.size;
        direction = context.direction;
        text = options.text || 'KLMNOPQRSTUVW';
        spacing = (options.spacing === undefined) ? 10 : options.spacing;
        offset = 0;
        set.size[0] = options.segmentSize ? options.segmentSize[0] : 20;
        set.size[1] = options.segmentSize ? options.segmentSize[1] : 4;

        for (var i = 0; i < text.length; i++) {
            var charSegments = charMap[text.charAt(i)] || charMap['?'];
            for (var j = 0; j < 8; j++) {
                if (charSegments & (1 << j)) {
                    node = context.next();
                    if (!node) {
                        return;
                    }
                    var segment = segmentMap[j];
                    set.translate[0] = (set.size[0] * segment[0]) + (segment[3] * set.size[1]);
                    set.translate[1] = (set.size[0] * segment[1]) + (segment[4] * set.size[1]);
                    set.translate[direction] += offset;
                    set.rotate[2] = (segment[2] * Math.PI * 2);
                    set.scrollLength = i ? 0 : (direction ? (set.size[0] * 2) : set.size[1]);
                    if ((j === 0) && (i < (text.length - 1))) {
                        set.scrollLength += spacing;
                    }
                    context.set(node, set);
                }
            }

            // Advance offset for next character
            offset += (direction ? (set.size[0] * 2) : set.size[0]) + spacing;
        }
    }

function
FontLayout
(
context
,
options
)
{
// Prepare
size
=
context
.
size
;
direction
=
context
.
direction
;
text
=
options
.
text
||
'KLMNOPQRSTUVW'
;
spacing
=
(
options
.
spacing
===
undefined
)
10
:
options
.
spacing
;
offset
=
0
;
set
.
size
[
0
]
=
options
.
segmentSize
options
.
segmentSize
[
0
]
:
20
;
set
.
size
[
1
]
=
options
.
segmentSize
options
.
segmentSize
[
1
]
:
4
;
for
(
var
i
=
0
;
i
<
text
.
length
;
i
++
)
{
var
charSegments
=
charMap
[
text
.
charAt
(
i
)
]
||
charMap
[
'?'
]
;
for
(
var
j
=
0
;
j
<
8
;
j
++
)
{
if
(
charSegments
&
(
1
<<
j
)
)
{
node
=
context
.
next
(
)
;
if
(
!
node
)
{
return
;
}
var
segment
=
segmentMap
[
j
]
;
set
.
translate
[
0
]
=
(
set
.
size
[
0
]
*
segment
[
0
]
)
+
(
segment
[
3
]
*
set
.
size
[
1
]
)
;
set
.
translate
[
1
]
=
(
set
.
size
[
0
]
*
segment
[
1
]
)
+
(
segment
[
4
]
*
set
.
size
[
1
]
)
;
set
.
translate
[
direction
]
+=
offset
;
set
.
rotate
[
2
]
=
(
segment
[
2
]
*
Math
.
PI
*
2
)
;
set
.
scrollLength
=
i
0
:
(
direction
(
set
.
size
[
0
]
*
2
)
:
set
.
size
[
1
]
)
;
if
(
(
j
===
0
)
&&
(
i
<
(
text
.
length
1
)
)
)
{
set
.
scrollLength
+=
spacing
;
}
context
.
set
(
node
,
set
)
;
}
}
// Advance offset for next character
offset
+=
(
direction
(
set
.
size
[
0
]
*
2
)
:
set
.
size
[
0
]
)
+
spacing
;
}
}


function removeFromExports(exports, dependencies = {}) {
    const localExports = { ...exports };
    Object.keys(localExports).forEach((exported) => {
        if (dependencies[exported]) {
            delete localExports[exported];
        }
    });
    return localExports;
}

function removeFromExports ( exports , dependencies = { } ) { const localExports = { ... exports } ; Object . keys ( localExports ) . forEach ( ( exported ) => { if ( dependencies [ exported ] ) { delete localExports [ exported ] ; } } ) ; return localExports ; }

Removes dependencies that exists in the package.json for the extension in question

Removes dependencies that exists in the package . json for the extension in question


function encode (payload) {
    var checksum = checksumFn(payload)

    return base58.encode(Buffer.concat([
      payload,
      checksum
    ], payload.length + 4))
  }

function encode ( payload ) { var checksum = checksumFn ( payload ) return base58 . encode ( Buffer . concat ( [ payload , checksum ] , payload . length + 4 ) ) }

Encode a buffer as a base58-check encoded string

Encode a buffer as a base58 - check encoded string


function main() {
  return new Promise((resolve) => {
    fsx.readFile(path.resolve(__dirname, '../package.json'), 'utf8', (err, data) => {
      if (err) {
        throw err;
      }

      resolve(data);
    });
  })
    .then((data) => JSON.parse(data))
    .then((packageData) => {
      const {
        author,
        version,
        description,
        keywords,
        repository,
        license,
        bugs,
        homepage,
        peerDependencies,
        dependencies,
      } = packageData;

      const minimalPackage = {
        name: '@boundlessgeo/sdk',
        author,
        version,
        description,
        keywords,
        repository,
        license,
        bugs,
        homepage,
        peerDependencies,
        dependencies,
      };

      return new Promise((resolve) => {
        const buildPath = path.resolve(__dirname, '../dist/package.json');
        const data = JSON.stringify(minimalPackage, null, 2);
        fsx.writeFile(buildPath, data, (err) => {
          if (err) {
            throw (err);
          }
          process.stdout.write(`Created package.json in ${buildPath}\n`);
          resolve();
        });
      });
    });
}

function main ( ) { return new Promise ( ( resolve ) => { fsx . readFile ( path . resolve ( __dirname , '../package.json' ) , 'utf8' , ( err , data ) => { if ( err ) { throw err ; } resolve ( data ) ; } ) ; } ) . then ( ( data ) => JSON . parse ( data ) ) . then ( ( packageData ) => { const { author , version , description , keywords , repository , license , bugs , homepage , peerDependencies , dependencies , } = packageData ; const minimalPackage = { name : '@boundlessgeo/sdk' , author , version , description , keywords , repository , license , bugs , homepage , peerDependencies , dependencies , } ; return new Promise ( ( resolve ) => { const buildPath = path . resolve ( __dirname , '../dist/package.json' ) ; const data = JSON . stringify ( minimalPackage , null , 2 ) ; fsx . writeFile ( buildPath , data , ( err ) => { if ( err ) { throw ( err ) ; } process . stdout . write ( ` ${ buildPath } \n ` ) ; resolve ( ) ; } ) ; } ) ; } ) ; }

Make a reduced version of the package.json file
that is more appropriate for distribution.

Make a reduced version of the package . json file that is more appropriate for distribution .


function authTileLoader(fetchOptions) {
  return function(tile, src) {
    fetch(src, fetchOptions)
      .then(r => r.blob())
      .then((imgData) => {
        tile.getImage().src = URL.createObjectURL(imgData);
      })
      .catch(() => {
        console.error('Error fetchimg image at:', src);
      });
  };
}

function
authTileLoader
(
fetchOptions
)
{
return
function
(
tile
,
src
)
{
fetch
(
src
,
fetchOptions
)
.
then
(
r
=>
r
.
blob
(
)
)
.
then
(
(
imgData
)
=>
{
tile
.
getImage
(
)
.
src
=
URL
.
createObjectURL
(
imgData
)
;
}
)
.
catch
(
(
)
=>
{
console
.
error
(
'Error fetchimg image at:'
,
src
)
;
}
)
;
}
;
}

Load a tile with full fetchOptions.

This is only used when the Authorization header has been set
in the fetchOptions.

@param {Object} fetchOptions Options to use for fetch calls.

@returns {Function} Tile loading function which uses fetch.


function authVectorTileLoader(fetchOptions) {
  return function(tile, url) {
    const loader = () => {
      fetch(url, fetchOptions)
        .then(r => r.arrayBuffer())
        .then((source) => {
          const format = tile.getFormat();
          tile.setProjection(format.readProjection(source));
          tile.setFeatures(format.readFeatures(source));
          tile.setExtent(format.getLastExtent());
        })
        .catch((err) => {
          tile.onError();
        });
    };

    tile.setLoader(loader);
  };
}

function authVectorTileLoader ( fetchOptions ) { return function ( tile , url ) { const loader = ( ) => { fetch ( url , fetchOptions ) . then ( r => r . arrayBuffer ( ) ) . then ( ( source ) => { const format = tile . getFormat ( ) ; tile . setProjection ( format . readProjection ( source ) ) ; tile . setFeatures ( format . readFeatures ( source ) ) ; tile . setExtent ( format . getLastExtent ( ) ) ; } ) . catch ( ( err ) => { tile . onError ( ) ; } ) ; } ; tile . setLoader ( loader ) ; } ; }

Load a vector tile with full fetchOptions
This is only used when the Authorization header has been set
in the fetchOptions.

@param {Object} fetchOptions Options to use for fetch calls.

@returns {Function} Tile loading function which uses fetch.

Load a vector tile with full fetchOptions This is only used when the Authorization header has been set in the fetchOptions .


function configureGeojsonSource(glSource, mapView, baseUrl, wrapX, fetchOptions) {
  const use_bbox = (typeof glSource.data === 'string' && glSource.data.indexOf(BBOX_STRING) >= 0);
  const vector_src = new VectorSource({
    strategy: use_bbox ? bboxStrategy : allStrategy,
    loader: getLoaderFunction(glSource, mapView.getProjection(), baseUrl, fetchOptions),
    useSpatialIndex: true,
    wrapX: wrapX,
  });

  // GeoJson sources can be clustered but OpenLayers
  // uses a special source type for that. This handles the
  // "switch" of source-class.
  let new_src = vector_src;
  if (glSource.cluster) {
    new_src = new ClusterSource({
      source: vector_src,
      // default the distance to 50 as that's what
      //  is specified by Mapbox.
      distance: glSource.clusterRadius ? glSource.clusterRadius : 50,
    });
  }

  // seed the vector source with the first update
  //  before returning it.
  updateGeojsonSource(new_src, glSource, mapView, baseUrl, fetchOptions);
  return new_src;
}

Create a vector source based on a
Mapbox GL styles definition.

@param {Object} glSource A Mapbox GL styles defintiion of the source.
@param {Object} mapView The OpenLayers map view.
@param {string} baseUrl The mapbox base url.
@param {boolean} wrapX Should we wrap the world?
@param {Object} fetchOptions Options to use for fetch calls.

@returns {Object} ol.source.vector instance.

Create a vector source based on a Mapbox GL styles definition .


function hydrateLayerGroup(layersDef, layerGroup) {
  const hydrated_group = [];
  for (let i = 0, ii = layerGroup.length; i < ii; i++) {
    // hydrateLayer checks for "ref"
    hydrated_group.push(hydrateLayer(layersDef, layerGroup[i]));
  }
  return hydrated_group;
}

function
hydrateLayerGroup
(
layersDef
,
layerGroup
)
{
const
hydrated_group
=
[
]
;
for
(
let
i
=
0
,
ii
=
layerGroup
.
length
;
i
<
ii
;
i
++
)
{
// hydrateLayer checks for "ref"
hydrated_group
.
push
(
hydrateLayer
(
layersDef
,
layerGroup
[
i
]
)
)
;
}
return
hydrated_group
;
}

Hydrate a layer group
Normalizes all the ref layers in a group.

@param {Object[]} layersDef All layers defined in the Mapbox GL stylesheet.
@param {Object[]} layerGroup Subset of layers to be rendered as a group.

@returns {Object[]} An array with the ref layers normalized.

Hydrate a layer group Normalizes all the ref layers in a group .


function incrementVersion(metadata, version) {
  const new_metadata = Object.assign({}, metadata);
  new_metadata[version] = getVersion(metadata, version) + 1;
  return {
    metadata: new_metadata,
  };
}

function incrementVersion ( metadata , version ) { const new_metadata = Object . assign ( { } , metadata ) ; new_metadata [ version ] = getVersion ( metadata , version ) + 1 ; return { metadata : new_metadata , } ; }

Increments metadata object version numbers.

@param {Object} metadata The state.map.metadata.
@param {string} version The metadata object to be incremented.

@returns {Object} The new state.map.metadata object with the incremented version.

Increments metadata object version numbers .


function placeLayer(state, layer, targetId) {
  const new_layers = state.layers.slice();
  const idx1 = getLayerIndexById(new_layers, layer.id);
  const idx2 = getLayerIndexById(new_layers, targetId);
  if (idx1 !== -1) {
    new_layers.splice(idx1, 1);
  }
  const newIndex = (targetId && idx2 !== -1) ? idx2 : new_layers.length;
  new_layers.splice(newIndex, 0, layer);
  return Object.assign({}, state, {
    layers: new_layers,
  }, incrementVersion(state.metadata, LAYER_VERSION_KEY));
}

function placeLayer ( state , layer , targetId ) { const new_layers = state . layers . slice ( ) ; const idx1 = getLayerIndexById ( new_layers , layer . id ) ; const idx2 = getLayerIndexById ( new_layers , targetId ) ; if ( idx1 !== - 1 ) { new_layers . splice ( idx1 , 1 ) ; } const newIndex = ( targetId && idx2 !== - 1 ) ? idx2 : new_layers . length ; new_layers . splice ( newIndex , 0 , layer ) ; return Object . assign ( { } , state , { layers : new_layers , } , incrementVersion ( state . metadata , LAYER_VERSION_KEY ) ) ; }

Move a layer in the layers list.

@param {Object} state The redux state.
@param {Object} layer The layer object to be moved.
@param {string} targetId The id of the layer
at the position where layer will be moved.

@returns {Object} The new state object.


function moveGroup(state, action) {
  const place_at = getLayerIndexById(state.layers, action.placeAt);
  const n_layers = state.layers.length;

  // sanity check the new index.
  if (place_at < 0 || place_at > n_layers) {
    return state;
  }

  // find the starting and ending points of the group
  let group_start = null;
  let group_end = null;
  for (let i = 0, ii = n_layers; i < ii; i++) {
    const group = getGroup(state.layers[i]);
    if (group === action.group) {
      if (group_start === null || i < group_start) {
        group_start = i;
      }
      if (group_end === null || i > group_end) {
        group_end = i;
      }
    }
  }

  // get the real index of the next spot for the group,
  // if the placeAt index is mid group then place_at should
  // be the index of the FIRST member of that group.
  let place_start = place_at;
  const place_group = getGroup(state.layers[place_at]);
  const place_ahead = (place_at > group_start);

  // when placing a group before or after another group
  // the bounds of the target group needs to be found and the
  // appropriate index chosen based on the direction of placement.
  if (place_group) {
    let new_place = -1;
    if (place_ahead) {
      for (let i = n_layers - 1; i >= 0 && new_place < 0; i--) {
        if (getGroup(state.layers[i]) === place_group) {
          new_place = i;
        }
      }
    } else {
      for (let i = 0, ii = n_layers; i < ii && new_place < 0; i++) {
        if (getGroup(state.layers[i]) === place_group) {
          new_place = i;
        }
      }
    }
    place_start = new_place;
  }

  // build a new array for the layers.
  let new_layers = [];

  // have the group layers ready to concat.
  const group_layers = state.layers.slice(group_start, group_end + 1);

  for (let i = 0, ii = n_layers; i < ii; i++) {
    const layer = state.layers[i];
    const in_group = (getGroup(layer) === action.group);

    if (place_ahead && !in_group) {
      new_layers.push(layer);
    }
    if (i === place_start) {
      new_layers = new_layers.concat(group_layers);
    }
    if (!place_ahead && !in_group) {
      new_layers.push(layer);
    }
  }

  return Object.assign({}, state, {
    layers: new_layers,
  }, incrementVersion(state.metadata, LAYER_VERSION_KEY));
}

Move a group relative to another group.

@param {Object} state Current state.
@param {Object} action Action to handle.

@returns {Object} The new state.

Move a group relative to another group .


function changeData(state, sourceName, data) {
  const source = state.sources[sourceName];
  if (!source) {
    return state;
  }
  const src_mixin = {};

  // update the individual source.
  src_mixin[sourceName] = Object.assign({}, source, {
    data,
  });

  // kick back the new state.
  return Object.assign({}, state, {
    sources: Object.assign({}, state.sources, src_mixin),
  }, incrementVersion(state.metadata, dataVersionKey(sourceName)));
}

function
changeData
(
state
,
sourceName
,
data
)
{
const
source
=
state
.
sources
[
sourceName
]
;
if
(
!
source
)
{
return
state
;
}
const
src_mixin
=
{
}
;
// update the individual source.
src_mixin
[
sourceName
]
=
Object
.
assign
(
{
}
,
source
,
{
data
,
}
)
;
// kick back the new state.
return
Object
.
assign
(
{
}
,
state
,
{
sources
:
Object
.
assign
(
{
}
,
state
.
sources
,
src_mixin
)
,
}
,
incrementVersion
(
state
.
metadata
,
dataVersionKey
(
sourceName
)
)
)
;
}

Creates a new state with the data for a
source changed to the contents of data.

@param {Object} state The redux state.
@param {string} sourceName The name of the source to be changed.
@param {Object[]} data The list of features to be added to the source.

@returns {Object} The new redux state.

Creates a new state with the data for a source changed to the contents of data .


function mapDispatchToProps(dispatch) {
  return {
    moveSlide: (count) => {
      dispatch(bookmarkAction.moveSlide(count));
    },
    zoomTo: (coords, zoomLevel) => {
      dispatch(mapActions.setView(coords, zoomLevel));
    }
  };
}

function mapDispatchToProps ( dispatch ) { return { moveSlide : ( count ) => { dispatch ( bookmarkAction . moveSlide ( count ) ) ; } , zoomTo : ( coords , zoomLevel ) => { dispatch ( mapActions . setView ( coords , zoomLevel ) ) ; } } ; }

Need the moveSlide function from bookmark reducer Need setView function from map reducer


function addPoints(sourceName, n_points = 10) {
  for (let i = 0; i < n_points; i++) {
    // the feature is a normal GeoJSON feature definition
    store.dispatch(mapActions.addFeatures(sourceName, [{
      type: 'Feature',
      properties: {
        id: `point${i}`,
        title: 'Random Point',
      },
      geometry: {
        type: 'Point',
        // this generates a point somewhere on the planet, unbounded.
        coordinates: [(Math.random() * 360) - 180, (Math.random() * 180) - 90],
      },
    }]));
  }
}

Handy all around function for adding a random
set of points to the map.
@param {string} sourceName The name of the source to add to.
@param {number} n_points Number of random points to add.

Handy all around function for adding a random set of points to the map .


function stripZeros(aInput) {
  var a = aInput; // eslint-disable-line
  var first = a[0]; // eslint-disable-line
  while (a.length > 0 && first.toString() === '0') {
    a = a.slice(1);
    first = a[0];
  }
  return a;
}

function
stripZeros
(
aInput
)
{
var
a
=
aInput
;
// eslint-disable-line
var
first
=
a
[
0
]
;
// eslint-disable-line
while
(
a
.
length
>
0
&&
first
.
toString
(
)
===
'0'
)
{
a
=
a
.
slice
(
1
)
;
first
=
a
[
0
]
;
}
return
a
;
}


function decodeParams(names, types, data, useNumberedParams = true) {
  // Names is optional, so shift over all the parameters if not provided
  if (arguments.length < 3) {
    data = types;
    types = names;
    names = [];
  }

  data = utils.hexOrBuffer(data);
  var values = new Result();

  var offset = 0;
  types.forEach(function(type, index) {
    var coder = getParamCoder(type);

    if (coder.dynamic) {
      var dynamicOffset = uint256Coder.decode(data, offset);
      var result = coder.decode(data, dynamicOffset.value.toNumber());
      offset += dynamicOffset.consumed;
    } else {
      var result = coder.decode(data, offset);
      offset += result.consumed;
    }

    if (useNumberedParams) {
      values[index] = result.value;
    }

    if (names[index]) {
      values[names[index]] = result.value;
    }
  });
  return values;
}

decode bytecode data from output names and types


function encodeSignature(method) {
  const signature = `${method.name}(${utils.getKeys(method.inputs, 'type').join(',')})`;
  const signatureEncoded = `0x${(new Buffer(utils.keccak256(signature), 'hex')).slice(0, 4).toString('hex')}`;

  return signatureEncoded;
}

function encodeSignature ( method ) { const signature = ` ${ method . name } ${ utils . getKeys ( method . inputs , 'type' ) . join ( ',' ) } ` ; const signatureEncoded = ` ${ ( new Buffer ( utils . keccak256 ( signature ) , 'hex' ) ) . slice ( 0 , 4 ) . toString ( 'hex' ) } ` ; return signatureEncoded ; }

create an encoded method signature from an ABI object


function encodeMethod(method, values) {
  const paramsEncoded = encodeParams(utils.getKeys(method.inputs, 'type'), values).substring(2);

  return `${encodeSignature(method)}${paramsEncoded}`;
}

function encodeMethod ( method , values ) { const paramsEncoded = encodeParams ( utils . getKeys ( method . inputs , 'type' ) , values ) . substring ( 2 ) ; return ` ${ encodeSignature ( method ) } ${ paramsEncoded } ` ; }

encode method ABI object with values in an array, output bytecode

encode method ABI object with values in an array output bytecode


function decodeLogItem(eventObject, log, useNumberedParams = true) {
  if (eventObject && log.topics[0] === eventSignature(eventObject)) {
    return decodeEvent(eventObject, log.data, log.topics, useNumberedParams)
  }
}

function decodeLogItem ( eventObject , log , useNumberedParams = true ) { if ( eventObject && log . topics [ 0 ] === eventSignature ( eventObject ) ) { return decodeEvent ( eventObject , log . data , log . topics , useNumberedParams ) } }

Decode a specific log item with a specific event abi


function logDecoder(abi, useNumberedParams = true) {
  const eventMap = {}
  abi.filter(item => item.type === 'event').map(item => {
    eventMap[eventSignature(item)] = item
  })
  return function(logItems) {
    return logItems.map(log => decodeLogItem(eventMap[log.topics[0]], log, useNumberedParams)).filter(i => i)
  }
}

function logDecoder ( abi , useNumberedParams = true ) { const eventMap = { } abi . filter ( item => item . type === 'event' ) . map ( item => { eventMap [ eventSignature ( item ) ] = item } ) return function ( logItems ) { return logItems . map ( log => decodeLogItem ( eventMap [ log . topics [ 0 ] ] , log , useNumberedParams ) ) . filter ( i => i ) } }

Create a decoder for all events defined in an abi. It returns a function which is called on an array of log entries such as received from getLogs or getTransactionReceipt and parses any matching log entries

Create a decoder for all events defined in an abi . It returns a function which is called on an array of log entries such as received from getLogs or getTransactionReceipt and parses any matching log entries


function loader(content) {
    const { addDependency, resource, resourcePath } = this;

    // Get callback because the SVG is going to be optimized and that is an async operation
    const callback = this.async();

    // Parse the loader query and apply the default values in case no values are provided
    const { iconName, publicPath, sprite, svgoOptions } = Object.assign({}, DEFAULT_LOADER_OPTIONS, loaderUtils.getOptions(this));

    // Add the icon as a dependency
    addDependency(resourcePath);

    // Start optimizing the SVG file
    imagemin
        .buffer(content, {
            plugins: [
                imageminSvgo(svgoOptions),
            ],
        })
        .then((content) => {

            // Create the icon name with the hash of the optimized content
            const name = loaderUtils.interpolateName(this, iconName, { content });

            // Register the icon using its resource path with query as id
            // so that tools like: `svg-transform-loader` can be used in combination with this loader.
            const icon = sprite.addIcon(resource, name, content.toString());

            // Export the icon as a metadata object that contains urls to be used on an <img/> in HTML or url() in CSS
            // If the outputted file is not hashed and to support hot module reload, we must force the browser
            // to re-download the sprite on subsequent compilations
            // We do this by adding a cache busting on the URL, with the following pattern: img/sprite.svg?icon-abcd#icon-abcd
            // It's important that the cache busting is not included initially so that it plays well with server-side rendering,
            // otherwise many view libraries will complain about mismatches during rehydration (such as React)
            const hasSamePath = sprite.originalResourcePath === sprite.resourcePath;

            setImmediate(() => {
                callback(
                    null,
                    `var publicPath = ${publicPath ? `'${publicPath}'` : '__webpack_public_path__'};
                    var symbolUrl = '${icon.getUrlToSymbol()}';
                    var viewUrl = '${icon.getUrlToView()}';

                    ${process.env.NODE_ENV !== 'production' && hasSamePath ? `
                        var addCacheBust = typeof document !== 'undefined' && document.readyState === 'complete';

                        if (addCacheBust) {
                            symbolUrl = '${icon.getUrlToSymbol(true)}';
                            viewUrl = '${icon.getUrlToView(true)}';
                        }
                    ` : '' }

                    module.exports = {
                        symbol: publicPath + symbolUrl,
                        view: publicPath + viewUrl,
                        viewBox: '${icon.getDocument().getViewBox()}',
                        title: '${icon.getDocument().getTitle()}',
                        toString: function () {
                            return JSON.stringify(this.view);
                        }
                    };`
                );
            });
        })
        .catch((err) => {
            setImmediate(() => callback(err));
        });
}

Applies SVGO on the SVG file in order to optimize its contents and remove unnecessary attributes for the sprite.
Adds the SVG to the given sprite which will then be processed by the plugin.
Generates SVG metadata to be passed to JavaScript and CSS files so that the symbols can be rendered.
@param {Buffer} content - the content of the SVG file.

Applies SVGO on the SVG file in order to optimize its contents and remove unnecessary attributes for the sprite . Adds the SVG to the given sprite which will then be processed by the plugin . Generates SVG metadata to be passed to JavaScript and CSS files so that the symbols can be rendered .


function() {
    var client = redis.client();
    return client.keysAsync('bull:*:id').then(function(keys) {
      return _.map(keys, function(key) {
        return key.slice(5, -3);
      });
    });
  }

function ( ) { var client = redis . client ( ) ; return client . keysAsync ( 'bull:*:id' ) . then ( function ( keys ) { return _ . map ( keys , function ( key ) { return key . slice ( 5 , - 3 ) ; } ) ; } ) ; }

List all queues
@returns {Promise} A promise that resolves to the keys of all queues


function(qName) {
    if (!qName || qName.length === 0) {
      throw new Error('You must specify a queue name.');
    }
    var client = redis.client();
    return client.keysAsync('bull:' + qName + ':*').then(function(keys) {
      if (keys.length) {
        return client.del(keys);
      }
    });
  }

function
(
qName
)
{
if
(
!
qName
||
qName
.
length
===
0
)
{
throw
new
Error
(
'You must specify a queue name.'
)
;
}
var
client
=
redis
.
client
(
)
;
return
client
.
keysAsync
(
'bull:'
+
qName
+
':*'
)
.
then
(
function
(
keys
)
{
if
(
keys
.
length
)
{
return
client
.
del
(
keys
)
;
}
}
)
;
}

Delete all data of a queue
@param {String} qName Queue name
@returns {Promise} A promise when all data of the queue is deleted


function(qName) {
    if (this._q.name !== qName) {
      this._q.name = qName;
      var queueOpts = {
        redis: {
          host: redis.redisOpts.host,
          port: redis.redisOpts.port,
          DB: redis.redisOpts.db,
          opts: {
            auth_pass: redis.redisOpts.auth_pass
          }
        }
      };
      this._q.instance = new bull(qName, queueOpts);
    }
    return this._q.instance;
  }

function ( qName ) { if ( this . _q . name !== qName ) { this . _q . name = qName ; var queueOpts = { redis : { host : redis . redisOpts . host , port : redis . redisOpts . port , DB : redis . redisOpts . db , opts : { auth_pass : redis . redisOpts . auth_pass } } } ; this . _q . instance = new bull ( qName , queueOpts ) ; } return this . _q . instance ; }

Get a queue by name
@param {String} qName Queue name
@returns {Object} An instance of the queue


function(qName, id) {
    var q = queue.get(qName);
    return q.getJob(id).then(function(job) {
      if (!job) {
        return job;
      }
      return job.getState().then(function(state) {
        job.state = state;
        return job;
      });
    });
  }

function ( qName , id ) { var q = queue . get ( qName ) ; return q . getJob ( id ) . then ( function ( job ) { if ( ! job ) { return job ; } return job . getState ( ) . then ( function ( state ) { job . state = state ; return job ; } ) ; } ) ; }

Get a job by id
@param {String} qName Queue name
@param {String} id Job id
@returns {Object} The job


function(qName, data, opts) {
    var q = queue.get(qName);
    return q.add(data, opts).then(function(job) {
      if (!job) {
        return job;
      }
      return job.getState().then(function(state) {
        job.state = state;
        return job;
      });
    });
  }

function ( qName , data , opts ) { var q = queue . get ( qName ) ; return q . add ( data , opts ) . then ( function ( job ) { if ( ! job ) { return job ; } return job . getState ( ) . then ( function ( state ) { job . state = state ; return job ; } ) ; } ) ; }

Add a job
@param {String} qName Queue name
@param {Object} data job data
@param {Object} opts job options
@returns {Object} The job


function(qName, id) {
    var q = queue.get(qName);
    return q.getJob(id).then(function(job) {
      return job.remove();
    });
  }

function ( qName , id ) { var q = queue . get ( qName ) ; return q . getJob ( id ) . then ( function ( job ) { return job . remove ( ) ; } ) ; }

Remove a job by id
@param {string} qName Queue name
@param {string} id Job id
@returns {Promise} A promise that resolves when the job is removed from queue


function(qName, type) {
    var client = redis.client();
    var key = 'bull:' + qName + ':' + type;
    if (type === 'wait' || type === 'active') {
      return client.llenAsync(key);
    } else if (type === 'delayed') {
      return client.zcardAsync(key);
    } else if (type === 'completed' || type === 'failed') {
      return client.scardAsync(key);
    }
    throw new Error('You must provide a valid job type.');
  }

function
(
qName
,
type
)
{
var
client
=
redis
.
client
(
)
;
var
key
=
'bull:'
+
qName
+
':'
+
type
;
if
(
type
===
'wait'
||
type
===
'active'
)
{
return
client
.
llenAsync
(
key
)
;
}
else
if
(
type
===
'delayed'
)
{
return
client
.
zcardAsync
(
key
)
;
}
else
if
(
type
===
'completed'
||
type
===
'failed'
)
{
return
client
.
scardAsync
(
key
)
;
}
throw
new
Error
(
'You must provide a valid job type.'
)
;
}

Get the total number of jobs of type
@param {String} qName Queue name
@param {String} type Job type: {wait|active|delayed|completed|failed}
@returns {Number} Total number of jobs


function(qName, type, offset, limit) {
    var q = queue.get(qName);
    if (!(offset >= 0)) {
      offset = 0;
    }
    if (!(limit >= 0)) {
      limit = 30;
    }
    if (type === 'wait' || type === 'active') {
      return q.getJobs(type, 'LIST', offset, offset + limit - 1).then(function(jobs) {
        return Promise.all(_.map(jobs, function(job) {
          if (!job) {
            return null;
          }
          return job.getState().then(function(state) {
            job.state = state;
            return job;
          });
        }));
      });
    } else if (type === 'delayed') {
      return q.getJobs(type, 'ZSET', offset, offset + limit - 1).then(function(jobs) {
        return Promise.all(_.map(jobs, function(job) {
          if (!job) {
            return null;
          }
          return job.getState().then(function(state) {
            job.state = state;
            return job;
          });
        }));
      });
    } else if (type === 'completed' || type === 'failed') {
      var client = redis.client();
      var key = 'bull:' + qName + ':' + type;
      return client.smembersAsync(key).then(function(ids) {
        var _ids = ids.slice(offset, offset + limit);
        return Promise.all(_.map(_ids, function(id) {
          return q.getJob(id).then(function(job) {
            if (!job) {
              return null;
            }
            return job.getState().then(function(state) {
              job.state = state;
              return job;
            });
          });
        }));
      });
    }
    throw new Error('You must provide a valid job type.');
  }

function
(
qName
,
type
,
offset
,
limit
)
{
var
q
=
queue
.
get
(
qName
)
;
if
(
!
(
offset
>=
0
)
)
{
offset
=
0
;
}
if
(
!
(
limit
>=
0
)
)
{
limit
=
30
;
}
if
(
type
===
'wait'
||
type
===
'active'
)
{
return
q
.
getJobs
(
type
,
'LIST'
,
offset
,
offset
+
limit
1
)
.
then
(
function
(
jobs
)
{
return
Promise
.
all
(
_
.
map
(
jobs
,
function
(
job
)
{
if
(
!
job
)
{
return
;
}
return
job
.
getState
(
)
.
then
(
function
(
state
)
{
job
.
state
=
state
;
return
job
;
}
)
;
}
)
)
;
}
)
;
}
else
if
(
type
===
'delayed'
)
{
return
q
.
getJobs
(
type
,
'ZSET'
,
offset
,
offset
+
limit
1
)
.
then
(
function
(
jobs
)
{
return
Promise
.
all
(
_
.
map
(
jobs
,
function
(
job
)
{
if
(
!
job
)
{
return
;
}
return
job
.
getState
(
)
.
then
(
function
(
state
)
{
job
.
state
=
state
;
return
job
;
}
)
;
}
)
)
;
}
)
;
}
else
if
(
type
===
'completed'
||
type
===
'failed'
)
{
var
client
=
redis
.
client
(
)
;
var
key
=
'bull:'
+
qName
+
':'
+
type
;
return
client
.
smembersAsync
(
key
)
.
then
(
function
(
ids
)
{
var
_ids
=
ids
.
slice
(
offset
,
offset
+
limit
)
;
return
Promise
.
all
(
_
.
map
(
_ids
,
function
(
id
)
{
return
q
.
getJob
(
id
)
.
then
(
function
(
job
)
{
if
(
!
job
)
{
return
;
}
return
job
.
getState
(
)
.
then
(
function
(
state
)
{
job
.
state
=
state
;
return
job
;
}
)
;
}
)
;
}
)
)
;
}
)
;
}
throw
new
Error
(
'You must provide a valid job type.'
)
;
}

Fetch a number of jobs of certain type
@param {String} qName Queue name
@param {String} type Job type: {wait|active|delayed|completed|failed}
@param {Number} offset Index offset (optional)
@param {Number} limit Limit of the number of jobs returned (optional)
@returns {Promise} A promise that resolves to an array of jobs


function(opts) {
    this._client = Promise.promisifyAll(redis.createClient(opts));
    if (opts.db) {
      this._client.selectAsync(opts.db);
    }
    this.redisOpts = opts;
  }

function ( opts ) { this . _client = Promise . promisifyAll ( redis . createClient ( opts ) ) ; if ( opts . db ) { this . _client . selectAsync ( opts . db ) ; } this . redisOpts = opts ; }

Initialize redis client
@param {Object} opts Options for creating the redis client


function() {
    var multi = this._client.multi();
    multi.execAsync = Promise.promisify(multi.exec);
    return multi;
  }

function ( ) { var multi = this . _client . multi ( ) ; multi . execAsync = Promise . promisify ( multi . exec ) ; return multi ; }

Get a redis multi interface
@returns {Object} Redis multi interface


function ial(app, opts) {

  /**
   * Lazily creates an i18n.
   *
   * @api public
   */

  Object.defineProperty(app.context, 'i18n', {
    get: function () {
      if (this._i18n) {
        return this._i18n
      }

      const i18n = new I18n(opts)
      i18n.request = this.request
      this._i18n = i18n

      // merge into ctx.state
      this.state.i18n = i18n
      registerMethods(this.state, i18n)

      debug('app.ctx.i18n %j', i18n)
      return i18n
    }
  })

  Object.defineProperty(app.request, 'i18n', {
    get: function () {
      return this.ctx.i18n
    }
  })

  return function i18nMiddleware(ctx, next) {
    ctx.i18n.whitelist.some(key => {
      const customLocaleMethod = typeof key === 'function'
        && ctx.i18n.setLocale(key.apply(ctx))
      if (customLocaleMethod || ctx.i18n[SET_PREFIX + key]()) return true
    })
    return next()
  }
}


function handleGroup(self, group, width, maxColumns) {
  if (group.length === 0) {
    return;
  }
  var minRows = Math.ceil(group.length / maxColumns);
  for (var row = 0; row < minRows; row++) {
    for (var col = 0; col < maxColumns; col++) {
      var idx = row * maxColumns + col;
      if (idx >= group.length) {
        break;
      }
      var item = group[idx];
      self._writeToOutput(item);
      if (col < maxColumns - 1) {
        for (var s = 0; s < width - item.length; s++) {
          self._writeToOutput(' ');
        }
      }
    }
    self._writeToOutput('\r\n');
  }
  self._writeToOutput('\r\n');
}

function
handleGroup
(
self
,
group
,
width
,
maxColumns
)
{
if
(
group
.
length
===
0
)
{
return
;
}
var
minRows
=
Math
.
ceil
(
group
.
length
/
maxColumns
)
;
for
(
var
row
=
0
;
row
<
minRows
;
row
++
)
{
for
(
var
col
=
0
;
col
<
maxColumns
;
col
++
)
{
var
idx
=
row
*
maxColumns
+
col
;
if
(
idx
>=
group
.
length
)
{
break
;
}
var
item
=
group
[
idx
]
;
self
.
_writeToOutput
(
item
)
;
if
(
col
<
maxColumns
1
)
{
for
(
var
s
=
0
;
s
<
width
item
.
length
;
s
++
)
{
self
.
_writeToOutput
(
' '
)
;
}
}
}
self
.
_writeToOutput
(
'\r\n'
)
;
}
self
.
_writeToOutput
(
'\r\n'
)
;
}


function emitKeypressEvents(stream, iface) {
  if (stream[KEYPRESS_DECODER]) return;

  if (StringDecoder === undefined)
    StringDecoder = require('string_decoder').StringDecoder;
  stream[KEYPRESS_DECODER] = new StringDecoder('utf8');

  stream[ESCAPE_DECODER] = emitKeys(stream);
  stream[ESCAPE_DECODER].next();

  const escapeCodeTimeout = () => stream[ESCAPE_DECODER].next('');
  let timeoutId;

  function onData(b) {
    if (stream.listenerCount('keypress') > 0) {
      var r = stream[KEYPRESS_DECODER].write(b);
      if (r) {
        clearTimeout(timeoutId);

        if (iface) {
          iface._sawKeyPress = r.length === 1;
        }

        for (var i = 0; i < r.length; i++) {
          if (r[i] === '\t' && typeof r[i + 1] === 'string' && iface) {
            iface.isCompletionEnabled = false;
          }

          try {
            stream[ESCAPE_DECODER].next(r[i]);
            // Escape letter at the tail position
            if (r[i] === kEscape && i + 1 === r.length) {
              timeoutId = setTimeout(
                escapeCodeTimeout,
                iface ? iface.escapeCodeTimeout : ESCAPE_CODE_TIMEOUT
              );
            }
          } catch (err) {
            // If the generator throws (it could happen in the `keypress`
            // event), we need to restart it.
            stream[ESCAPE_DECODER] = emitKeys(stream);
            stream[ESCAPE_DECODER].next();
            throw err;
          } finally {
            if (iface) {
              iface.isCompletionEnabled = true;
            }
          }
        }
      }
    } else {
      // Nobody's watching anyway
      stream.removeListener('data', onData);
      stream.on('newListener', onNewListener);
    }
  }

  function onNewListener(event) {
    if (event === 'keypress') {
      stream.on('data', onData);
      stream.removeListener('newListener', onNewListener);
    }
  }

  if (stream.listenerCount('keypress') > 0) {
    stream.on('data', onData);
  } else {
    stream.on('newListener', onNewListener);
  }
}

accepts a readable Stream instance and makes it emit "keypress" events

accepts a readable Stream instance and makes it emit keypress events


function cursorTo(stream, x, y) {
  if (stream === null || stream === undefined)
    return;

  if (typeof x !== 'number' && typeof y !== 'number')
    return;

  if (typeof x !== 'number')
    throw new Error('ERR_INVALID_CURSOR_POS');

  if (typeof y !== 'number') {
    stream.write(CSI`${x + 1}G`);
  } else {
    stream.write(CSI`${y + 1};${x + 1}H`);
  }
}

function cursorTo ( stream , x , y ) { if ( stream === null || stream === undefined ) return ; if ( typeof x !== 'number' && typeof y !== 'number' ) return ; if ( typeof x !== 'number' ) throw new Error ( 'ERR_INVALID_CURSOR_POS' ) ; if ( typeof y !== 'number' ) { stream . write ( CSI ` ${ x + 1 } ` ) ; } else { stream . write ( CSI ` ${ y + 1 } ${ x + 1 } ` ) ; } }

moves the cursor to the x and y coordinate on the given stream


function moveCursor(stream, dx, dy) {
  if (stream === null || stream === undefined)
    return;

  if (dx < 0) {
    stream.write(CSI`${-dx}D`);
  } else if (dx > 0) {
    stream.write(CSI`${dx}C`);
  }

  if (dy < 0) {
    stream.write(CSI`${-dy}A`);
  } else if (dy > 0) {
    stream.write(CSI`${dy}B`);
  }
}

function moveCursor ( stream , dx , dy ) { if ( stream === null || stream === undefined ) return ; if ( dx < 0 ) { stream . write ( CSI ` ${ - dx } ` ) ; } else if ( dx > 0 ) { stream . write ( CSI ` ${ dx } ` ) ; } if ( dy < 0 ) { stream . write ( CSI ` ${ - dy } ` ) ; } else if ( dy > 0 ) { stream . write ( CSI ` ${ dy } ` ) ; } }

moves the cursor relative to its current location


function toCompute(value) {
	if(value) {

		if(value.isComputed) {
			return value;
		}
		if(value.compute) {
			return value.compute;
		} else {
			return makeComputeLike(value);
		}
	}
	return value;
}

function toCompute ( value ) { if ( value ) { if ( value . isComputed ) { return value ; } if ( value . compute ) { return value . compute ; } else { return makeComputeLike ( value ) ; } } return value ; }

try to make it a compute no matter what.  This is useful for ~ operator.

try to make it a compute no matter what . This is useful for ~ operator .


function HelperOptions(scope, nodeList, exprData, stringOnly) {
	this.metadata = { rendered: false };
	this.stringOnly = stringOnly;
	this.scope = scope;
	this.nodeList = nodeList;
	this.exprData = exprData;
}

function HelperOptions ( scope , nodeList , exprData , stringOnly ) { this . metadata = { rendered : false } ; this . stringOnly = stringOnly ; this . scope = scope ; this . nodeList = nodeList ; this . exprData = exprData ; }

Lazily lookup the context only if it's needed.

Lazily lookup the context only if it s needed .


function valueShouldBeInsertedAsHTML(value) {
	return value !== null && typeof value === "object" && (
		typeof value[toDOMSymbol] === "function" ||
		typeof value[viewInsertSymbol] === "function" ||
		typeof value.nodeType === "number" );
}

function valueShouldBeInsertedAsHTML ( value ) { return value !== null && typeof value === "object" && ( typeof value [ toDOMSymbol ] === "function" || typeof value [ viewInsertSymbol ] === "function" || typeof value . nodeType === "number" ) ; }

DOM, safeString or the insertSymbol can opt-out of updating as text

DOM safeString or the insertSymbol can opt - out of updating as text


function debuggerHelper (left, right) {
	//!steal-remove-start
	if (process.env.NODE_ENV !== 'production') {
		var shouldBreak = evaluateArgs.apply(null, Array.prototype.slice.call(arguments, 0, -1));
		if (!shouldBreak) {
			return;
		}

		var options = arguments[arguments.length - 1],
			scope = options && options.scope;
		var get = function (path) {
			return scope.get(path);
		};
		// This makes sure `get`, `options` and `scope` are available
		debuggerHelper._lastGet = get;

		canLog.log('Use `get(<path>)` to debug this template');

		var allowDebugger = __testing.allowDebugger;
		// forgotten debugger
		// jshint -W087
		if (allowDebugger) {
			debugger;
			return;
		}
		// jshint +W087
	}
	//!steal-remove-end

	canLog.warn('Forgotten {{debugger}} helper');
}


function(helperOptions) {
	// lookup

	// TODO: remove in prod
	// make sure we got called with the right stuff
	if(helperOptions.exprData.argExprs.length !== 1) {
		throw new Error("for(of) broken syntax");
	}

	// TODO: check if an instance of helper;

	var helperExpr = helperOptions.exprData.argExprs[0].expr;
	var variableName, valueLookup, valueObservable;
	if(helperExpr instanceof expression.Lookup) {

		valueObservable = helperExpr.value(helperOptions.scope);

	} else if(helperExpr instanceof expression.Helper) {
		// TODO: remove in prod
		var inLookup = helperExpr.argExprs[0];
		if(inLookup.key !== "of") {
			throw new Error("for(of) broken syntax");
		}
		variableName = helperExpr.methodExpr.key;
		valueLookup = helperExpr.argExprs[1];
		valueObservable = valueLookup.value(helperOptions.scope);
	}

	var items =  valueObservable;

	var args = [].slice.call(arguments),
		options = args.pop(),
		resolved = bindAndRead(items);

	if(resolved && !canReflect.isListLike(resolved)) {
		return forOfObject(resolved,variableName, helperOptions);
	}
	if(options.stringOnly) {
		var parts = [];
		canReflect.eachIndex(resolved, function(value, index){
			var variableScope = {};
			if(variableName !== undefined){
				variableScope[variableName] = value;
			}
			parts.push(
				helperOptions.fn( options.scope
					.add({ index: index }, { special: true })
					.addLetContext(variableScope) )
			);
		});
		return parts.join("");
	} else {
		// Tells that a helper has been called, this function should be returned through
		// checking its value.
		options.metadata.rendered = true;
		return function(el){
			// make a child nodeList inside the can.view.live.html nodeList
			// so that if the html is re
			var nodeList = [el];
			nodeList.expression = "live.list";
			nodeLists.register(nodeList, null, options.nodeList, true);
			// runs nest replacements
			nodeLists.update(options.nodeList, [el]);

			var cb = function (item, index, parentNodeList) {
				var variableScope = {};
				if(variableName !== undefined){
					variableScope[variableName] = item;
				}
				return options.fn(
					options.scope
					.add({ index: index }, { special: true })
					.addLetContext(variableScope),
				options.options,
				parentNodeList
				);
			};

			live.list(el, items, cb, options.context, el.parentNode, nodeList, function(list, parentNodeList){
				return options.inverse(options.scope, options.options, parentNodeList);
			});
		};
	}
}

this is called with the ast ... we are going to use that to our advantage.

this is called with the ast ... we are going to use that to our advantage .


function(process){
		var subSection = new TextSection();
		this.last().add({process: process, truthy: subSection});
		this.stack.push(subSection);
	}

function ( process ) { var subSection = new TextSection ( ) ; this . last ( ) . add ( { process : process , truthy : subSection } ) ; this . stack . push ( subSection ) ; }


function inferType(type) {
  if (!type) return '';

  function iterateTypes(subTree) {
    return map(normalizeValue(subTree), inferType).join(', ');
  }

  switch (type.name) {
    case 'arrayOf':
      return `array of ${iterateTypes(type.value)}`;
    case 'custom':
      return COMMON_PROP_TYPES_TO_LINKS_MAP[type.raw] || type.raw;
    case 'enum':
      return `one of: ${iterateTypes(type.value)}`;
    case 'shape':
    case 'shapeOf': // FALL THROUGH
      return 'object';
    case 'union':
      return iterateTypes(type.value);
    default:
      return type.name || type.value;
  }
}

function
inferType
(
type
)
{
if
(
!
type
)
return
''
;
function
iterateTypes
(
subTree
)
{
return
map
(
normalizeValue
(
subTree
)
,
inferType
)
.
join
(
', '
)
;
}
switch
(
type
.
name
)
{
case
'arrayOf'
:
return
`
${
iterateTypes
(
type
.
value
)
}
`
;
case
'custom'
:
return
COMMON_PROP_TYPES_TO_LINKS_MAP
[
type
.
raw
]
||
type
.
raw
;
case
'enum'
:
return
`
${
iterateTypes
(
type
.
value
)
}
`
;
case
'shape'
:
case
'shapeOf'
:
// FALL THROUGH
return
'object'
;
case
'union'
:
return
iterateTypes
(
type
.
value
)
;
default
:
return
type
.
name
||
type
.
value
;
}
}

Given a type description object, return legible string description
@param {Object} type
@return {String}

Given a type description object return legible string description


function generateMarkdownTable(api) {
  if (isEmpty(api.props)) return '';
  return HEADER.concat(
    join(map(api.props, (description, propName) =>
      join([
        `\`${propName}\``,
        description.required ? 'true' : '',
        inferType(description.type),
        replaceNewlineWithBreak(getValue(description, 'defaultValue.value', '')),
        replaceNewlineWithBreak(description.description),
      ], ' | ')
    ), '\n')
  );
}

function
generateMarkdownTable
(
api
)
{
if
(
isEmpty
(
api
.
props
)
)
return
''
;
return
HEADER
.
concat
(
join
(
map
(
api
.
props
,
(
description
,
propName
)
=>
join
(
[
`
\`
${
propName
}
\`
`
,
description
.
required
'true'
:
''
,
inferType
(
description
.
type
)
,
replaceNewlineWithBreak
(
getValue
(
description
,
'defaultValue.value'
,
''
)
)
,
replaceNewlineWithBreak
(
description
.
description
)
,
]
,
' | '
)
)
,
'\n'
)
)
;
}

given tree-like description of component api, return markdown table
header of table described by HEADER
@param {Object} api
@return {String}

given tree - like description of component api return markdown table header of table described by HEADER


function buildDocs(api) {
  const view = buildTemplateView(api);

  // build up readmes one at a time
  const queue = d3.queue(1);

  Object.keys(api).forEach((filepath) => {
    queue.defer(buildReadMe, filepath, view);
  });

  queue.await((err) => {
    if (err) {
      console.log(err);
    }

    console.log('Finished building docs');
  });
}

function
buildDocs
(
api
)
{
const
view
=
buildTemplateView
(
api
)
;
// build up readmes one at a time
const
queue
=
d3
.
queue
(
1
)
;
Object
.
keys
(
api
)
.
forEach
(
(
filepath
)
=>
{
queue
.
defer
(
buildReadMe
,
filepath
,
view
)
;
}
)
;
queue
.
await
(
(
err
)
=>
{
if
(
err
)
{
console
.
log
(
err
)
;
}
console
.
log
(
'Finished building docs'
)
;
}
)
;
}

accept output from react-docgen, create READMEs
@param {Object} api

accept output from react - docgen create READMEs


function flush(callback) {
    // Ideally, this function would be a call to Polymer.dom.flush, but that
    // doesn't support a callback yet
    // (https://github.com/Polymer/polymer-dev/issues/851),
    // ...and there's cross-browser flakiness to deal with.
    // Make sure that we're invoking the callback with no arguments so that the
    // caller can pass Mocha callbacks, etc.
    var done = function done() {
        callback();
    };
    // Because endOfMicrotask is flaky for IE, we perform microtask checkpoints
    // ourselves (https://github.com/Polymer/polymer-dev/issues/114):
    var isIE = navigator.appName === 'Microsoft Internet Explorer';
    if (isIE && window.Platform && window.Platform.performMicrotaskCheckpoint) {
        var reallyDone_1 = done;
        done = function doneIE() {
            Platform.performMicrotaskCheckpoint();
            nativeSetTimeout(reallyDone_1, 0);
        };
    }
    // Everyone else gets a regular flush.
    var scope;
    if (window.Polymer && window.Polymer.dom && window.Polymer.dom.flush) {
        scope = window.Polymer.dom;
    }
    else if (window.Polymer && window.Polymer.flush) {
        scope = window.Polymer;
    }
    else if (window.WebComponents && window.WebComponents.flush) {
        scope = window.WebComponents;
    }
    if (scope) {
        scope.flush();
    }
    // Ensure that we are creating a new _task_ to allow all active microtasks to
    // finish (the code you're testing may be using endOfMicrotask, too).
    nativeSetTimeout(done, 0);
}

Triggers a flush of any pending events, observations, etc and calls you back
after they have been processed.

@param {function()} callback

Triggers a flush of any pending events observations etc and calls you back after they have been processed .


function setup(options) {
    var childRunner = ChildRunner.current();
    if (childRunner) {
        _deepMerge(_config, childRunner.parentScope.WCT._config);
        // But do not force the mocha UI
        delete _config.mochaOptions.ui;
    }
    if (options && typeof options === 'object') {
        _deepMerge(_config, options);
    }
    if (!_config.root) {
        // Sibling dependencies.
        var root = scriptPrefix('browser.js');
        _config.root = basePath(root.substr(0, root.length - 1));
        if (!_config.root) {
            throw new Error('Unable to detect root URL for WCT sources. Please set WCT.root before including browser.js');
        }
    }
}

Merges initial `options` into WCT's global configuration.

@param {Object} options The options to merge. See `browser/config.js` for a
reference.

Merges initial options into WCT s global configuration .


function expandUrl(url, base) {
    if (!base)
        return url;
    if (url.match(/^(\/|https?:\/\/)/))
        return url;
    if (base.substr(base.length - 1) !== '/') {
        base = base + '/';
    }
    return base + url;
}

function expandUrl ( url , base ) { if ( ! base ) return url ; if ( url . match ( / ^(\/|https?:\/\/) / ) ) return url ; if ( base . substr ( base . length - 1 ) !== '/' ) { base = base + '/' ; } return base + url ; }

Expands a URL that may or may not be relative to `base`.

@param {string} url
@param {string} base
@return {string}

Expands a URL that may or may not be relative to base .


function scriptPrefix(filename) {
    var scripts = document.querySelectorAll('script[src*="' + filename + '"]');
    if (scripts.length !== 1) {
        return null;
    }
    var script = scripts[0].src;
    return script.substring(0, script.indexOf(filename));
}

function scriptPrefix ( filename ) { var scripts = document . querySelectorAll ( 'script[src*="' + filename + '"]' ) ; if ( scripts . length !== 1 ) { return null ; } var script = scripts [ 0 ] . src ; return script . substring ( 0 , script . indexOf ( filename ) ) ; }

Finds the directory that a loaded script is hosted on.

@param {string} filename
@return {string?}

Finds the directory that a loaded script is hosted on .


function drawFaviconArc(context, total, start, length, color) {
    var arcStart = ARC_OFFSET + Math.PI * 2 * (start / total);
    var arcEnd = ARC_OFFSET + Math.PI * 2 * ((start + length) / total);
    context.beginPath();
    context.strokeStyle = color;
    context.lineWidth = ARC_WIDTH;
    context.arc(16, 16, 16 - ARC_WIDTH / 2, arcStart, arcEnd);
    context.stroke();
}

function drawFaviconArc ( context , total , start , length , color ) { var arcStart = ARC_OFFSET + Math . PI * 2 * ( start / total ) ; var arcEnd = ARC_OFFSET + Math . PI * 2 * ( ( start + length ) / total ) ; context . beginPath ( ) ; context . strokeStyle = color ; context . lineWidth = ARC_WIDTH ; context . arc ( 16 , 16 , 16 - ARC_WIDTH / 2 , arcStart , arcEnd ) ; context . stroke ( ) ; }

Draws an arc for the favicon status, relative to the total number of tests.

Draws an arc for the favicon status relative to the total number of tests .


function loadSuites(files) {
    files.forEach(function (file) {
        if (/\.js(\?.*)?$/.test(file)) {
            jsSuites$1.push(file);
        }
        else if (/\.html(\?.*)?$/.test(file)) {
            htmlSuites$1.push(file);
        }
        else {
            throw new Error('Unknown resource type: ' + file);
        }
    });
}

function
loadSuites
(
files
)
{
files
.
forEach
(
function
(
file
)
{
if
(
/
\.js(\?.*)?$
/
.
test
(
file
)
)
{
jsSuites$1
.
push
(
file
)
;
}
else
if
(
/
\.html(\?.*)?$
/
.
test
(
file
)
)
{
htmlSuites$1
.
push
(
file
)
;
}
else
{
throw
new
Error
(
'Unknown resource type: '
+
file
)
;
}
}
)
;
}

Loads suites of tests, supporting both `.js` and `.html` files.

@param files The files to load.

Loads suites of tests supporting both . js and . html files .


function loadJsSuites(_reporter, done) {
    debug('loadJsSuites', jsSuites$1);
    var loaders = jsSuites$1.map(function (file) {
        // We only support `.js` dependencies for now.
        return loadScript.bind(util, file);
    });
    parallel(loaders, done);
}

Loads all `.js` sources requested by the current suite.

Loads all . js sources requested by the current suite .