summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/user_tabs.js.coffee
blob: 0b285f6ad80182d00aea2e248ed498860f3fd6f2 (plain)
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
82
83
84
85
86
class @UserTabs
  actions: ['activity', 'groups', 'contributed', 'personal'],
  defaultAction: 'activity',
  tabButtonSelector: '.nav-links a[data-toggle="tab"]'

  constructor: (@opts = {}) ->
    # Store the `location` object, allowing for easier stubbing in tests
    @_location = location
    @loaded = {}

    @bindEvents()
    @setTabState()

    # Set default tab
    source = $(".#{@defaultAction}-tab a").attr('href')
    @setTab(source, @defaultAction)

  bindEvents: ->
    $(document).on 'shown.bs.tab', @tabButtonSelector, @tabShown

  setTabState: ->
    for action in @actions
      @loaded[action] = false

  tabShown: (event) =>
    $target = $(event.target)
    action = $target.data('action')
    source = $target.attr('href')

    @setTab(source, action)
    @setCurrentAction(action)

  setTab: (source, action) ->
    return if @loaded[action] is true

    if action is 'activity'
      @loadActivities(source)

    if action is 'groups'
      @loadTab(source, action)

    if action is 'contributed'
      @loadTab(source, action)

    if action is 'personal'
      @loadTab(source, action)

  loadTab: (source, action) ->
    $.ajax
      beforeSend: => @toggleLoading(true)
      complete:   => @toggleLoading(false)
      dataType: 'json'
      type: 'GET'
      url: "#{source}.json"
      success: (data) =>
        tabSelector = 'div#' + action
        document.querySelector(tabSelector).innerHTML = data.html
        @loaded[action] = true

  loadActivities: (source) ->
    return if @loaded['activity'] is true

    $calendarWrap = $('.user-calendar')
    $calendarWrap.load($calendarWrap.data('url'))

    new Activities()
    @loaded['activity'] = true

  toggleLoading: (status) ->
    $('.loading-status .loading').toggle(status)

  setCurrentAction: (action) ->
    # Remove possible actions from URL
    regExp = new RegExp('\/(' + @actions.join('|') + ')(\.html)?\/?$')
    new_state = @_location.pathname.replace(regExp, '')

    # Append the new action if we're on a tab other than 'activity'
    unless action == @defaultAction
      new_state += "/#{action}"

    # Ensure parameters and hash come along for the ride
    new_state += @_location.search + @_location.hash

    history.replaceState {turbolinks: true, url: new_state}, document.title, new_state

    new_state