Нет описания

picker.js 39KB

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