all files / src/ collectionStats.cjsx

87.5% Statements 35/40
66.67% Branches 6/9
100% Functions 6/6
90.91% Lines 30/33
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                                                                                                     
 
React = require('react')
Backbone = require('backbone')
 
# see ./collectionStats.md
module.exports = class CollectionStats extends React.Component
  @displayName: "react-datum.CollectionStats"
 
  @propTypes:
    # a Backbone.Collection
    collection: React.PropTypes.instanceOf(Backbone.Collection)
 
    # used as the display name for found items. ex.
    #```javascript
    #  <CollectionStats itemDisplayName="thing"/>
    #```
    # => "Found 1,230 things".
    itemDisplayName: React.PropTypes.string
 
  @defaultProps:
    itemDisplayName: "item"
 
  @contextTypes:
    collection: React.PropTypes.instanceOf(Backbone.Collection)
 
 
  render: ->
    @collection = @props.collection || @context.collection
    Iunless @collection?
      throw "#{@constructor.displayName} needs a collection prop or react-datum Collection context parent"
 
    return (
      <div className='collection-stats'>
        {@_renderFound()}
        {@_renderSelected()}
        {@_renderViewing()}
      </div>
    )
 
 
  _renderFound: ->
    total = @collection.getTotalRows?() || @collection.models.length
    displayName = @props.itemDisplayName
    things = switch
      # inflection is loaded globally
      when inflection?.inflect? then inflection.inflect(@props.itemDisplayName, total)
      # ... hack for zuKeeper string helpers
      when displayName.plural? then displayName.plural(total)
      else displayName
 
    return (
      <span className="found stats fade in">
        Found {@_renderCount(total)} {things}
      </span>
    )
 
 
  _renderSelected: ->
    return null unless @collection.hasSelectableCollection
    return(
      <span className="selected stats fade in">
        , {@_renderCount(@collection.getSelectedModels().length)} selected
      </span>
    )
 
 
  _renderViewing: ->
    topIndex = @collection.topDisplayIndex || @collection.statsModel?.get('topDisplayIndex')
    bottomIndex = @collection.bottomDisplayIndex || @collection.statsModel?.get('bottomDisplayIndex')
    return null unless topIndex? && bottomIndex
    return (
      <span className="viewing stats fade in">
        Viewing {@_renderCount(topIndex, 'top-index')} - 
        {@_renderCount(bottomIndex, 'bottom-index')}
      </span>
    )
    
  _renderCount: (value, addClass="") ->
    className = ["count", addClass].join(' ')
    return <span className={className}>{value}</span>