3 Copyright 2012 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
7 YUI.add('slider-base', function(Y) {
10 * Create a sliding value range input visualized as a draggable thumb on a
14 * @submodule slider-base
17 var INVALID_VALUE = Y.Attribute.INVALID_VALUE;
20 * Create a slider to represent an input control capable of representing a
21 * series of intermediate states based on the position of the slider's thumb.
22 * These states are typically aligned to a value algorithm whereby the thumb
23 * position corresponds to a given value. Sliders may be oriented vertically or
24 * horizontally, based on the <code>axis</code> configuration.
28 * @param config {Object} Configuration object
31 function SliderBase() {
32 SliderBase.superclass.constructor.apply( this, arguments );
35 Y.SliderBase = Y.extend( SliderBase, Y.Widget, {
40 * Construction logic executed during Slider instantiation.
45 initializer : function () {
47 * The configured axis, stored for fast lookup since it's a writeOnce
48 * attribute. This is for use by extension classes. For
49 * implementation code, use <code>get( "axis" )</code> for
50 * authoritative source. Never write to this property.
56 this.axis = this.get( 'axis' );
59 * Cached fast access map for DOM properties and attributes that
60 * pertain to accessing dimensional or positioning information
61 * according to the Slider's axis (e.g. "height" vs.
62 * "width"). Extension classes should add to this collection
63 * for axis related strings if necessary.
70 dim : ( this.axis === 'y' ) ? 'height' : 'width',
71 minEdge: ( this.axis === 'y' ) ? 'top' : 'left',
72 maxEdge: ( this.axis === 'y' ) ? 'bottom' : 'right',
73 xyIndex: ( this.axis === 'y' ) ? 1 : 0
77 * Signals that the thumb has moved. Payload includes the thumb's
78 * pixel offset from the top/left edge of the rail, and if triggered by
79 * dragging the thumb, the <code>drag:drag</code> event.
82 * @param event {Event} The event object for the thumbMove with the
83 * following extra properties:
86 * <dd>Pixel offset from top/left of the slider to the new
88 * <dt>ddEvent (deprecated)</dt>
89 * <dd><code>drag:drag</code> event from the thumb</dd>
90 * <dt>originEvent</dt>
91 * <dd><code>drag:drag</code> event from the thumb</dd>
94 this.publish( 'thumbMove', {
95 defaultFn: this._defThumbMoveFn,
101 * Create the DOM structure for the Slider.
106 renderUI : function () {
107 var contentBox = this.get( 'contentBox' );
110 * The Node instance of the Slider's rail element. Do not write to
116 this.rail = this.renderRail();
118 this._uiSetRailLength( this.get( 'length' ) );
121 * The Node instance of the Slider's thumb element. Do not write to
127 this.thumb = this.renderThumb();
129 this.rail.appendChild( this.thumb );
130 // @TODO: insert( contentBox, 'replace' ) or setContent?
131 contentBox.appendChild( this.rail );
133 // <span class="yui3-slider-x">
134 contentBox.addClass( this.getClassName( this.axis ) );
138 * Creates the Slider rail DOM subtree for insertion into the Slider's
139 * <code>contentBox</code>. Override this method if you want to provide
140 * the rail element (presumably from existing markup).
143 * @return {Node} the rail node subtree
145 renderRail: function () {
146 var minCapClass = this.getClassName( 'rail', 'cap', this._key.minEdge ),
147 maxCapClass = this.getClassName( 'rail', 'cap', this._key.maxEdge );
149 return Y.Node.create(
150 Y.substitute( this.RAIL_TEMPLATE, {
151 railClass : this.getClassName( 'rail' ),
152 railMinCapClass: minCapClass,
153 railMaxCapClass: maxCapClass
158 * Sets the rail length according to the <code>length</code> attribute.
160 * @method _uiSetRailLength
161 * @param length {String} the length to apply to the rail style
164 _uiSetRailLength: function ( length ) {
165 this.rail.setStyle( this._key.dim, length );
169 * Creates the Slider thumb DOM subtree for insertion into the Slider's
170 * rail. Override this method if you want to provide the thumb element
171 * (presumably from existing markup).
173 * @method renderThumb
174 * @return {Node} the thumb node subtree
176 renderThumb: function () {
177 this._initThumbUrl();
179 var imageUrl = this.get( 'thumbUrl' );
181 return Y.Node.create(
182 Y.substitute( this.THUMB_TEMPLATE, {
183 thumbClass : this.getClassName( 'thumb' ),
184 thumbShadowClass: this.getClassName( 'thumb', 'shadow' ),
185 thumbImageClass : this.getClassName( 'thumb', 'image' ),
186 thumbShadowUrl : imageUrl,
187 thumbImageUrl : imageUrl,
188 thumbAriaLabelId: this.getClassName( 'label', Y.guid()) // get unique id for specifying a label for ARIA
193 * Gives focus to the thumb enabling keyboard access after clicking thumb
195 * @method _onThumbClick
198 _onThumbClick : function(e){
204 * Creates the Y.DD.Drag instance used to handle the thumb movement and
205 * binds Slider interaction to the configured value model.
210 bindUI : function () {
212 // Begin keyboard listeners ///////////////////////////////
213 var boundingBox = this.get("boundingBox"), //Y.one('body'),
214 // Looking for a key event which will fire continously across browsers while the key is held down.
215 keyEvent = (!Y.UA.opera) ? "down:" : "press:",
216 // 38, 40 = arrow up/down, 33, 34 = page up/down, 35 , 36 = end/home
217 keyEventSpec = keyEvent + "38,40,33,34,35,36",
218 // 37 , 39 = arrow left/right
219 keyLeftRightSpec = keyEvent + "37,39",
220 // 37 , 39 = arrow left/right + meta (command/apple key) for mac
221 keyLeftRightSpecMeta = keyEvent + "37+meta,39+meta";
223 boundingBox.on("key", this._onDirectionKey, keyEventSpec, this);
224 boundingBox.on("key", this._onLeftRightKey, keyLeftRightSpec, this);
225 boundingBox.on("key", this._onLeftRightKeyMeta, keyLeftRightSpecMeta, this);
226 // End keyboard listeners //////////////////////////////////
228 this.thumb.on('click', this._onThumbClick, this);
232 this._bindValueLogic();
234 this.after( 'disabledChange', this._afterDisabledChange );
235 this.after( 'lengthChange', this._afterLengthChange );
240 * increments Slider value by a minor increment
245 _incrMinor : function(){
246 this.set('value', (this.get('value') + this.get('minorStep')));
250 * decrements Slider value by a minor increment
255 _decrMinor : function(){
256 this.set('value', (this.get('value') - this.get('minorStep')));
260 * increments Slider value by a major increment
265 _incrMajor : function(){
266 this.set('value', (this.get('value') + this.get('majorStep')));
270 * decrements Slider value by a major increment
275 _decrMajor : function(){
276 this.set('value', (this.get('value') - this.get('majorStep')));
280 * sets the Slider value to the min value.
285 _setToMin : function(e){
286 this.set('value', this.get('min'));
290 * sets the Slider value to the max value.
295 _setToMax : function(e){
296 this.set('value', this.get('max'));
300 * sets the Slider's value in response to key events.
301 * Left and right keys are in a separate method
302 * in case an implementation wants to increment values
303 * but needs left and right arrow keys for other purposes.
305 * @method _onDirectionKey
306 * @param e {Event} the key event
309 _onDirectionKey : function(e) {
311 if(this.get('disabled') === false){
312 switch (e.charCode) {
328 case 34: // page down
336 * sets the Slider's value in response to left or right key events
338 * @method _onLeftRightKey
339 * @param e {Event} the key event
342 _onLeftRightKey : function(e) {
344 if(this.get('disabled') === false){
345 switch (e.charCode) {
357 * sets the Slider's value in response to left or right key events when a meta (mac command/apple) key is also pressed
359 * @method _onLeftRightKeyMeta
360 * @param e {Event} the key event
363 _onLeftRightKeyMeta : function(e) {
365 if(this.get('disabled') === false){
366 switch (e.charCode) {
367 case 37: // left + meta
370 case 39: // right + meta
382 * Makes the thumb draggable and constrains it to the rail.
384 * @method _bindThumbDD
387 _bindThumbDD: function () {
388 var config = { constrain: this.rail };
390 // { constrain: rail, stickX: true }
391 config[ 'stick' + this.axis.toUpperCase() ] = true;
394 * The DD.Drag instance linked to the thumb node.
400 this._dd = new Y.DD.Drag( {
404 'drag:start': Y.bind( this._onDragStart, this )
407 'drag:drag': Y.bind( this._afterDrag, this ),
408 'drag:end' : Y.bind( this._afterDragEnd, this )
412 // Constrain the thumb to the rail
413 this._dd.plug( Y.Plugin.DDConstrained, config );
417 * Stub implementation. Override this (presumably in a class extension) to
418 * initialize any value logic that depends on the presence of the Drag
421 * @method _bindValueLogic
424 _bindValueLogic: function () {},
427 * Moves the thumb to pixel offset position along the rail.
429 * @method _uiMoveThumb
430 * @param offset {Number} the pixel offset to set as left or top style
431 * @param [options] {Object} Details to send with the `thumbMove` event
434 _uiMoveThumb: function ( offset, options ) {
436 this.thumb.setStyle( this._key.minEdge, offset + 'px' );
439 options || (options = {});
440 options.offset = offset;
442 this.fire( 'thumbMove', options );
447 * Dispatches the <code>slideStart</code> event.
449 * @method _onDragStart
450 * @param e {Event} the <code>drag:start</code> event from the thumb
453 _onDragStart: function ( e ) {
455 * Signals the beginning of a thumb drag operation. Payload includes
456 * the thumb's drag:start event.
459 * @param event {Event} The event object for the slideStart with the
460 * following extra properties:
462 * <dt>ddEvent (deprecated)</dt>
463 * <dd><code>drag:start</code> event from the thumb</dd>
464 * <dt>originEvent</dt>
465 * <dd><code>drag:start</code> event from the thumb</dd>
468 this.fire('slideStart', {
469 ddEvent: e, // for backward compatibility
475 * Dispatches the <code>thumbMove</code> event.
478 * @param e {Event} the <code>drag:drag</code> event from the thumb
481 _afterDrag: function ( e ) {
482 var thumbXY = e.info.xy[ this._key.xyIndex ],
483 railXY = e.target.con._regionCache[ this._key.minEdge ];
485 this.fire( 'thumbMove', {
486 offset : (thumbXY - railXY),
487 ddEvent: e, // for backward compatibility
493 * Dispatches the <code>slideEnd</code> event.
496 * @param e {Event} the <code>drag:end</code> event from the thumb
499 _afterDragEnd: function ( e ) {
501 * Signals the end of a thumb drag operation. Payload includes
502 * the thumb's drag:end event.
505 * @param event {Event} The event object for the slideEnd with the
506 * following extra properties:
508 * <dt>ddEvent (deprecated)</dt>
509 * <dd><code>drag:end</code> event from the thumb</dd>
510 * <dt>originEvent</dt>
511 * <dd><code>drag:end</code> event from the thumb</dd>
514 this.fire('slideEnd', {
521 * Locks or unlocks the thumb.
523 * @method _afterDisabledChange
524 * @param e {Event} The disabledChange event object
527 _afterDisabledChange: function ( e ) {
528 this._dd.set( 'lock', e.newVal );
532 * Handles changes to the <code>length</code> attribute. By default, it
533 * triggers an update to the UI.
535 * @method _afterLengthChange
536 * @param e {Event} The lengthChange event object
539 _afterLengthChange: function ( e ) {
540 if ( this.get( 'rendered' ) ) {
541 this._uiSetRailLength( e.newVal );
548 * Synchronizes the DOM state with the attribute settings.
552 syncUI : function () {
553 this._dd.con.resetCache();
555 this._syncThumbPosition();
557 // Forces a reflow of the bounding box to address IE8 inline-block
558 // container not expanding correctly. bug 2527905
559 //this.get('boundingBox').toggleClass('');
560 this.thumb.set('aria-valuemin', this.get('min'));
561 this.thumb.set('aria-valuemax', this.get('max'));
565 * Stub implementation. Override this (presumably in a class extension) to
566 * ensure the thumb is in the correct position according to the value
570 * @method _syncThumbPosition
573 _syncThumbPosition: function () {},
576 * Validates the axis is "x" or "y" (case insensitive).
577 * Converts to lower case for storage.
580 * @param v {String} proposed value for the axis attribute
581 * @return {String} lowercased first character of the input string
584 _setAxis : function (v) {
585 v = ( v + '' ).toLowerCase();
587 return ( v === 'x' || v === 'y' ) ? v : INVALID_VALUE;
591 * <p>Ensures the stored length value is a string with a quantity and unit.
592 * Unit will be defaulted to "px" if not included. Rejects
593 * values less than or equal to 0 and those that don't at least start with
596 * <p>Currently only pixel lengths are supported.</p>
599 * @param v {String} proposed value for the length attribute
600 * @return {String} the sanitized value
603 _setLength: function ( v ) {
604 v = ( v + '' ).toLowerCase();
606 var length = parseFloat( v, 10 ),
607 units = v.replace( /[\d\.\-]/g, '' ) || this.DEF_UNIT;
609 return length > 0 ? ( length + units ) : INVALID_VALUE;
613 * <p>Defaults the thumbURL attribute according to the current skin, or
614 * "sam" if none can be determined. Horizontal Sliders will have
615 * their <code>thumbUrl</code> attribute set to</p>
616 * <p><code>"/<em>configured</em>/<em>yu</em>i/<em>builddi</em>r/slider-base/assets/skins/sam/thumb-x.png"</code></p>
617 * <p>And vertical thumbs will get</p>
618 * <p><code>"/<em>configured</em>/<em>yui</em>/<em>builddir</em>/slider-base/assets/skins/sam/thumb-y.png"</code></p>
620 * @method _initThumbUrl
623 _initThumbUrl: function () {
624 if (!this.get('thumbUrl')) {
625 var skin = this.getSkinName() || 'sam',
626 base = Y.config.base;
628 // Unfortunate hack to avoid requesting image resources from the
629 // combo service. The combo service does not serve images.
630 if (base.indexOf('http://yui.yahooapis.com/combo') === 0) {
631 base = 'http://yui.yahooapis.com/' + Y.version + '/build/';
634 // <img src="/path/to/build/slider-base/assets/skins/sam/thumb-x.png">
635 this.set('thumbUrl', base + 'slider-base/assets/skins/' +
636 skin + '/thumb-' + this.axis + '.png');
642 * Bounding box template that will contain the Slider's DOM subtree. <span>s are used to support inline-block styling.
644 * @property BOUNDING_TEMPLATE
646 * @default <span></span>
648 BOUNDING_TEMPLATE : '<span></span>',
651 * Content box template that will contain the Slider's rail and thumb.
653 * @property CONTENT_TEMPLATE
655 * @default <span></span>
657 CONTENT_TEMPLATE : '<span></span>',
660 * Rail template that will contain the end caps and the thumb.
661 * {placeholder}s are used for template substitution at render time.
663 * @property RAIL_TEMPLATE
665 * @default <span class="{railClass}"><span class="{railMinCapClass}"></span><span class="{railMaxCapClass}"></span></span>
667 RAIL_TEMPLATE : '<span class="{railClass}">' +
668 '<span class="{railMinCapClass}"></span>' +
669 '<span class="{railMaxCapClass}"></span>' +
673 * Thumb template that will contain the thumb image and shadow. <img>
674 * tags are used instead of background images to avoid a flicker bug in IE.
675 * {placeholder}s are used for template substitution at render time.
677 * @property THUMB_TEMPLATE
679 * @default <span class="{thumbClass}" tabindex="-1"><img src="{thumbShadowUrl}" alt="Slider thumb shadow" class="{thumbShadowClass}"><img src="{thumbImageUrl}" alt="Slider thumb" class="{thumbImageClass}"></span>
681 THUMB_TEMPLATE : '<span class="{thumbClass}" aria-labelledby="{thumbAriaLabelId}" aria-valuetext="" aria-valuemax="" aria-valuemin="" aria-valuenow="" role="slider" tabindex="0">' + // keyboard access jeff tabindex="-1"
682 '<img src="{thumbShadowUrl}" ' +
683 'alt="Slider thumb shadow" ' +
684 'class="{thumbShadowClass}">' +
685 '<img src="{thumbImageUrl}" ' +
686 'alt="Slider thumb" ' +
687 'class="{thumbImageClass}">' +
692 // Y.SliderBase static properties
695 * The identity of the widget.
699 * @default 'sliderBase'
707 * Static property used to define the default attribute configuration of
718 * Axis upon which the Slider's thumb moves. "x" for
719 * horizontal, "y" for vertical.
723 * @default "x"
734 * The length of the rail (exclusive of the end caps if positioned by
735 * CSS). This corresponds to the movable range of the thumb.
738 * @type {String | Number} e.g. "200px" or 200
747 * Path to the thumb image. This will be used as both the thumb and
748 * shadow as a sprite. Defaults at render() to thumb-x.png or
749 * thumb-y.png in the skin directory of the current skin.
751 * @attribute thumbUrl
753 * @default thumb-x.png or thumb-y.png in the sam skin directory of the
754 * current build path for Slider
758 validator: Y.Lang.isString
765 }, '3.5.0' ,{requires:['widget', 'substitute', 'dd-constrain', 'event-key']});