Sha256: 08825c4ac6337c4dae612780d6942a57b5d86ca41a2a28283d04bbaf5c90ad62

Contents?: true

Size: 1.5 KB

Versions: 6

Compression:

Stored size: 1.5 KB

Contents

/* global history, location */

import $ from 'jquery'

import { init } from '../core/events'

const TAB_SELECTOR = 'a[data-toggle="tab"]'
const TAB_PANE_SELECTOR = '.tab-pane'
const ERROR_SELECTOR = '.is-invalid:not([type="hidden"])'

// Save active tab to URL hash
init(function (root) {
  $(root).find(TAB_SELECTOR).on('shown.bs.tab', function (e) {
    const hash = $(this).attr('href')
    const withinModal = $(this).closest('.modal').length > 0

    if (hash.substr(0, 1) === '#' && !withinModal) {
      history.replaceState({ turbolinks: {} }, '', '#!' + hash.substr(1))
    }
  })
})

// Restore active tab when loading
init(function () {
  focusActiveTab()
})

// Add error count to tabs
init(function (root) {
  $(root).find(TAB_PANE_SELECTOR).each(function () {
    const errorCount = $(this).find(ERROR_SELECTOR).length

    if (errorCount > 0) {
      const badge = $('<span>').addClass('badge badge-danger badge-pill').text(errorCount)
      const id = $(this).attr('id')
      const selector = `${TAB_SELECTOR}[href='#${id}']`

      $(selector).append(badge)
    }
  })
})

export function focusTab (id) {
  const selector = `${TAB_SELECTOR}[href='#${id}']`
  $(selector).tab('show')
}

export function focusActiveTab () {
  if (location.hash.substr(0, 2) === '#!') {
    // Focus on active tab from URL
    focusTab(location.hash.substr(2))
  } else {
    const $errorTabs = $(`${TAB_PANE_SELECTOR}:has(${ERROR_SELECTOR})`)

    if ($errorTabs.length) {
      focusTab($errorTabs.first().attr('id'))
    }
  }
}

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
trestle-0.9.7 frontend/js/components/tabs.js
trestle-0.9.6 frontend/js/components/tabs.js
trestle-0.9.5 frontend/js/components/tabs.js
trestle-0.9.4 frontend/js/components/tabs.js
trestle-0.9.3 frontend/js/components/tabs.js
trestle-0.9.2 frontend/js/components/tabs.js