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, NAME) {
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 setHTML?
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.Lang.sub( 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.Lang.sub( 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' );
438 Y.log("Setting thumb " + this._key.minEdge + " to " + offset + "px","info","slider");
440 options || (options = {});
441 options.offset = offset;
443 this.fire( 'thumbMove', options );
448 * Dispatches the <code>slideStart</code> event.
450 * @method _onDragStart
451 * @param e {Event} the <code>drag:start</code> event from the thumb
454 _onDragStart: function ( e ) {
456 * Signals the beginning of a thumb drag operation. Payload includes
457 * the thumb's drag:start event.
460 * @param event {Event} The event object for the slideStart with the
461 * following extra properties:
463 * <dt>ddEvent (deprecated)</dt>
464 * <dd><code>drag:start</code> event from the thumb</dd>
465 * <dt>originEvent</dt>
466 * <dd><code>drag:start</code> event from the thumb</dd>
469 this.fire('slideStart', {
470 ddEvent: e, // for backward compatibility
476 * Dispatches the <code>thumbMove</code> event.
479 * @param e {Event} the <code>drag:drag</code> event from the thumb
482 _afterDrag: function ( e ) {
483 var thumbXY = e.info.xy[ this._key.xyIndex ],
484 railXY = e.target.con._regionCache[ this._key.minEdge ];
486 Y.log("Thumb position: " + thumbXY + ", Rail position: " + railXY, "info", "slider");
487 this.fire( 'thumbMove', {
488 offset : (thumbXY - railXY),
489 ddEvent: e, // for backward compatibility
495 * Dispatches the <code>slideEnd</code> event.
498 * @param e {Event} the <code>drag:end</code> event from the thumb
501 _afterDragEnd: function ( e ) {
503 * Signals the end of a thumb drag operation. Payload includes
504 * the thumb's drag:end event.
507 * @param event {Event} The event object for the slideEnd with the
508 * following extra properties:
510 * <dt>ddEvent (deprecated)</dt>
511 * <dd><code>drag:end</code> event from the thumb</dd>
512 * <dt>originEvent</dt>
513 * <dd><code>drag:end</code> event from the thumb</dd>
516 this.fire('slideEnd', {
523 * Locks or unlocks the thumb.
525 * @method _afterDisabledChange
526 * @param e {Event} The disabledChange event object
529 _afterDisabledChange: function ( e ) {
530 this._dd.set( 'lock', e.newVal );
534 * Handles changes to the <code>length</code> attribute. By default, it
535 * triggers an update to the UI.
537 * @method _afterLengthChange
538 * @param e {Event} The lengthChange event object
541 _afterLengthChange: function ( e ) {
542 if ( this.get( 'rendered' ) ) {
543 this._uiSetRailLength( e.newVal );
550 * Synchronizes the DOM state with the attribute settings.
554 syncUI : function () {
555 this._dd.con.resetCache();
557 this._syncThumbPosition();
559 // Forces a reflow of the bounding box to address IE8 inline-block
560 // container not expanding correctly. bug 2527905
561 //this.get('boundingBox').toggleClass('');
562 this.thumb.set('aria-valuemin', this.get('min'));
563 this.thumb.set('aria-valuemax', this.get('max'));
565 this._dd.set('lock', this.get('disabled'));
569 * Stub implementation. Override this (presumably in a class extension) to
570 * ensure the thumb is in the correct position according to the value
574 * @method _syncThumbPosition
577 _syncThumbPosition: function () {},
580 * Validates the axis is "x" or "y" (case insensitive).
581 * Converts to lower case for storage.
584 * @param v {String} proposed value for the axis attribute
585 * @return {String} lowercased first character of the input string
588 _setAxis : function (v) {
589 v = ( v + '' ).toLowerCase();
591 return ( v === 'x' || v === 'y' ) ? v : INVALID_VALUE;
595 * <p>Ensures the stored length value is a string with a quantity and unit.
596 * Unit will be defaulted to "px" if not included. Rejects
597 * values less than or equal to 0 and those that don't at least start with
600 * <p>Currently only pixel lengths are supported.</p>
603 * @param v {String} proposed value for the length attribute
604 * @return {String} the sanitized value
607 _setLength: function ( v ) {
608 v = ( v + '' ).toLowerCase();
610 var length = parseFloat( v, 10 ),
611 units = v.replace( /[\d\.\-]/g, '' ) || this.DEF_UNIT;
613 return length > 0 ? ( length + units ) : INVALID_VALUE;
617 * <p>Defaults the thumbURL attribute according to the current skin, or
618 * "sam" if none can be determined. Horizontal Sliders will have
619 * their <code>thumbUrl</code> attribute set to</p>
620 * <p><code>"/<em>configured</em>/<em>yu</em>i/<em>builddi</em>r/slider-base/assets/skins/sam/thumb-x.png"</code></p>
621 * <p>And vertical thumbs will get</p>
622 * <p><code>"/<em>configured</em>/<em>yui</em>/<em>builddir</em>/slider-base/assets/skins/sam/thumb-y.png"</code></p>
624 * @method _initThumbUrl
627 _initThumbUrl: function () {
628 if (!this.get('thumbUrl')) {
629 var skin = this.getSkinName() || 'sam',
630 base = Y.config.base;
632 // Unfortunate hack to avoid requesting image resources from the
633 // combo service. The combo service does not serve images.
634 if (base.indexOf('http://yui.yahooapis.com/combo') === 0) {
635 base = 'http://yui.yahooapis.com/' + Y.version + '/build/';
638 // <img src="/path/to/build/slider-base/assets/skins/sam/thumb-x.png">
639 this.set('thumbUrl', base + 'slider-base/assets/skins/' +
640 skin + '/thumb-' + this.axis + '.png');
646 * Bounding box template that will contain the Slider's DOM subtree. <span>s are used to support inline-block styling.
648 * @property BOUNDING_TEMPLATE
650 * @default <span></span>
652 BOUNDING_TEMPLATE : '<span></span>',
655 * Content box template that will contain the Slider's rail and thumb.
657 * @property CONTENT_TEMPLATE
659 * @default <span></span>
661 CONTENT_TEMPLATE : '<span></span>',
664 * Rail template that will contain the end caps and the thumb.
665 * {placeholder}s are used for template substitution at render time.
667 * @property RAIL_TEMPLATE
669 * @default <span class="{railClass}"><span class="{railMinCapClass}"></span><span class="{railMaxCapClass}"></span></span>
671 RAIL_TEMPLATE : '<span class="{railClass}">' +
672 '<span class="{railMinCapClass}"></span>' +
673 '<span class="{railMaxCapClass}"></span>' +
677 * Thumb template that will contain the thumb image and shadow. <img>
678 * tags are used instead of background images to avoid a flicker bug in IE.
679 * {placeholder}s are used for template substitution at render time.
681 * @property THUMB_TEMPLATE
683 * @default <span class="{thumbClass}" tabindex="-1"><img src="{thumbShadowUrl}" alt="Slider thumb shadow" class="{thumbShadowClass}"><img src="{thumbImageUrl}" alt="Slider thumb" class="{thumbImageClass}"></span>
685 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"
686 '<img src="{thumbShadowUrl}" ' +
687 'alt="Slider thumb shadow" ' +
688 'class="{thumbShadowClass}">' +
689 '<img src="{thumbImageUrl}" ' +
690 'alt="Slider thumb" ' +
691 'class="{thumbImageClass}">' +
696 // Y.SliderBase static properties
699 * The identity of the widget.
703 * @default 'sliderBase'
711 * Static property used to define the default attribute configuration of
722 * Axis upon which the Slider's thumb moves. "x" for
723 * horizontal, "y" for vertical.
727 * @default "x"
738 * The length of the rail (exclusive of the end caps if positioned by
739 * CSS). This corresponds to the movable range of the thumb.
742 * @type {String | Number} e.g. "200px" or 200
751 * Path to the thumb image. This will be used as both the thumb and
752 * shadow as a sprite. Defaults at render() to thumb-x.png or
753 * thumb-y.png in the skin directory of the current skin.
755 * @attribute thumbUrl
757 * @default thumb-x.png or thumb-y.png in the sam skin directory of the
758 * current build path for Slider
762 validator: Y.Lang.isString
768 }, '3.7.2', {"requires": ["widget", "dd-constrain", "event-key"], "skinnable": true});