UNPKG

@angular/material

Version:
1,304 lines 59.9 kB
import * as tslib_1 from "tslib"; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Attribute, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, Directive, ElementRef, EventEmitter, Inject, InjectionToken, Input, NgModule, Optional, Output, Renderer2, Self, ViewChild, ViewEncapsulation, isDevMode } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FocusKeyManager } from '@angular/cdk/a11y'; import { Directionality } from '@angular/cdk/bidi'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { SelectionModel } from '@angular/cdk/collections'; import { DOWN_ARROW, END, ENTER, HOME, SPACE, UP_ARROW } from '@angular/cdk/keycodes'; import { ConnectedOverlayDirective, Overlay, OverlayModule, ViewportRuler } from '@angular/cdk/overlay'; import { Platform } from '@angular/cdk/platform'; import { filter, startWith } from '@angular/cdk/rxjs'; import { FormGroupDirective, NgControl, NgForm } from '@angular/forms'; import { MD_PLACEHOLDER_GLOBAL_OPTIONS, MdCommonModule, MdOptgroup, MdOption, MdOptionModule, mixinColor, mixinDisabled, mixinTabIndex } from '@angular/material/core'; import { merge } from 'rxjs/observable/merge'; import { Subscription } from 'rxjs/Subscription'; import { animate, state, style, transition, trigger } from '@angular/animations'; /** * This animation shrinks the placeholder text to 75% of its normal size and translates * it to either the top left corner (ltr) or top right corner (rtl) of the trigger, * depending on the text direction of the application. */ var transformPlaceholder = trigger('transformPlaceholder', [ state('floating-ltr', style({ top: '-22px', left: '-2px', transform: 'scale(0.75)' })), state('floating-rtl', style({ top: '-22px', left: '2px', transform: 'scale(0.75)' })), transition('* => *', animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')) ]); /** * This animation transforms the select's overlay panel on and off the page. * * When the panel is attached to the DOM, it expands its width by the amount of padding, scales it * up to 100% on the Y axis, fades in its border, and translates slightly up and to the * side to ensure the option text correctly overlaps the trigger text. * * When the panel is removed from the DOM, it simply fades out linearly. */ var transformPanel = trigger('transformPanel', [ state('showing', style({ opacity: 1, minWidth: 'calc(100% + 32px)', transform: 'scaleY(1)' })), state('showing-multiple', style({ opacity: 1, minWidth: 'calc(100% + 64px)', transform: 'scaleY(1)' })), transition('void => *', [ style({ opacity: 0, minWidth: '100%', transform: 'scaleY(0)' }), animate('150ms cubic-bezier(0.25, 0.8, 0.25, 1)') ]), transition('* => void', [ animate('250ms 100ms linear', style({ opacity: 0 })) ]) ]); /** * This animation fades in the background color and text content of the * select's options. It is time delayed to occur 100ms after the overlay * panel has transformed in. */ var fadeInContent = trigger('fadeInContent', [ state('showing', style({ opacity: 1 })), transition('void => showing', [ style({ opacity: 0 }), animate('150ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)') ]) ]); /** * Returns an exception to be thrown when attempting to change a select's `multiple` option * after initialization. * \@docs-private * @return {?} */ function getMdSelectDynamicMultipleError() { return Error('Cannot change `multiple` mode of select after initialization.'); } /** * Returns an exception to be thrown when attempting to assign a non-array value to a select * in `multiple` mode. Note that `undefined` and `null` are still valid values to allow for * resetting the value. * \@docs-private * @return {?} */ function getMdSelectNonArrayValueError() { return Error('Cannot assign truthy non-array value to select in `multiple` mode.'); } /** * Returns an exception to be thrown when assigning a non-function value to the comparator * used to determine if a value corresponds to an option. Note that whether the function * actually takes two values and returns a boolean is not checked. * @return {?} */ function getMdSelectNonFunctionValueError() { return Error('Cannot assign a non-function value to `compareWith`.'); } /** * The fixed height of every option element (option, group header etc.). */ var SELECT_ITEM_HEIGHT = 48; /** * The max height of the select's overlay panel */ var SELECT_PANEL_MAX_HEIGHT = 256; /** * The max number of options visible at once in the select panel. */ var SELECT_MAX_OPTIONS_DISPLAYED = Math.floor(SELECT_PANEL_MAX_HEIGHT / SELECT_ITEM_HEIGHT); /** * The fixed height of the select's trigger element. */ var SELECT_TRIGGER_HEIGHT = 30; /** * Must adjust for the difference in height between the option and the trigger, * so the text will align on the y axis. */ var SELECT_OPTION_HEIGHT_ADJUSTMENT = (SELECT_ITEM_HEIGHT - SELECT_TRIGGER_HEIGHT) / 2; /** * The panel's padding on the x-axis */ var SELECT_PANEL_PADDING_X = 16; /** * The panel's x axis padding if it is indented (e.g. there is an option group). */ var SELECT_PANEL_INDENT_PADDING_X = SELECT_PANEL_PADDING_X * 2; /** * Distance between the panel edge and the option text in * multi-selection mode. * * (SELECT_PADDING * 1.75) + 20 = 48 * The padding is multiplied by 1.75 because the checkbox's margin is half the padding, and * the browser adds ~4px, because we're using inline elements. * The checkbox width is 20px. */ var SELECT_MULTIPLE_PANEL_PADDING_X = SELECT_PANEL_PADDING_X * 1.75 + 20; /** * The panel's padding on the y-axis. This padding indicates there are more * options available if you scroll. */ var SELECT_PANEL_PADDING_Y = 16; /** * The select panel will only "fit" inside the viewport if it is positioned at * this value or more away from the viewport boundary. */ var SELECT_PANEL_VIEWPORT_PADDING = 8; /** * Default minimum width of the trigger based on the CSS. * Used as a fallback for server-side rendering. * \@docs-private */ var SELECT_TRIGGER_MIN_WIDTH = 112; /** * Injection token that determines the scroll handling while a select is open. */ var MD_SELECT_SCROLL_STRATEGY = new InjectionToken('md-select-scroll-strategy'); /** * \@docs-private * @param {?} overlay * @return {?} */ function MD_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY(overlay) { return function () { return overlay.scrollStrategies.reposition(); }; } /** * \@docs-private */ var MD_SELECT_SCROLL_STRATEGY_PROVIDER = { provide: MD_SELECT_SCROLL_STRATEGY, deps: [Overlay], useFactory: MD_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY, }; /** * Change event object that is emitted when the select value has changed. */ var MdSelectChange = (function () { /** * @param {?} source * @param {?} value */ function MdSelectChange(source, value) { this.source = source; this.value = value; } return MdSelectChange; }()); /** * \@docs-private */ var MdSelectBase = (function () { /** * @param {?} _renderer * @param {?} _elementRef */ function MdSelectBase(_renderer, _elementRef) { this._renderer = _renderer; this._elementRef = _elementRef; } return MdSelectBase; }()); var _MdSelectMixinBase = mixinTabIndex(mixinColor(mixinDisabled(MdSelectBase), 'primary')); /** * Allows the user to customize the trigger that is displayed when the select has a value. */ var MdSelectTrigger = (function () { function MdSelectTrigger() { } return MdSelectTrigger; }()); MdSelectTrigger.decorators = [ { type: Directive, args: [{ selector: 'md-select-trigger, mat-select-trigger' },] }, ]; /** * @nocollapse */ MdSelectTrigger.ctorParameters = function () { return []; }; var MdSelect = (function (_super) { tslib_1.__extends(MdSelect, _super); /** * @param {?} _viewportRuler * @param {?} _changeDetectorRef * @param {?} _platform * @param {?} renderer * @param {?} elementRef * @param {?} _dir * @param {?} _parentForm * @param {?} _parentFormGroup * @param {?} _control * @param {?} tabIndex * @param {?} placeholderOptions * @param {?} _scrollStrategyFactory */ function MdSelect(_viewportRuler, _changeDetectorRef, _platform, renderer, elementRef, _dir, _parentForm, _parentFormGroup, _control, tabIndex, placeholderOptions, _scrollStrategyFactory) { var _this = _super.call(this, renderer, elementRef) || this; _this._viewportRuler = _viewportRuler; _this._changeDetectorRef = _changeDetectorRef; _this._platform = _platform; _this._dir = _dir; _this._parentForm = _parentForm; _this._parentFormGroup = _parentFormGroup; _this._control = _control; _this._scrollStrategyFactory = _scrollStrategyFactory; /** * Whether or not the overlay panel is open. */ _this._panelOpen = false; /** * Subscriptions to option events. */ _this._optionSubscription = Subscription.EMPTY; /** * Subscription to changes in the option list. */ _this._changeSubscription = Subscription.EMPTY; /** * Subscription to tab events while overlay is focused. */ _this._tabSubscription = Subscription.EMPTY; /** * Whether filling out the select is required in the form. */ _this._required = false; /** * The scroll position of the overlay panel, calculated to center the selected option. */ _this._scrollTop = 0; /** * Whether the component is in multiple selection mode. */ _this._multiple = false; /** * Comparison function to specify which option is displayed. Defaults to object equality. */ _this._compareWith = function (o1, o2) { return o1 === o2; }; /** * The animation state of the placeholder. */ _this._placeholderState = ''; /** * View -> model callback called when value changes */ _this._onChange = function () { }; /** * View -> model callback called when select has been touched */ _this._onTouched = function () { }; /** * The IDs of child options to be passed to the aria-owns attribute. */ _this._optionIds = ''; /** * The value of the select panel's transform-origin property. */ _this._transformOrigin = 'top'; /** * Whether the panel's animation is done. */ _this._panelDoneAnimating = false; /** * Strategy that will be used to handle scrolling while the select panel is open. */ _this._scrollStrategy = _this._scrollStrategyFactory(); /** * The y-offset of the overlay panel in relation to the trigger's top start corner. * This must be adjusted to align the selected option text over the trigger text. * when the panel opens. Will change based on the y-position of the selected option. */ _this._offsetY = 0; /** * This position config ensures that the top "start" corner of the overlay * is aligned with with the top "start" of the origin by default (overlapping * the trigger completely). If the panel cannot fit below the trigger, it * will fall back to a position above the trigger. */ _this._positions = [ { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top', }, { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'bottom', }, ]; _this._disableRipple = false; /** * Aria label of the select. If not specified, the placeholder will be used as label. */ _this.ariaLabel = ''; /** * Input that can be used to specify the `aria-labelledby` attribute. */ _this.ariaLabelledby = ''; /** * Event emitted when the select has been opened. */ _this.onOpen = new EventEmitter(); /** * Event emitted when the select has been closed. */ _this.onClose = new EventEmitter(); /** * Event emitted when the selected value has been changed by the user. */ _this.change = new EventEmitter(); /** * Event that emits whenever the raw value of the select changes. This is here primarily * to facilitate the two-way binding for the `value` input. * \@docs-private */ _this.valueChange = new EventEmitter(); if (_this._control) { _this._control.valueAccessor = _this; } _this.tabIndex = parseInt(tabIndex) || 0; _this._placeholderOptions = placeholderOptions ? placeholderOptions : {}; _this.floatPlaceholder = _this._placeholderOptions.float || 'auto'; return _this; } Object.defineProperty(MdSelect.prototype, "placeholder", { /** * Placeholder to be shown if no value has been selected. * @return {?} */ get: function () { return this._placeholder; }, /** * @param {?} value * @return {?} */ set: function (value) { var _this = this; this._placeholder = value; // Must wait to record the trigger width to ensure placeholder width is included. Promise.resolve(null).then(function () { return _this._setTriggerWidth(); }); }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "required", { /** * Whether the component is required. * @return {?} */ get: function () { return this._required; }, /** * @param {?} value * @return {?} */ set: function (value) { this._required = coerceBooleanProperty(value); }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "multiple", { /** * Whether the user should be allowed to select multiple options. * @return {?} */ get: function () { return this._multiple; }, /** * @param {?} value * @return {?} */ set: function (value) { if (this._selectionModel) { throw getMdSelectDynamicMultipleError(); } this._multiple = coerceBooleanProperty(value); }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "compareWith", { /** * A function to compare the option values with the selected values. The first argument * is a value from an option. The second is a value from the selection. A boolean * should be returned. * @return {?} */ get: function () { return this._compareWith; }, /** * @param {?} fn * @return {?} */ set: function (fn) { if (typeof fn !== 'function') { throw getMdSelectNonFunctionValueError(); } this._compareWith = fn; if (this._selectionModel) { // A different comparator means the selection could change. this._initializeSelection(); } }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "floatPlaceholder", { /** * Whether to float the placeholder text. * @return {?} */ get: function () { return this._floatPlaceholder; }, /** * @param {?} value * @return {?} */ set: function (value) { this._floatPlaceholder = value || this._placeholderOptions.float || 'auto'; }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "value", { /** * Value of the select control. * @return {?} */ get: function () { return this._value; }, /** * @param {?} newValue * @return {?} */ set: function (newValue) { this.writeValue(newValue); this._value = newValue; }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "disableRipple", { /** * Whether ripples for all options in the select are disabled. * @return {?} */ get: function () { return this._disableRipple; }, /** * @param {?} value * @return {?} */ set: function (value) { this._disableRipple = coerceBooleanProperty(value); this._setOptionDisableRipple(); }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "optionSelectionChanges", { /** * Combined stream of all of the child options' change events. * @return {?} */ get: function () { return merge.apply(void 0, this.options.map(function (option) { return option.onSelectionChange; })); }, enumerable: true, configurable: true }); /** * @return {?} */ MdSelect.prototype.ngOnInit = function () { this._selectionModel = new SelectionModel(this.multiple, undefined, false); }; /** * @return {?} */ MdSelect.prototype.ngAfterContentInit = function () { var _this = this; this._initKeyManager(); this._changeSubscription = startWith.call(this.options.changes, null).subscribe(function () { _this._resetOptions(); _this._initializeSelection(); }); }; /** * @return {?} */ MdSelect.prototype.ngOnDestroy = function () { this._dropSubscriptions(); this._changeSubscription.unsubscribe(); this._tabSubscription.unsubscribe(); }; /** * Toggles the overlay panel open or closed. * @return {?} */ MdSelect.prototype.toggle = function () { this.panelOpen ? this.close() : this.open(); }; /** * Opens the overlay panel. * @return {?} */ MdSelect.prototype.open = function () { if (this.disabled || !this.options.length) { return; } if (!this._triggerWidth) { this._setTriggerWidth(); } this._calculateOverlayPosition(); this._placeholderState = this._floatPlaceholderState(); this._panelOpen = true; this._changeDetectorRef.markForCheck(); }; /** * Closes the overlay panel and focuses the host element. * @return {?} */ MdSelect.prototype.close = function () { if (this._panelOpen) { this._panelOpen = false; if (this._selectionModel.isEmpty()) { this._placeholderState = ''; } this._changeDetectorRef.markForCheck(); this.focus(); } }; /** * Sets the select's value. Part of the ControlValueAccessor interface * required to integrate with Angular's core forms API. * * @param {?} value New value to be written to the model. * @return {?} */ MdSelect.prototype.writeValue = function (value) { if (this.options) { this._setSelectionByValue(value); } }; /** * Saves a callback function to be invoked when the select's value * changes from user input. Part of the ControlValueAccessor interface * required to integrate with Angular's core forms API. * * @param {?} fn Callback to be triggered when the value changes. * @return {?} */ MdSelect.prototype.registerOnChange = function (fn) { this._onChange = fn; }; /** * Saves a callback function to be invoked when the select is blurred * by the user. Part of the ControlValueAccessor interface required * to integrate with Angular's core forms API. * * @param {?} fn Callback to be triggered when the component has been touched. * @return {?} */ MdSelect.prototype.registerOnTouched = function (fn) { this._onTouched = fn; }; /** * Disables the select. Part of the ControlValueAccessor interface required * to integrate with Angular's core forms API. * * @param {?} isDisabled Sets whether the component is disabled. * @return {?} */ MdSelect.prototype.setDisabledState = function (isDisabled) { this.disabled = isDisabled; this._changeDetectorRef.markForCheck(); }; Object.defineProperty(MdSelect.prototype, "panelOpen", { /** * Whether or not the overlay panel is open. * @return {?} */ get: function () { return this._panelOpen; }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "selected", { /** * The currently selected option. * @return {?} */ get: function () { return this.multiple ? this._selectionModel.selected : this._selectionModel.selected[0]; }, enumerable: true, configurable: true }); Object.defineProperty(MdSelect.prototype, "triggerValue", { /** * The value displayed in the trigger. * @return {?} */ get: function () { if (!this._selectionModel || this._selectionModel.isEmpty()) { return ''; } if (this._multiple) { var /** @type {?} */ selectedOptions = this._selectionModel.selected.map(function (option) { return option.viewValue; }); if (this._isRtl()) { selectedOptions.reverse(); } // TODO(crisbeto): delimiter should be configurable for proper localization. return selectedOptions.join(', '); } return this._selectionModel.selected[0].viewValue; }, enumerable: true, configurable: true }); /** * Whether the element is in RTL mode. * @return {?} */ MdSelect.prototype._isRtl = function () { return this._dir ? this._dir.value === 'rtl' : false; }; /** * Sets the width of the trigger element. This is necessary to match * the overlay width to the trigger width. * @return {?} */ MdSelect.prototype._setTriggerWidth = function () { this._triggerWidth = this._platform.isBrowser ? this._getTriggerRect().width : SELECT_TRIGGER_MIN_WIDTH; this._changeDetectorRef.markForCheck(); }; /** * Handles the keyboard interactions of a closed select. * @param {?} event * @return {?} */ MdSelect.prototype._handleClosedKeydown = function (event) { if (!this.disabled) { if (event.keyCode === ENTER || event.keyCode === SPACE) { event.preventDefault(); // prevents the page from scrolling down when pressing space this.open(); } else if (event.keyCode === UP_ARROW || event.keyCode === DOWN_ARROW) { this._handleArrowKey(event); } } }; /** * Handles keypresses inside the panel. * @param {?} event * @return {?} */ MdSelect.prototype._handlePanelKeydown = function (event) { if (event.keyCode === HOME || event.keyCode === END) { event.preventDefault(); event.keyCode === HOME ? this._keyManager.setFirstItemActive() : this._keyManager.setLastItemActive(); } else { this._keyManager.onKeydown(event); } }; /** * When the panel element is finished transforming in (though not fading in), it * emits an event and focuses an option if the panel is open. * @return {?} */ MdSelect.prototype._onPanelDone = function () { if (this.panelOpen) { this._focusCorrectOption(); this.onOpen.emit(); } else { this.onClose.emit(); this._panelDoneAnimating = false; this.overlayDir.offsetX = 0; this._changeDetectorRef.markForCheck(); } }; /** * When the panel content is done fading in, the _panelDoneAnimating property is * set so the proper class can be added to the panel. * @return {?} */ MdSelect.prototype._onFadeInDone = function () { this._panelDoneAnimating = this.panelOpen; this._changeDetectorRef.markForCheck(); }; /** * Calls the touched callback only if the panel is closed. Otherwise, the trigger will * "blur" to the panel when it opens, causing a false positive. * @return {?} */ MdSelect.prototype._onBlur = function () { if (!this.disabled && !this.panelOpen) { this._onTouched(); this._changeDetectorRef.markForCheck(); } }; /** * Callback that is invoked when the overlay panel has been attached. * @return {?} */ MdSelect.prototype._onAttached = function () { this._calculateOverlayOffsetX(); this._setScrollTop(); }; /** * Whether the select has a value. * @return {?} */ MdSelect.prototype._hasValue = function () { return this._selectionModel && this._selectionModel.hasValue(); }; /** * Whether the select is in an error state. * @return {?} */ MdSelect.prototype._isErrorState = function () { var /** @type {?} */ isInvalid = this._control && this._control.invalid; var /** @type {?} */ isTouched = this._control && this._control.touched; var /** @type {?} */ isSubmitted = (this._parentFormGroup && this._parentFormGroup.submitted) || (this._parentForm && this._parentForm.submitted); return !!(isInvalid && (isTouched || isSubmitted)); }; /** * Sets the scroll position of the scroll container. This must be called after * the overlay pane is attached or the scroll container element will not yet be * present in the DOM. * @return {?} */ MdSelect.prototype._setScrollTop = function () { var /** @type {?} */ scrollContainer = this.overlayDir.overlayRef.overlayElement.querySelector('.mat-select-panel'); /** @type {?} */ ((scrollContainer)).scrollTop = this._scrollTop; }; /** * @return {?} */ MdSelect.prototype._initializeSelection = function () { var _this = this; // Defer setting the value in order to avoid the "Expression // has changed after it was checked" errors from Angular. Promise.resolve().then(function () { _this._setSelectionByValue(_this._control ? _this._control.value : _this._value); }); }; /** * Sets the selected option based on a value. If no option can be * found with the designated value, the select trigger is cleared. * @param {?} value * @param {?=} isUserInput * @return {?} */ MdSelect.prototype._setSelectionByValue = function (value, isUserInput) { var _this = this; if (isUserInput === void 0) { isUserInput = false; } var /** @type {?} */ isArray = Array.isArray(value); if (this.multiple && value && !isArray) { throw getMdSelectNonArrayValueError(); } this._clearSelection(); if (isArray) { value.forEach(function (currentValue) { return _this._selectValue(currentValue, isUserInput); }); this._sortValues(); } else { var /** @type {?} */ correspondingOption = this._selectValue(value, isUserInput); // Shift focus to the active item. Note that we shouldn't do this in multiple // mode, because we don't know what option the user interacted with last. if (correspondingOption) { this._keyManager.setActiveItem(this.options.toArray().indexOf(correspondingOption)); } } this._setValueWidth(); if (this._selectionModel.isEmpty()) { this._placeholderState = ''; } this._changeDetectorRef.markForCheck(); }; /** * Finds and selects and option based on its value. * @param {?} value * @param {?=} isUserInput * @return {?} Option that has the corresponding value. */ MdSelect.prototype._selectValue = function (value, isUserInput) { var _this = this; if (isUserInput === void 0) { isUserInput = false; } var /** @type {?} */ correspondingOption = this.options.find(function (option) { try { // Treat null as a special reset value. return option.value != null && _this._compareWith(option.value, value); } catch (error) { if (isDevMode()) { // Notify developers of errors in their comparator. console.warn(error); } return false; } }); if (correspondingOption) { isUserInput ? correspondingOption._selectViaInteraction() : correspondingOption.select(); this._selectionModel.select(correspondingOption); } return correspondingOption; }; /** * Clears the select trigger and deselects every option in the list. * @param {?=} skip Option that should not be deselected. * @return {?} */ MdSelect.prototype._clearSelection = function (skip) { this._selectionModel.clear(); this.options.forEach(function (option) { if (option !== skip) { option.deselect(); } }); }; /** * @return {?} */ MdSelect.prototype._getTriggerRect = function () { return this.trigger.nativeElement.getBoundingClientRect(); }; /** * Sets up a key manager to listen to keyboard events on the overlay panel. * @return {?} */ MdSelect.prototype._initKeyManager = function () { var _this = this; this._keyManager = new FocusKeyManager(this.options).withTypeAhead(); this._tabSubscription = this._keyManager.tabOut.subscribe(function () { return _this.close(); }); }; /** * Drops current option subscriptions and IDs and resets from scratch. * @return {?} */ MdSelect.prototype._resetOptions = function () { this._dropSubscriptions(); this._listenToOptions(); this._setOptionIds(); this._setOptionMultiple(); this._setOptionDisableRipple(); }; /** * Listens to user-generated selection events on each option. * @return {?} */ MdSelect.prototype._listenToOptions = function () { var _this = this; this._optionSubscription = filter.call(this.optionSelectionChanges, function (event) { return event.isUserInput; }).subscribe(function (event) { _this._onSelect(event.source); _this._setValueWidth(); if (!_this.multiple) { _this.close(); } }); }; /** * Invoked when an option is clicked. * @param {?} option * @return {?} */ MdSelect.prototype._onSelect = function (option) { var /** @type {?} */ wasSelected = this._selectionModel.isSelected(option); // TODO(crisbeto): handle blank/null options inside multi-select. if (this.multiple) { this._selectionModel.toggle(option); wasSelected ? option.deselect() : option.select(); this._sortValues(); } else { this._clearSelection(option.value == null ? undefined : option); if (option.value == null) { this._propagateChanges(option.value); } else { this._selectionModel.select(option); } } if (wasSelected !== this._selectionModel.isSelected(option)) { this._propagateChanges(); } }; /** * Sorts the model values, ensuring that they keep the same * order that they have in the panel. * @return {?} */ MdSelect.prototype._sortValues = function () { var _this = this; if (this._multiple) { this._selectionModel.clear(); this.options.forEach(function (option) { if (option.selected) { _this._selectionModel.select(option); } }); } }; /** * Unsubscribes from all option subscriptions. * @return {?} */ MdSelect.prototype._dropSubscriptions = function () { this._optionSubscription.unsubscribe(); }; /** * Emits change event to set the model value. * @param {?=} fallbackValue * @return {?} */ MdSelect.prototype._propagateChanges = function (fallbackValue) { var /** @type {?} */ valueToEmit = null; if (Array.isArray(this.selected)) { valueToEmit = this.selected.map(function (option) { return option.value; }); } else { valueToEmit = this.selected ? this.selected.value : fallbackValue; } this._value = valueToEmit; this._onChange(valueToEmit); this.change.emit(new MdSelectChange(this, valueToEmit)); this.valueChange.emit(valueToEmit); }; /** * Records option IDs to pass to the aria-owns property. * @return {?} */ MdSelect.prototype._setOptionIds = function () { this._optionIds = this.options.map(function (option) { return option.id; }).join(' '); }; /** * Sets the `multiple` property on each option. The promise is necessary * in order to avoid Angular errors when modifying the property after init. * @return {?} */ MdSelect.prototype._setOptionMultiple = function () { var _this = this; if (this.multiple) { Promise.resolve(null).then(function () { _this.options.forEach(function (option) { return option.multiple = _this.multiple; }); }); } }; /** * Sets the `disableRipple` property on each option. * @return {?} */ MdSelect.prototype._setOptionDisableRipple = function () { var _this = this; if (this.options) { this.options.forEach(function (option) { return option.disableRipple = _this.disableRipple; }); } }; /** * Must set the width of the selected option's value programmatically * because it is absolutely positioned and otherwise will not clip * overflow. The selection arrow is 9px wide, add 4px of padding = 13 * @return {?} */ MdSelect.prototype._setValueWidth = function () { this._selectedValueWidth = this._triggerWidth - 13; this._changeDetectorRef.markForCheck(); }; /** * Focuses the selected item. If no option is selected, it will focus * the first item instead. * @return {?} */ MdSelect.prototype._focusCorrectOption = function () { if (this._selectionModel.isEmpty()) { this._keyManager.setFirstItemActive(); } else { this._keyManager.setActiveItem(/** @type {?} */ ((this._getOptionIndex(this._selectionModel.selected[0])))); } }; /** * Focuses the select element. * @return {?} */ MdSelect.prototype.focus = function () { this._elementRef.nativeElement.focus(); }; /** * Gets the index of the provided option in the option list. * @param {?} option * @return {?} */ MdSelect.prototype._getOptionIndex = function (option) { return this.options.reduce(function (result, current, index) { return result === undefined ? (option === current ? index : undefined) : result; }, undefined); }; /** * Calculates the scroll position and x- and y-offsets of the overlay panel. * @return {?} */ MdSelect.prototype._calculateOverlayPosition = function () { var /** @type {?} */ items = this._getItemCount(); var /** @type {?} */ panelHeight = Math.min(items * SELECT_ITEM_HEIGHT, SELECT_PANEL_MAX_HEIGHT); var /** @type {?} */ scrollContainerHeight = items * SELECT_ITEM_HEIGHT; // The farthest the panel can be scrolled before it hits the bottom var /** @type {?} */ maxScroll = scrollContainerHeight - panelHeight; if (this._hasValue()) { var /** @type {?} */ selectedOptionOffset = ((this._getOptionIndex(this._selectionModel.selected[0]))); selectedOptionOffset += MdOption.countGroupLabelsBeforeOption(selectedOptionOffset, this.options, this.optionGroups); // We must maintain a scroll buffer so the selected option will be scrolled to the // center of the overlay panel rather than the top. var /** @type {?} */ scrollBuffer = panelHeight / 2; this._scrollTop = this._calculateOverlayScroll(selectedOptionOffset, scrollBuffer, maxScroll); this._offsetY = this._calculateOverlayOffsetY(selectedOptionOffset, scrollBuffer, maxScroll); } else { // If no option is selected, the panel centers on the first option. In this case, // we must only adjust for the height difference between the option element // and the trigger element, then multiply it by -1 to ensure the panel moves // in the correct direction up the page. var /** @type {?} */ groupLabels = MdOption.countGroupLabelsBeforeOption(0, this.options, this.optionGroups); this._offsetY = (SELECT_ITEM_HEIGHT - SELECT_TRIGGER_HEIGHT) / 2 * -1 - (groupLabels * SELECT_ITEM_HEIGHT); } this._checkOverlayWithinViewport(maxScroll); }; /** * Calculates the scroll position of the select's overlay panel. * * Attempts to center the selected option in the panel. If the option is * too high or too low in the panel to be scrolled to the center, it clamps the * scroll position to the min or max scroll positions respectively. * @param {?} selectedIndex * @param {?} scrollBuffer * @param {?} maxScroll * @return {?} */ MdSelect.prototype._calculateOverlayScroll = function (selectedIndex, scrollBuffer, maxScroll) { var /** @type {?} */ optionOffsetFromScrollTop = SELECT_ITEM_HEIGHT * selectedIndex; var /** @type {?} */ halfOptionHeight = SELECT_ITEM_HEIGHT / 2; // Starts at the optionOffsetFromScrollTop, which scrolls the option to the top of the // scroll container, then subtracts the scroll buffer to scroll the option down to // the center of the overlay panel. Half the option height must be re-added to the // scrollTop so the option is centered based on its middle, not its top edge. var /** @type {?} */ optimalScrollPosition = optionOffsetFromScrollTop - scrollBuffer + halfOptionHeight; return clampValue(0, optimalScrollPosition, maxScroll); }; /** * Figures out the appropriate animation state for the placeholder. * @return {?} */ MdSelect.prototype._getPlaceholderAnimationState = function () { if (this.floatPlaceholder === 'never') { return ''; } if (this.floatPlaceholder === 'always') { return this._floatPlaceholderState(); } return this._placeholderState; }; /** * Determines the CSS `opacity` of the placeholder element. * @return {?} */ MdSelect.prototype._getPlaceholderOpacity = function () { return (this.floatPlaceholder !== 'never' || this._selectionModel.isEmpty()) ? '1' : '0'; }; Object.defineProperty(MdSelect.prototype, "_ariaLabel", { /** * Returns the aria-label of the select component. * @return {?} */ get: function () { // If an ariaLabelledby value has been set, the select should not overwrite the // `aria-labelledby` value by setting the ariaLabel to the placeholder. return this.ariaLabelledby ? null : this.ariaLabel || this.placeholder; }, enumerable: true, configurable: true }); /** * Sets the x-offset of the overlay panel in relation to the trigger's top start corner. * This must be adjusted to align the selected option text over the trigger text when * the panel opens. Will change based on LTR or RTL text direction. Note that the offset * can't be calculated until the panel has been attached, because we need to know the * content width in order to constrain the panel within the viewport. * @return {?} */ MdSelect.prototype._calculateOverlayOffsetX = function () { var /** @type {?} */ overlayRect = this.overlayDir.overlayRef.overlayElement.getBoundingClientRect(); var /** @type {?} */ viewportRect = this._viewportRuler.getViewportRect(); var /** @type {?} */ isRtl = this._isRtl(); var /** @type {?} */ paddingWidth = this.multiple ? SELECT_MULTIPLE_PANEL_PADDING_X + SELECT_PANEL_PADDING_X : SELECT_PANEL_PADDING_X * 2; var /** @type {?} */ offsetX; // Adjust the offset, depending on the option padding. if (this.multiple) { offsetX = SELECT_MULTIPLE_PANEL_PADDING_X; } else { var /** @type {?} */ selected = this._selectionModel.selected[0] || this.options.first; offsetX = selected && selected.group ? SELECT_PANEL_INDENT_PADDING_X : SELECT_PANEL_PADDING_X; } // Invert the offset in LTR. if (!isRtl) { offsetX *= -1; } // Determine how much the select overflows on each side. var /** @type {?} */ leftOverflow = 0 - (overlayRect.left + offsetX - (isRtl ? paddingWidth : 0)); var /** @type {?} */ rightOverflow = overlayRect.right + offsetX - viewportRect.width + (isRtl ? 0 : paddingWidth); // If the element overflows on either side, reduce the offset to allow it to fit. if (leftOverflow > 0) { offsetX += leftOverflow + SELECT_PANEL_VIEWPORT_PADDING; } else if (rightOverflow > 0) { offsetX -= rightOverflow + SELECT_PANEL_VIEWPORT_PADDING; } // Set the offset directly in order to avoid having to go through change detection and // potentially triggering "changed after it was checked" errors. this.overlayDir.offsetX = offsetX; this.overlayDir.overlayRef.updatePosition(); }; /** * Calculates the y-offset of the select's overlay panel in relation to the * top start corner of the trigger. It has to be adjusted in order for the * selected option to be aligned over the trigger when the panel opens. * @param {?} selectedIndex * @param {?} scrollBuffer * @param {?} maxScroll * @return {?} */ MdSelect.prototype._calculateOverlayOffsetY = function (selectedIndex, scrollBuffer, maxScroll) { var /** @type {?} */ optionOffsetFromPanelTop; if (this._scrollTop === 0) { optionOffsetFromPanelTop = selectedIndex * SELECT_ITEM_HEIGHT; } else if (this._scrollTop === maxScroll) { var /** @type {?} */ firstDisplayedIndex = this._getItemCount() - SELECT_MAX_OPTIONS_DISPLAYED; var /** @type {?} */ selectedDisplayIndex = selectedIndex - firstDisplayedIndex; // Because the panel height is longer than the height of the options alone, // there is always extra padding at the top or bottom of the panel. When // scrolled to the very bottom, this padding is at the top of the panel and // must be added to the offset. optionOffsetFromPanelTop = selectedDisplayIndex * SELECT_ITEM_HEIGHT + SELECT_PANEL_PADDING_Y; } else { // If the option was scrolled to the middle of the panel using a scroll buffer, // its offset will be the scroll buffer minus the half height that was added to // center it. optionOffsetFromPanelTop = scrollBuffer - SELECT_ITEM_HEIGHT / 2; } // The final offset is the option's offset from the top, adjusted for the height // difference, multiplied by -1 to ensure that the overlay moves in the correct // direction up the page. return optionOffsetFromPanelTop * -1 - SELECT_OPTION_HEIGHT_ADJUSTMENT; }; /** * Checks that the attempted overlay position will fit within the viewport. * If it will not fit, tries to adjust the scroll position and the associated * y-offset so the panel can open fully on-screen. If it still won't fit, * sets the offset back to 0 to allow the fallback position to take over. * @param {?} maxScroll * @return {?} */ MdSelect.prototype._checkOverlayWithinViewport = function (maxScroll) { var /** @type {?} */ viewportRect = this._viewportRuler.getViewportRect(); var /** @type {?} */ triggerRect = this._getTriggerRect(); var /** @type {?} */ topSpaceAvailable = triggerRect.top - SELECT_PANEL_VIEWPORT_PADDING; var /** @type {?} */ bottomSpaceAvailable = viewportRect.height - triggerRect.bottom - SELECT_PANEL_VIEWPORT_PADDING; var /** @type {?} */ panelHeightTop = Math.abs(this._offsetY); var /** @type {?} */ totalPanelHeight = Math.min(this._getItemCount() * SELECT_ITEM_HEIGHT, SELECT_PANEL_MAX_HEIGHT); var /** @type {?} */ panelHeightBottom = totalPanelHeight - panelHeightTop - triggerRect.height; if (panelHeightBottom > bottomSpaceAvailable) { this._adjustPanelUp(panelHeightBottom, bottomSpaceAvailable); } else if (panelHeightTop > topSpaceAvailable) { this._adjustPanelDown(panelHeightTop, topSpaceAvailable, maxScroll); } else { this._transformOrigin = this._getOriginBasedOnOption(); } }; /** * Adjusts the overlay panel up to fit in the viewport. * @param {?} panelHeightBottom * @param {?} bottomSpaceAvailable * @return {?} */ MdSelect.prototype._adjustPanelUp = function (panelHeightBottom, bottomSpaceAvailable) { var /** @type {?} */ distanceBelowViewport = panelHeightBottom - bottomSpaceAvailable; // Scrolls the panel up by the distance it was extending past the boundary, then // adjusts the offset by that amount to move the panel up into the viewport. this._scrollTop -= distanceBelowViewport; this._offsetY -= distanceBelowViewport; this._transformOrigin = this._getOriginBasedOnOption(); // If the panel is scrolled to the very top, it won't be able to fit the panel // by scrolling, so set the offset to 0 to allow the fallback position to take // effect. if (this._scrollTop <= 0) { this._scrollTop = 0; this._offsetY = 0; this._transformOrigin = "50% bottom 0px"; } }; /** * Adjusts the overlay panel down to fit in the viewport. * @param {?} panelHeightTop * @param {?} topSpaceAvailable * @param {?} maxScroll * @return {?} */ MdSelect.prototype._adjustPanelDown = function (panelHeightTop, topSpaceAvailable, maxScroll) { var /** @type {?} */ distanceAboveViewport = panelHeightTop - topSpaceAvailable; // Scrolls the panel down by the distance it was extending past the boundary, then // adjusts the offset by that amount to move the panel down into the viewport. this._scrollTop += distanceAboveViewport; this._offsetY += distanceAboveViewport; this._transformOrigin = this._getOriginBasedOnOption(); // If the panel is scrolled to the very bottom, it won't be able to fit the // panel by scrolling, so set the offset to 0 to allow the fallback position // to take effect. if (this._scrollTop >= maxScroll) { this._scrollTop = maxScroll; this._offsetY = 0; this._transformOrigin = "50% top 0px"; return; } }; /** * Sets the transform origin point based on the selected option. * @return {?} */ MdSelect.prototype._getOriginBasedOnOption = function () { var /** @type {?} */ originY = Math.abs(this._offsetY) - SELECT_OPTION_HEIGHT_ADJUSTMENT + SELECT_ITEM_HEIGHT / 2; return "50% " + originY + "px 0px"; }; /** * Figures out the floating placeholder state value. * @return {?} */ MdSelect.prototype._floatPlaceholderState = function () { return this._isRtl() ? 'floating-rtl' : 'floating-ltr'; }; /** * Handles the