picker.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. /*!
  2. * pickadate.js v3.5.6, 2015/04/20
  3. * By Amsul, http://amsul.ca
  4. * Hosted on http://amsul.github.io/pickadate.js
  5. * Licensed under MIT
  6. */
  7. (function (factory) {
  8. // AMD.
  9. if (typeof define == 'function' && define.amd)
  10. define('picker', ['jquery'], factory)
  11. // Node.js/browserify.
  12. else if (typeof exports == 'object')
  13. module.exports = factory(require('jquery'))
  14. // Browser globals.
  15. else this.Picker = factory(jQuery)
  16. }(function ($) {
  17. var $window = $(window)
  18. var $document = $(document)
  19. var $html = $(document.documentElement)
  20. var supportsTransitions = document.documentElement.style.transition != null
  21. /**
  22. * The picker constructor that creates a blank picker.
  23. */
  24. function PickerConstructor(ELEMENT, NAME, COMPONENT, OPTIONS) {
  25. // If there’s no element, return the picker constructor.
  26. if (!ELEMENT) return PickerConstructor
  27. var
  28. IS_DEFAULT_THEME = false,
  29. // The state of the picker.
  30. STATE = {
  31. id: ELEMENT.id || 'P' + Math.abs(~~(Math.random() * new Date()))
  32. },
  33. // Merge the defaults and options passed.
  34. SETTINGS = COMPONENT ? $.extend(true, {}, COMPONENT.defaults, OPTIONS) : OPTIONS || {},
  35. // Merge the default classes with the settings classes.
  36. CLASSES = $.extend({}, PickerConstructor.klasses(), SETTINGS.klass),
  37. // The element node wrapper into a jQuery object.
  38. $ELEMENT = $(ELEMENT),
  39. // Pseudo picker constructor.
  40. PickerInstance = function () {
  41. return this.start()
  42. },
  43. // The picker prototype.
  44. P = PickerInstance.prototype = {
  45. constructor: PickerInstance,
  46. $node: $ELEMENT,
  47. /**
  48. * Initialize everything
  49. */
  50. start: function () {
  51. // If it’s already started, do nothing.
  52. if (STATE && STATE.start) return P
  53. // Update the picker states.
  54. STATE.methods = {}
  55. STATE.start = true
  56. STATE.open = false
  57. STATE.type = ELEMENT.type
  58. // Confirm focus state, convert into text input to remove UA stylings,
  59. // and set as readonly to prevent keyboard popup.
  60. ELEMENT.autofocus = ELEMENT == getActiveElement()
  61. ELEMENT.readOnly = !SETTINGS.editable
  62. ELEMENT.id = ELEMENT.id || STATE.id
  63. if (ELEMENT.type != 'text') {
  64. ELEMENT.type = 'text'
  65. }
  66. // Create a new picker component with the settings.
  67. P.component = new COMPONENT(P, SETTINGS)
  68. // Create the picker root and then prepare it.
  69. P.$root = $('<div class="' + CLASSES.picker + '" id="' + ELEMENT.id + '_root" />')
  70. prepareElementRoot()
  71. // Create the picker holder and then prepare it.
  72. P.$holder = $(createWrappedComponent()).appendTo(P.$root)
  73. prepareElementHolder()
  74. // If there’s a format for the hidden input element, create the element.
  75. if (SETTINGS.formatSubmit) {
  76. prepareElementHidden()
  77. }
  78. // Prepare the input element.
  79. prepareElement()
  80. // Insert the hidden input as specified in the settings.
  81. if (SETTINGS.containerHidden) $(SETTINGS.containerHidden).append(P._hidden)
  82. else $ELEMENT.after(P._hidden)
  83. // Insert the root as specified in the settings.
  84. if (SETTINGS.container) $(SETTINGS.container).append(P.$root)
  85. else $ELEMENT.after(P.$root)
  86. // Bind the default component and settings events.
  87. P.on({
  88. start: P.component.onStart,
  89. render: P.component.onRender,
  90. stop: P.component.onStop,
  91. open: P.component.onOpen,
  92. close: P.component.onClose,
  93. set: P.component.onSet
  94. }).on({
  95. start: SETTINGS.onStart,
  96. render: SETTINGS.onRender,
  97. stop: SETTINGS.onStop,
  98. open: SETTINGS.onOpen,
  99. close: SETTINGS.onClose,
  100. set: SETTINGS.onSet
  101. })
  102. // Once we’re all set, check the theme in use.
  103. IS_DEFAULT_THEME = isUsingDefaultTheme(P.$holder[0])
  104. // If the element has autofocus, open the picker.
  105. if (ELEMENT.autofocus) {
  106. P.open()
  107. }
  108. // Trigger queued the “start” and “render” events.
  109. return P.trigger('start').trigger('render')
  110. }, //start
  111. /**
  112. * Render a new picker
  113. */
  114. render: function (entireComponent) {
  115. // Insert a new component holder in the root or box.
  116. if (entireComponent) {
  117. P.$holder = $(createWrappedComponent())
  118. prepareElementHolder()
  119. P.$root.html(P.$holder)
  120. } else P.$root.find('.' + CLASSES.box).html(P.component.nodes(STATE.open))
  121. // Trigger the queued “render” events.
  122. return P.trigger('render')
  123. }, //render
  124. /**
  125. * Destroy everything
  126. */
  127. stop: function () {
  128. // If it’s already stopped, do nothing.
  129. if (!STATE.start) return P
  130. // Then close the picker.
  131. P.close()
  132. // Remove the hidden field.
  133. if (P._hidden) {
  134. P._hidden.parentNode.removeChild(P._hidden)
  135. }
  136. // Remove the root.
  137. P.$root.remove()
  138. // Remove the input class, remove the stored data, and unbind
  139. // the events (after a tick for IE - see `P.close`).
  140. $ELEMENT.removeClass(CLASSES.input).removeData(NAME)
  141. setTimeout(function () {
  142. $ELEMENT.off('.' + STATE.id)
  143. }, 0)
  144. // Restore the element state
  145. ELEMENT.type = STATE.type
  146. ELEMENT.readOnly = false
  147. // Trigger the queued “stop” events.
  148. P.trigger('stop')
  149. // Reset the picker states.
  150. STATE.methods = {}
  151. STATE.start = false
  152. return P
  153. }, //stop
  154. /**
  155. * Open up the picker
  156. */
  157. open: function (dontGiveFocus) {
  158. // If it’s already open, do nothing.
  159. if (STATE.open) return P
  160. // Add the “active” class.
  161. $ELEMENT.addClass(CLASSES.active)
  162. aria(ELEMENT, 'expanded', true)
  163. // * A Firefox bug, when `html` has `overflow:hidden`, results in
  164. // killing transitions :(. So add the “opened” state on the next tick.
  165. // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
  166. setTimeout(function () {
  167. // Add the “opened” class to the picker root.
  168. P.$root.addClass(CLASSES.opened)
  169. aria(P.$root[0], 'hidden', false)
  170. }, 0)
  171. // If we have to give focus, bind the element and doc events.
  172. if (dontGiveFocus !== false) {
  173. // Set it as open.
  174. STATE.open = true
  175. // Prevent the page from scrolling.
  176. if (IS_DEFAULT_THEME) {
  177. $html.
  178. css('overflow', 'hidden').
  179. css('padding-right', '+=' + getScrollbarWidth())
  180. }
  181. // Pass focus to the root element’s jQuery object.
  182. focusPickerOnceOpened()
  183. // Bind the document events.
  184. $document.on('click.' + STATE.id + ' focusin.' + STATE.id, function (event) {
  185. var target = event.target
  186. // If the target of the event is not the element, close the picker picker.
  187. // * Don’t worry about clicks or focusins on the root because those don’t bubble up.
  188. // Also, for Firefox, a click on an `option` element bubbles up directly
  189. // to the doc. So make sure the target wasn't the doc.
  190. // * In Firefox stopPropagation() doesn’t prevent right-click events from bubbling,
  191. // which causes the picker to unexpectedly close when right-clicking it. So make
  192. // sure the event wasn’t a right-click.
  193. if (target != ELEMENT && target != document && event.which != 3) {
  194. // If the target was the holder that covers the screen,
  195. // keep the element focused to maintain tabindex.
  196. P.close(target === P.$holder[0])
  197. }
  198. }).on('keydown.' + STATE.id, function (event) {
  199. var
  200. // Get the keycode.
  201. keycode = event.keyCode,
  202. // Translate that to a selection change.
  203. keycodeToMove = P.component.key[keycode],
  204. // Grab the target.
  205. target = event.target
  206. // On escape, close the picker and give focus.
  207. if (keycode == 27) {
  208. P.close(true)
  209. }
  210. // Check if there is a key movement or “enter” keypress on the element.
  211. else if (target == P.$holder[0] && (keycodeToMove || keycode == 13)) {
  212. // Prevent the default action to stop page movement.
  213. event.preventDefault()
  214. // Trigger the key movement action.
  215. if (keycodeToMove) {
  216. PickerConstructor._.trigger(P.component.key.go, P, [PickerConstructor._.trigger(keycodeToMove)])
  217. }
  218. // On “enter”, if the highlighted item isn’t disabled, set the value and close.
  219. else if (!P.$root.find('.' + CLASSES.highlighted).hasClass(CLASSES.disabled)) {
  220. P.set('select', P.component.item.highlight)
  221. if (SETTINGS.closeOnSelect) {
  222. P.close(true)
  223. }
  224. }
  225. }
  226. // If the target is within the root and “enter” is pressed,
  227. // prevent the default action and trigger a click on the target instead.
  228. else if ($.contains(P.$root[0], target) && keycode == 13) {
  229. event.preventDefault()
  230. target.click()
  231. }
  232. })
  233. }
  234. // Trigger the queued “open” events.
  235. return P.trigger('open')
  236. }, //open
  237. /**
  238. * Close the picker
  239. */
  240. close: function (giveFocus) {
  241. // If we need to give focus, do it before changing states.
  242. if (giveFocus) {
  243. if (SETTINGS.editable) {
  244. ELEMENT.focus()
  245. } else {
  246. // ....ah yes! It would’ve been incomplete without a crazy workaround for IE :|
  247. // The focus is triggered *after* the close has completed - causing it
  248. // to open again. So unbind and rebind the event at the next tick.
  249. P.$holder.off('focus.toOpen').focus()
  250. setTimeout(function () {
  251. P.$holder.on('focus.toOpen', handleFocusToOpenEvent)
  252. }, 0)
  253. }
  254. }
  255. // Remove the “active” class.
  256. $ELEMENT.removeClass(CLASSES.active)
  257. aria(ELEMENT, 'expanded', false)
  258. // * A Firefox bug, when `html` has `overflow:hidden`, results in
  259. // killing transitions :(. So remove the “opened” state on the next tick.
  260. // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
  261. setTimeout(function () {
  262. // Remove the “opened” and “focused” class from the picker root.
  263. P.$root.removeClass(CLASSES.opened + ' ' + CLASSES.focused)
  264. aria(P.$root[0], 'hidden', true)
  265. }, 0)
  266. // If it’s already closed, do nothing more.
  267. if (!STATE.open) return P
  268. // Set it as closed.
  269. STATE.open = false
  270. // Allow the page to scroll.
  271. if (IS_DEFAULT_THEME) {
  272. $html.
  273. css('overflow', '').
  274. css('padding-right', '-=' + getScrollbarWidth())
  275. }
  276. // Unbind the document events.
  277. $document.off('.' + STATE.id)
  278. // Trigger the queued “close” events.
  279. return P.trigger('close')
  280. }, //close
  281. /**
  282. * Clear the values
  283. */
  284. clear: function (options) {
  285. return P.set('clear', null, options)
  286. }, //clear
  287. /**
  288. * Set something
  289. */
  290. set: function (thing, value, options) {
  291. var thingItem, thingValue,
  292. thingIsObject = $.isPlainObject(thing),
  293. thingObject = thingIsObject ? thing : {}
  294. // Make sure we have usable options.
  295. options = thingIsObject && $.isPlainObject(value) ? value : options || {}
  296. if (thing) {
  297. // If the thing isn’t an object, make it one.
  298. if (!thingIsObject) {
  299. thingObject[thing] = value
  300. }
  301. // Go through the things of items to set.
  302. for (thingItem in thingObject) {
  303. // Grab the value of the thing.
  304. thingValue = thingObject[thingItem]
  305. // First, if the item exists and there’s a value, set it.
  306. if (thingItem in P.component.item) {
  307. if (thingValue === undefined) thingValue = null
  308. P.component.set(thingItem, thingValue, options)
  309. }
  310. // Then, check to update the element value and broadcast a change.
  311. if (thingItem == 'select' || thingItem == 'clear') {
  312. $ELEMENT.
  313. val(thingItem == 'clear' ? '' : P.get(thingItem, SETTINGS.format)).
  314. trigger('change')
  315. }
  316. }
  317. // Render a new picker.
  318. P.render()
  319. }
  320. // When the method isn’t muted, trigger queued “set” events and pass the `thingObject`.
  321. return options.muted ? P : P.trigger('set', thingObject)
  322. }, //set
  323. /**
  324. * Get something
  325. */
  326. get: function (thing, format) {
  327. // Make sure there’s something to get.
  328. thing = thing || 'value'
  329. // If a picker state exists, return that.
  330. if (STATE[thing] != null) {
  331. return STATE[thing]
  332. }
  333. // Return the submission value, if that.
  334. if (thing == 'valueSubmit') {
  335. if (P._hidden) {
  336. return P._hidden.value
  337. }
  338. thing = 'value'
  339. }
  340. // Return the value, if that.
  341. if (thing == 'value') {
  342. return ELEMENT.value
  343. }
  344. // Check if a component item exists, return that.
  345. if (thing in P.component.item) {
  346. if (typeof format == 'string') {
  347. var thingValue = P.component.get(thing)
  348. return thingValue ?
  349. PickerConstructor._.trigger(
  350. P.component.formats.toString,
  351. P.component, [format, thingValue]
  352. ) : ''
  353. }
  354. return P.component.get(thing)
  355. }
  356. }, //get
  357. /**
  358. * Bind events on the things.
  359. */
  360. on: function (thing, method, internal) {
  361. var thingName, thingMethod,
  362. thingIsObject = $.isPlainObject(thing),
  363. thingObject = thingIsObject ? thing : {}
  364. if (thing) {
  365. // If the thing isn’t an object, make it one.
  366. if (!thingIsObject) {
  367. thingObject[thing] = method
  368. }
  369. // Go through the things to bind to.
  370. for (thingName in thingObject) {
  371. // Grab the method of the thing.
  372. thingMethod = thingObject[thingName]
  373. // If it was an internal binding, prefix it.
  374. if (internal) {
  375. thingName = '_' + thingName
  376. }
  377. // Make sure the thing methods collection exists.
  378. STATE.methods[thingName] = STATE.methods[thingName] || []
  379. // Add the method to the relative method collection.
  380. STATE.methods[thingName].push(thingMethod)
  381. }
  382. }
  383. return P
  384. }, //on
  385. /**
  386. * Unbind events on the things.
  387. */
  388. off: function () {
  389. var i, thingName,
  390. names = arguments;
  391. for (i = 0, namesCount = names.length; i < namesCount; i += 1) {
  392. thingName = names[i]
  393. if (thingName in STATE.methods) {
  394. delete STATE.methods[thingName]
  395. }
  396. }
  397. return P
  398. },
  399. /**
  400. * Fire off method events.
  401. */
  402. trigger: function (name, data) {
  403. var _trigger = function (name) {
  404. var methodList = STATE.methods[name]
  405. if (methodList) {
  406. methodList.map(function (method) {
  407. PickerConstructor._.trigger(method, P, [data])
  408. })
  409. }
  410. }
  411. _trigger('_' + name)
  412. _trigger(name)
  413. return P
  414. } //trigger
  415. } //PickerInstance.prototype
  416. /**
  417. * Wrap the picker holder components together.
  418. */
  419. function createWrappedComponent() {
  420. // Create a picker wrapper holder
  421. return PickerConstructor._.node('div',
  422. // Create a picker wrapper node
  423. PickerConstructor._.node('div',
  424. // Create a picker frame
  425. PickerConstructor._.node('div',
  426. // Create a picker box node
  427. PickerConstructor._.node('div',
  428. // Create the components nodes.
  429. P.component.nodes(STATE.open),
  430. // The picker box class
  431. CLASSES.box
  432. ),
  433. // Picker wrap class
  434. CLASSES.wrap
  435. ),
  436. // Picker frame class
  437. CLASSES.frame
  438. ),
  439. // Picker holder class
  440. CLASSES.holder,
  441. 'tabindex="-1"'
  442. ) //endreturn
  443. } //createWrappedComponent
  444. /**
  445. * Prepare the input element with all bindings.
  446. */
  447. function prepareElement() {
  448. $ELEMENT.
  449. // Store the picker data by component name.
  450. data(NAME, P).
  451. // Add the “input” class name.
  452. addClass(CLASSES.input).
  453. // If there’s a `data-value`, update the value of the element.
  454. val($ELEMENT.data('value') ?
  455. P.get('select', SETTINGS.format) :
  456. ELEMENT.value
  457. )
  458. // Only bind keydown events if the element isn’t editable.
  459. if (!SETTINGS.editable) {
  460. $ELEMENT.
  461. // On focus/click, open the picker.
  462. on('focus.' + STATE.id + ' click.' + STATE.id, function (event) {
  463. event.preventDefault()
  464. P.open()
  465. }).
  466. // Handle keyboard event based on the picker being opened or not.
  467. on('keydown.' + STATE.id, handleKeydownEvent)
  468. }
  469. // Update the aria attributes.
  470. aria(ELEMENT, {
  471. haspopup: true,
  472. expanded: false,
  473. readonly: false,
  474. owns: ELEMENT.id + '_root'
  475. })
  476. }
  477. /**
  478. * Prepare the root picker element with all bindings.
  479. */
  480. function prepareElementRoot() {
  481. aria(P.$root[0], 'hidden', true)
  482. }
  483. /**
  484. * Prepare the holder picker element with all bindings.
  485. */
  486. function prepareElementHolder() {
  487. P.$holder.
  488. on({
  489. // For iOS8.
  490. keydown: handleKeydownEvent,
  491. 'focus.toOpen': handleFocusToOpenEvent,
  492. blur: function () {
  493. // Remove the “target” class.
  494. $ELEMENT.removeClass(CLASSES.target)
  495. },
  496. // When something within the holder is focused, stop from bubbling
  497. // to the doc and remove the “focused” state from the root.
  498. focusin: function (event) {
  499. P.$root.removeClass(CLASSES.focused)
  500. event.stopPropagation()
  501. },
  502. // When something within the holder is clicked, stop it
  503. // from bubbling to the doc.
  504. 'mousedown click': function (event) {
  505. var target = event.target
  506. // Make sure the target isn’t the root holder so it can bubble up.
  507. if (target != P.$holder[0]) {
  508. event.stopPropagation()
  509. // * For mousedown events, cancel the default action in order to
  510. // prevent cases where focus is shifted onto external elements
  511. // when using things like jQuery mobile or MagnificPopup (ref: #249 & #120).
  512. // Also, for Firefox, don’t prevent action on the `option` element.
  513. if (event.type == 'mousedown' && !$(target).is('input, select, textarea, button, option')) {
  514. event.preventDefault()
  515. // Re-focus onto the holder so that users can click away
  516. // from elements focused within the picker.
  517. P.$holder[0].focus()
  518. }
  519. }
  520. }
  521. }).
  522. // If there’s a click on an actionable element, carry out the actions.
  523. on('click', '[data-pick], [data-nav], [data-clear], [data-close]', function () {
  524. var $target = $(this),
  525. targetData = $target.data(),
  526. targetDisabled = $target.hasClass(CLASSES.navDisabled) || $target.hasClass(CLASSES.disabled),
  527. // * For IE, non-focusable elements can be active elements as well
  528. // (http://stackoverflow.com/a/2684561).
  529. activeElement = getActiveElement()
  530. activeElement = activeElement && (activeElement.type || activeElement.href)
  531. // If it’s disabled or nothing inside is actively focused, re-focus the element.
  532. if (targetDisabled || activeElement && !$.contains(P.$root[0], activeElement)) {
  533. P.$holder[0].focus()
  534. }
  535. // If something is superficially changed, update the `highlight` based on the `nav`.
  536. if (!targetDisabled && targetData.nav) {
  537. P.set('highlight', P.component.item.highlight, {
  538. nav: targetData.nav
  539. })
  540. }
  541. // If something is picked, set `select` then close with focus.
  542. else if (!targetDisabled && 'pick' in targetData) {
  543. P.set('select', targetData.pick)
  544. if (SETTINGS.closeOnSelect) {
  545. P.close(true)
  546. }
  547. }
  548. // If a “clear” button is pressed, empty the values and close with focus.
  549. else if (targetData.clear) {
  550. P.clear()
  551. if (SETTINGS.closeOnClear) {
  552. P.close(true)
  553. }
  554. } else if (targetData.close) {
  555. P.close(true)
  556. }
  557. }) //P.$holder
  558. }
  559. /**
  560. * Prepare the hidden input element along with all bindings.
  561. */
  562. function prepareElementHidden() {
  563. var name
  564. if (SETTINGS.hiddenName === true) {
  565. name = ELEMENT.name
  566. ELEMENT.name = ''
  567. } else {
  568. name = [
  569. typeof SETTINGS.hiddenPrefix == 'string' ? SETTINGS.hiddenPrefix : '',
  570. typeof SETTINGS.hiddenSuffix == 'string' ? SETTINGS.hiddenSuffix : '_submit'
  571. ]
  572. name = name[0] + ELEMENT.name + name[1]
  573. }
  574. P._hidden = $(
  575. '<input ' +
  576. 'type=hidden ' +
  577. // Create the name using the original input’s with a prefix and suffix.
  578. 'name="' + name + '"' +
  579. // If the element has a value, set the hidden value as well.
  580. (
  581. $ELEMENT.data('value') || ELEMENT.value ?
  582. ' value="' + P.get('select', SETTINGS.formatSubmit) + '"' :
  583. ''
  584. ) +
  585. '>'
  586. )[0]
  587. $ELEMENT.
  588. // If the value changes, update the hidden input with the correct format.
  589. on('change.' + STATE.id, function () {
  590. P._hidden.value = ELEMENT.value ?
  591. P.get('select', SETTINGS.formatSubmit) :
  592. ''
  593. })
  594. }
  595. // Wait for transitions to end before focusing the holder. Otherwise, while
  596. // using the `container` option, the view jumps to the container.
  597. function focusPickerOnceOpened() {
  598. if (IS_DEFAULT_THEME && supportsTransitions) {
  599. P.$holder.find('.' + CLASSES.frame).one('transitionend', function () {
  600. P.$holder[0].focus()
  601. })
  602. } else {
  603. P.$holder[0].focus()
  604. }
  605. }
  606. function handleFocusToOpenEvent(event) {
  607. // Stop the event from propagating to the doc.
  608. event.stopPropagation()
  609. // Add the “target” class.
  610. $ELEMENT.addClass(CLASSES.target)
  611. // Add the “focused” class to the root.
  612. P.$root.addClass(CLASSES.focused)
  613. // And then finally open the picker.
  614. P.open()
  615. }
  616. // For iOS8.
  617. function handleKeydownEvent(event) {
  618. var keycode = event.keyCode,
  619. // Check if one of the delete keys was pressed.
  620. isKeycodeDelete = /^(8|46)$/.test(keycode)
  621. // For some reason IE clears the input value on “escape”.
  622. if (keycode == 27) {
  623. P.close(true)
  624. return false
  625. }
  626. // Check if `space` or `delete` was pressed or the picker is closed with a key movement.
  627. if (keycode == 32 || isKeycodeDelete || !STATE.open && P.component.key[keycode]) {
  628. // Prevent it from moving the page and bubbling to doc.
  629. event.preventDefault()
  630. event.stopPropagation()
  631. // If `delete` was pressed, clear the values and close the picker.
  632. // Otherwise open the picker.
  633. if (isKeycodeDelete) {
  634. P.clear().close()
  635. } else {
  636. P.open()
  637. }
  638. }
  639. }
  640. // Return a new picker instance.
  641. return new PickerInstance()
  642. } //PickerConstructor
  643. /**
  644. * The default classes and prefix to use for the HTML classes.
  645. */
  646. PickerConstructor.klasses = function (prefix) {
  647. prefix = prefix || 'picker'
  648. return {
  649. picker: prefix,
  650. opened: prefix + '--opened',
  651. focused: prefix + '--focused',
  652. input: prefix + '__input',
  653. active: prefix + '__input--active',
  654. target: prefix + '__input--target',
  655. holder: prefix + '__holder',
  656. frame: prefix + '__frame',
  657. wrap: prefix + '__wrap',
  658. box: prefix + '__box'
  659. }
  660. } //PickerConstructor.klasses
  661. /**
  662. * Check if the default theme is being used.
  663. */
  664. function isUsingDefaultTheme(element) {
  665. var theme,
  666. prop = 'position'
  667. // For IE.
  668. if (element.currentStyle) {
  669. theme = element.currentStyle[prop]
  670. }
  671. // For normal browsers.
  672. else if (window.getComputedStyle) {
  673. theme = getComputedStyle(element)[prop]
  674. }
  675. return theme == 'fixed'
  676. }
  677. /**
  678. * Get the width of the browser’s scrollbar.
  679. * Taken from: https://github.com/VodkaBears/Remodal/blob/master/src/jquery.remodal.js
  680. */
  681. function getScrollbarWidth() {
  682. if ($html.height() <= $window.height()) {
  683. return 0
  684. }
  685. var $outer = $('<div style="visibility:hidden;width:100px" />').
  686. appendTo('body')
  687. // Get the width without scrollbars.
  688. var widthWithoutScroll = $outer[0].offsetWidth
  689. // Force adding scrollbars.
  690. $outer.css('overflow', 'scroll')
  691. // Add the inner div.
  692. var $inner = $('<div style="width:100%" />').appendTo($outer)
  693. // Get the width with scrollbars.
  694. var widthWithScroll = $inner[0].offsetWidth
  695. // Remove the divs.
  696. $outer.remove()
  697. // Return the difference between the widths.
  698. return widthWithoutScroll - widthWithScroll
  699. }
  700. /**
  701. * PickerConstructor helper methods.
  702. */
  703. PickerConstructor._ = {
  704. /**
  705. * Create a group of nodes. Expects:
  706. * `
  707. {
  708. min: {Integer},
  709. max: {Integer},
  710. i: {Integer},
  711. node: {String},
  712. item: {Function}
  713. }
  714. * `
  715. */
  716. group: function (groupObject) {
  717. var
  718. // Scope for the looped object
  719. loopObjectScope,
  720. // Create the nodes list
  721. nodesList = '',
  722. // The counter starts from the `min`
  723. counter = PickerConstructor._.trigger(groupObject.min, groupObject)
  724. // Loop from the `min` to `max`, incrementing by `i`
  725. for (; counter <= PickerConstructor._.trigger(groupObject.max, groupObject, [counter]); counter += groupObject.i) {
  726. // Trigger the `item` function within scope of the object
  727. loopObjectScope = PickerConstructor._.trigger(groupObject.item, groupObject, [counter])
  728. // Splice the subgroup and create nodes out of the sub nodes
  729. nodesList += PickerConstructor._.node(
  730. groupObject.node,
  731. loopObjectScope[0], // the node
  732. loopObjectScope[1], // the classes
  733. loopObjectScope[2] // the attributes
  734. )
  735. }
  736. // Return the list of nodes
  737. return nodesList
  738. }, //group
  739. /**
  740. * Create a dom node string
  741. */
  742. node: function (wrapper, item, klass, attribute) {
  743. // If the item is false-y, just return an empty string
  744. if (!item) return ''
  745. // If the item is an array, do a join
  746. item = $.isArray(item) ? item.join('') : item
  747. // Check for the class
  748. klass = klass ? ' class="' + klass + '"' : ''
  749. // Check for any attributes
  750. attribute = attribute ? ' ' + attribute : ''
  751. // Return the wrapped item
  752. return '<' + wrapper + klass + attribute + '>' + item + '</' + wrapper + '>'
  753. }, //node
  754. /**
  755. * Lead numbers below 10 with a zero.
  756. */
  757. lead: function (number) {
  758. return (number < 10 ? '0' : '') + number
  759. },
  760. /**
  761. * Trigger a function otherwise return the value.
  762. */
  763. trigger: function (callback, scope, args) {
  764. return typeof callback == 'function' ? callback.apply(scope, args || []) : callback
  765. },
  766. /**
  767. * If the second character is a digit, length is 2 otherwise 1.
  768. */
  769. digits: function (string) {
  770. return (/\d/).test(string[1]) ? 2 : 1
  771. },
  772. /**
  773. * Tell if something is a date object.
  774. */
  775. isDate: function (value) {
  776. return {}.toString.call(value).indexOf('Date') > -1 && this.isInteger(value.getDate())
  777. },
  778. /**
  779. * Tell if something is an integer.
  780. */
  781. isInteger: function (value) {
  782. return {}.toString.call(value).indexOf('Number') > -1 && value % 1 === 0
  783. },
  784. /**
  785. * Create ARIA attribute strings.
  786. */
  787. ariaAttr: ariaAttr
  788. } //PickerConstructor._
  789. /**
  790. * Extend the picker with a component and defaults.
  791. */
  792. PickerConstructor.extend = function (name, Component) {
  793. // Extend jQuery.
  794. $.fn[name] = function (options, action) {
  795. // Grab the component data.
  796. var componentData = this.data(name)
  797. // If the picker is requested, return the data object.
  798. if (options == 'picker') {
  799. return componentData
  800. }
  801. // If the component data exists and `options` is a string, carry out the action.
  802. if (componentData && typeof options == 'string') {
  803. return PickerConstructor._.trigger(componentData[options], componentData, [action])
  804. }
  805. // Otherwise go through each matched element and if the component
  806. // doesn’t exist, create a new picker using `this` element
  807. // and merging the defaults and options with a deep copy.
  808. return this.each(function () {
  809. var $this = $(this)
  810. if (!$this.data(name)) {
  811. new PickerConstructor(this, name, Component, options)
  812. }
  813. })
  814. }
  815. // Set the defaults.
  816. $.fn[name].defaults = Component.defaults
  817. } //PickerConstructor.extend
  818. function aria(element, attribute, value) {
  819. if ($.isPlainObject(attribute)) {
  820. for (var key in attribute) {
  821. ariaSet(element, key, attribute[key])
  822. }
  823. } else {
  824. ariaSet(element, attribute, value)
  825. }
  826. }
  827. function ariaSet(element, attribute, value) {
  828. element.setAttribute(
  829. (attribute == 'role' ? '' : 'aria-') + attribute,
  830. value
  831. )
  832. }
  833. function ariaAttr(attribute, data) {
  834. if (!$.isPlainObject(attribute)) {
  835. attribute = {
  836. attribute: data
  837. }
  838. }
  839. data = ''
  840. for (var key in attribute) {
  841. var attr = (key == 'role' ? '' : 'aria-') + key,
  842. attrVal = attribute[key]
  843. data += attrVal == null ? '' : attr + '="' + attribute[key] + '"'
  844. }
  845. return data
  846. }
  847. // IE8 bug throws an error for activeElements within iframes.
  848. function getActiveElement() {
  849. try {
  850. return document.activeElement
  851. } catch (err) { }
  852. }
  853. // Expose the picker constructor.
  854. return PickerConstructor
  855. }));