mirror of
https://github.com/angular/angular.git
synced 2026-09-14 13:54:52 +08:00
@@ -1,3 +1,4 @@
|
||||
<div style="height: 1000px">This div is for testing scrolled selects.</div>
|
||||
<div class="demo-select">
|
||||
<md-card>
|
||||
<md-select placeholder="Food i would like to eat" [formControl]="foodControl">
|
||||
@@ -28,3 +29,4 @@
|
||||
</md-card>
|
||||
|
||||
</div>
|
||||
<div style="height: 500px">This div is for testing scrolled selects.</div>
|
||||
|
||||
@@ -21,8 +21,14 @@ export class SelectDemo {
|
||||
|
||||
drinks = [
|
||||
{value: 'coke-0', viewValue: 'Coke'},
|
||||
{value: 'sprite-1', viewValue: 'Sprite', disabled: true},
|
||||
{value: 'water-2', viewValue: 'Water'}
|
||||
{value: 'sprite-1', viewValue: 'Sprite'},
|
||||
{value: 'water-2', viewValue: 'Water'},
|
||||
{value: 'pepper-3', viewValue: 'Dr. Pepper'},
|
||||
{value: 'coffee-4', viewValue: 'Coffee'},
|
||||
{value: 'tea-5', viewValue: 'Tea'},
|
||||
{value: 'juice-6', viewValue: 'Orange juice'},
|
||||
{value: 'wine-7', viewValue: 'Wine'},
|
||||
{value: 'milk-8', viewValue: 'Milk'},
|
||||
];
|
||||
|
||||
toggleDisabled() {
|
||||
|
||||
@@ -42,25 +42,10 @@ export const transformPlaceholder: AnimationEntryMetadata = trigger('transformPl
|
||||
* When the panel is removed from the DOM, it simply fades out linearly.
|
||||
*/
|
||||
export const transformPanel: AnimationEntryMetadata = trigger('transformPanel', [
|
||||
state('top-ltr', style({
|
||||
state('showing', style({
|
||||
opacity: 1,
|
||||
width: 'calc(100% + 32px)',
|
||||
transform: `translate3d(-16px, -9px, 0) scaleY(1)`
|
||||
})),
|
||||
state('top-rtl', style({
|
||||
opacity: 1,
|
||||
width: 'calc(100% + 32px)',
|
||||
transform: `translate3d(16px, -9px, 0) scaleY(1)`
|
||||
})),
|
||||
state('bottom-ltr', style({
|
||||
opacity: 1,
|
||||
width: 'calc(100% + 32px)',
|
||||
transform: `translate3d(-16px, 8px, 0) scaleY(1)`
|
||||
})),
|
||||
state('bottom-rtl', style({
|
||||
opacity: 1,
|
||||
width: 'calc(100% + 32px)',
|
||||
transform: `translate3d(16px, 8px, 0) scaleY(1)`
|
||||
transform: `translate3d(0,0,0) scaleY(1)`
|
||||
})),
|
||||
transition('void => *', [
|
||||
style({
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
|
||||
<template connected-overlay [origin]="origin" [open]="panelOpen" hasBackdrop (backdropClick)="close()"
|
||||
backdropClass="md-overlay-transparent-backdrop" [positions]="_positions" [width]="_getWidth()"
|
||||
(positionChange)="_updateTransformOrigin($event)">
|
||||
<div class="md-select-panel" [@transformPanel]="_getPanelState()" (@transformPanel.done)="_onPanelDone()"
|
||||
[offsetY]="_offsetY" [offsetX]="_offsetX" (attach)="_setScrollTop()">
|
||||
<div class="md-select-panel" [@transformPanel]="'showing'" (@transformPanel.done)="_onPanelDone()"
|
||||
(keydown)="_keyManager.onKeydown($event)" [style.transformOrigin]="_transformOrigin">
|
||||
<div class="md-select-content" [@fadeInContent]="'showing'">
|
||||
<ng-content></ng-content>
|
||||
|
||||
@@ -5,6 +5,7 @@ $md-select-trigger-height: 30px !default;
|
||||
$md-select-trigger-min-width: 112px !default;
|
||||
$md-select-arrow-size: 5px !default;
|
||||
$md-select-arrow-margin: 4px !default;
|
||||
$md-select-panel-max-height: 256px !default;
|
||||
|
||||
md-select {
|
||||
display: inline-block;
|
||||
@@ -19,6 +20,7 @@ md-select {
|
||||
min-width: $md-select-trigger-min-width;
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
|
||||
[aria-disabled='true'] & {
|
||||
@include md-control-disabled-underline();
|
||||
@@ -78,7 +80,7 @@ md-select {
|
||||
@include md-menu-base();
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
transform-origin: top;
|
||||
max-height: $md-select-panel-max-height;
|
||||
}
|
||||
|
||||
md-option {
|
||||
|
||||
+260
-54
@@ -208,16 +208,16 @@ describe('MdSelect', () => {
|
||||
}));
|
||||
|
||||
it('should select an option that was added after initialization', () => {
|
||||
fixture.componentInstance.foods.push({viewValue: 'Pasta', value: 'pasta-3'});
|
||||
fixture.componentInstance.foods.push({viewValue: 'Potatoes', value: 'potatoes-8'});
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const options =
|
||||
overlayContainerElement.querySelectorAll('md-option') as NodeListOf<HTMLElement>;
|
||||
options[3].click();
|
||||
options[8].click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(trigger.textContent).toContain('Pasta');
|
||||
expect(trigger.textContent).toContain('Potatoes');
|
||||
expect(fixture.componentInstance.select.selected)
|
||||
.toBe(fixture.componentInstance.options.last);
|
||||
});
|
||||
@@ -490,79 +490,280 @@ describe('MdSelect', () => {
|
||||
expect(fixture.componentInstance.select._getPlaceholderState()).toEqual('floating-rtl');
|
||||
});
|
||||
|
||||
it('should use the ltr panel state when the dir is ltr', () => {
|
||||
dir.value = 'ltr';
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.componentInstance.select._getPanelState()).toEqual('top-ltr');
|
||||
});
|
||||
|
||||
it('should use the rtl panel state when the dir is rtl', () => {
|
||||
dir.value = 'rtl';
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.componentInstance.select._getPanelState()).toEqual('top-rtl');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('positioning', () => {
|
||||
let fixture: ComponentFixture<BasicSelect>;
|
||||
let trigger: HTMLElement;
|
||||
let select: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(BasicSelect);
|
||||
fixture.detectChanges();
|
||||
trigger = fixture.debugElement.query(By.css('.md-select-trigger')).nativeElement;
|
||||
select = fixture.debugElement.query(By.css('md-select')).nativeElement;
|
||||
});
|
||||
|
||||
it('should open below the trigger if the panel will fit', () => {
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
/**
|
||||
* Asserts that the given option is aligned with the trigger.
|
||||
* @param index The index of the option.
|
||||
*/
|
||||
function checkTriggerAlignedWithOption(index: number): void {
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const overlayRect = overlayPane.getBoundingClientRect();
|
||||
const triggerRect = trigger.getBoundingClientRect();
|
||||
const triggerTop = trigger.getBoundingClientRect().top;
|
||||
const overlayTop = overlayPane.getBoundingClientRect().top;
|
||||
const options = overlayPane.querySelectorAll('md-option');
|
||||
const optionTop = options[index].getBoundingClientRect().top;
|
||||
|
||||
// when the select panel opens below the trigger, the tops of the trigger and the overlay
|
||||
// should be aligned.
|
||||
expect(overlayRect.top.toFixed(2))
|
||||
.toEqual(triggerRect.top.toFixed(2), `Expected panel to open below by default.`);
|
||||
// The option text should align with the trigger text. Because each option is 18px
|
||||
// larger in height than the trigger, the option needs to be adjusted up 9 pixels.
|
||||
expect(optionTop.toFixed(2))
|
||||
.toEqual((triggerTop - 9).toFixed(2), `Expected trigger to align with option ${index}.`);
|
||||
|
||||
// animation should match the position
|
||||
expect(fixture.componentInstance.select._getPanelState())
|
||||
.toEqual('top-ltr', `Expected panel animation values to match the position.`);
|
||||
// For the animation to start at the option's center, its origin must be the distance
|
||||
// from the top of the overlay to the option top + half the option height (48/2 = 24).
|
||||
const expectedOrigin = optionTop - overlayTop + 24;
|
||||
expect(fixture.componentInstance.select._transformOrigin)
|
||||
.toBe('top', `Expected panel animation to originate at the top.`);
|
||||
.toContain(`${expectedOrigin}px`,
|
||||
`Expected panel animation to originate in the center of option ${index}.`);
|
||||
}
|
||||
|
||||
describe('ample space to open', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
// these styles are necessary because we are first testing the overlay's position
|
||||
// if there is room for it to open to its full extent in either direction.
|
||||
select.style.marginTop = '300px';
|
||||
select.style.marginLeft = '20px';
|
||||
select.style.marginRight = '20px';
|
||||
});
|
||||
|
||||
it('should align the first option with the trigger text if no option is selected', () => {
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const scrollContainer = overlayPane.querySelector('.md-select-panel');
|
||||
|
||||
// The panel should be scrolled to 0 because centering the option is not possible.
|
||||
expect(scrollContainer.scrollTop).toEqual(0, `Expected panel not to be scrolled.`);
|
||||
|
||||
checkTriggerAlignedWithOption(0);
|
||||
});
|
||||
|
||||
it('should align a selected option too high to be centered with the trigger text', () => {
|
||||
// Select the second option, because it can't be scrolled any further downward
|
||||
fixture.componentInstance.control.setValue('pizza-1');
|
||||
fixture.detectChanges();
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const scrollContainer = overlayPane.querySelector('.md-select-panel');
|
||||
|
||||
// The panel should be scrolled to 0 because centering the option is not possible.
|
||||
expect(scrollContainer.scrollTop).toEqual(0, `Expected panel not to be scrolled.`);
|
||||
|
||||
checkTriggerAlignedWithOption(1);
|
||||
});
|
||||
|
||||
it('should align a selected option in the middle with the trigger text', () => {
|
||||
// Select the fifth option, which has enough space to scroll to the center
|
||||
fixture.componentInstance.control.setValue('chips-4');
|
||||
fixture.detectChanges();
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const scrollContainer = overlayPane.querySelector('.md-select-panel');
|
||||
|
||||
// The selected option should be scrolled to the center of the panel.
|
||||
// This will be its original offset from the scrollTop - half the panel height + half the
|
||||
// option height. 4 (index) * 48 (option height) = 192px offset from scrollTop
|
||||
// 192 - 256/2 + 48/2 = 88px
|
||||
expect(scrollContainer.scrollTop)
|
||||
.toEqual(88, `Expected overlay panel to be scrolled to center the selected option.`);
|
||||
|
||||
checkTriggerAlignedWithOption(4);
|
||||
});
|
||||
|
||||
it('should align a selected option at the scroll max with the trigger text', () => {
|
||||
// Select the last option in the list
|
||||
fixture.componentInstance.control.setValue('sushi-7');
|
||||
fixture.detectChanges();
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const scrollContainer = overlayPane.querySelector('.md-select-panel');
|
||||
|
||||
// The selected option should be scrolled to the max scroll position.
|
||||
// This will be the height of the scrollContainer - the panel height.
|
||||
// 8 options * 48px = 384 scrollContainer height, 384 - 256 = 128px max scroll
|
||||
expect(scrollContainer.scrollTop)
|
||||
.toEqual(128, `Expected overlay panel to be scrolled to its maximum position.`);
|
||||
|
||||
checkTriggerAlignedWithOption(7);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
it('should open above the trigger if there is not space below for the panel', () => {
|
||||
// Push trigger to the bottom part of viewport, so it doesn't have space to open
|
||||
// in its default position below the trigger.
|
||||
trigger.style.position = 'relative';
|
||||
trigger.style.top = '650px';
|
||||
describe('limited space to open vertically', () => {
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
beforeEach(() => {
|
||||
select.style.marginLeft = '20px';
|
||||
select.style.marginRight = '20px';
|
||||
});
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const overlayRect = overlayPane.getBoundingClientRect();
|
||||
const triggerRect = trigger.getBoundingClientRect();
|
||||
it('should adjust position of centered option if there is little space above', () => {
|
||||
// Push the select to a position with not quite enough space on the top to open
|
||||
// with the option completely centered (needs 113px at least: 256/2 - 48/2 + 9)
|
||||
select.style.marginTop = '85px';
|
||||
|
||||
// In "above" position, the bottom edges of the overlay and the origin are aligned.
|
||||
// To find the overlay top, subtract the panel height from the origin's bottom edge.
|
||||
const expectedTop = triggerRect.bottom - overlayRect.height;
|
||||
expect(overlayRect.top.toFixed(2))
|
||||
.toEqual(expectedTop.toFixed(2),
|
||||
`Expected panel to open above the trigger if below wouldn't fit.`);
|
||||
// Select an option in the middle of the list
|
||||
fixture.componentInstance.control.setValue('chips-4');
|
||||
fixture.detectChanges();
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const scrollContainer = overlayPane.querySelector('.md-select-panel');
|
||||
|
||||
// Scroll should adjust by the difference between the top space available (85px + 8px
|
||||
// viewport padding = 77px) and the height of the panel above the option (113px).
|
||||
// 113px - 77px = 36px difference + original scrollTop 88px = 124px
|
||||
expect(scrollContainer.scrollTop)
|
||||
.toEqual(124, `Expected panel to adjust scroll position to fit in viewport.`);
|
||||
|
||||
checkTriggerAlignedWithOption(4);
|
||||
});
|
||||
|
||||
it('should adjust position of centered option if there is little space below', () => {
|
||||
// Push the select to a position with not quite enough space on the bottom to open
|
||||
// with the option completely centered (needs 113px at least: 256/2 - 48/2 + 9)
|
||||
select.style.marginTop = '600px';
|
||||
|
||||
// Select an option in the middle of the list
|
||||
fixture.componentInstance.control.setValue('chips-4');
|
||||
fixture.detectChanges();
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const scrollContainer = overlayPane.querySelector('.md-select-panel');
|
||||
|
||||
// Scroll should adjust by the difference between the bottom space available
|
||||
// (686px - 600px margin - 30px trigger height = 56px - 8px padding = 48px)
|
||||
// and the height of the panel below the option (113px).
|
||||
// 113px - 48px = 75px difference. Original scrollTop 88px - 75px = 23px
|
||||
expect(scrollContainer.scrollTop)
|
||||
.toEqual(23, `Expected panel to adjust scroll position to fit in viewport.`);
|
||||
|
||||
checkTriggerAlignedWithOption(4);
|
||||
});
|
||||
|
||||
it('should fall back to "above" positioning if scroll adjustment will not help', () => {
|
||||
// Push the select to a position with not enough space on the bottom to open
|
||||
select.style.marginTop = '600px';
|
||||
fixture.detectChanges();
|
||||
|
||||
// Select an option that cannot be scrolled any farther upward
|
||||
fixture.componentInstance.control.setValue('coke-0');
|
||||
fixture.detectChanges();
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const triggerBottom = trigger.getBoundingClientRect().bottom;
|
||||
const overlayBottom = overlayPane.getBoundingClientRect().bottom;
|
||||
const scrollContainer = overlayPane.querySelector('.md-select-panel');
|
||||
|
||||
// Expect no scroll to be attempted
|
||||
expect(scrollContainer.scrollTop).toEqual(0, `Expected panel not to be scrolled.`);
|
||||
|
||||
expect(overlayBottom.toFixed(2))
|
||||
.toEqual(triggerBottom.toFixed(2),
|
||||
`Expected trigger bottom to align with overlay bottom.`);
|
||||
|
||||
expect(fixture.componentInstance.select._transformOrigin)
|
||||
.toContain(`bottom`, `Expected panel animation to originate at the bottom.`);
|
||||
});
|
||||
|
||||
it('should fall back to "below" positioning if scroll adjustment will not help', () => {
|
||||
// Push the select to a position with not enough space on the top to open
|
||||
select.style.marginTop = '85px';
|
||||
|
||||
// Select an option that cannot be scrolled any farther downward
|
||||
fixture.componentInstance.control.setValue('sushi-7');
|
||||
fixture.detectChanges();
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const triggerTop = trigger.getBoundingClientRect().top;
|
||||
const overlayTop = overlayPane.getBoundingClientRect().top;
|
||||
const scrollContainer = overlayPane.querySelector('.md-select-panel');
|
||||
|
||||
// Expect scroll to remain at the max scroll position
|
||||
expect(scrollContainer.scrollTop).toEqual(128, `Expected panel to be at max scroll.`);
|
||||
|
||||
expect(overlayTop.toFixed(2))
|
||||
.toEqual(triggerTop.toFixed(2), `Expected trigger top to align with overlay top.`);
|
||||
|
||||
expect(fixture.componentInstance.select._transformOrigin)
|
||||
.toContain(`top`, `Expected panel animation to originate at the top.`);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('x-axis positioning', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
select.style.marginLeft = '20px';
|
||||
select.style.marginRight = '20px';
|
||||
});
|
||||
|
||||
it('should align the trigger and the selected option on the x-axis in ltr', () => {
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const triggerLeft = trigger.getBoundingClientRect().left;
|
||||
const firstOptionLeft =
|
||||
overlayPane.querySelector('md-option').getBoundingClientRect().left;
|
||||
|
||||
// Each option is 32px wider than the trigger, so it must be adjusted 16px
|
||||
// to ensure the text overlaps correctly.
|
||||
expect(firstOptionLeft.toFixed(2))
|
||||
.toEqual((triggerLeft - 16).toFixed(2),
|
||||
`Expected trigger to align with the selected option on the x-axis in LTR.`);
|
||||
});
|
||||
|
||||
it('should align the trigger and the selected option on the x-axis in rtl', () => {
|
||||
dir.value = 'rtl';
|
||||
|
||||
trigger.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlayPane = overlayContainerElement.children[0] as HTMLElement;
|
||||
const triggerRight = trigger.getBoundingClientRect().right;
|
||||
const firstOptionRight =
|
||||
overlayPane.querySelector('md-option').getBoundingClientRect().right;
|
||||
|
||||
// Each option is 32px wider than the trigger, so it must be adjusted 16px
|
||||
// to ensure the text overlaps correctly.
|
||||
expect(firstOptionRight.toFixed(2))
|
||||
.toEqual((triggerRight + 16).toFixed(2),
|
||||
`Expected trigger to align with the selected option on the x-axis in RTL.`);
|
||||
});
|
||||
|
||||
// animation should match the position
|
||||
expect(fixture.componentInstance.select._getPanelState())
|
||||
.toEqual('bottom-ltr', `Expected panel animation values to match the position.`);
|
||||
expect(fixture.componentInstance.select._transformOrigin)
|
||||
.toBe('bottom', `Expected panel animation to originate at the bottom.`);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -784,6 +985,11 @@ class BasicSelect {
|
||||
{ value: 'steak-0', viewValue: 'Steak' },
|
||||
{ value: 'pizza-1', viewValue: 'Pizza' },
|
||||
{ value: 'tacos-2', viewValue: 'Tacos', disabled: true },
|
||||
{ value: 'sandwich-3', viewValue: 'Sandwich' },
|
||||
{ value: 'chips-4', viewValue: 'Chips' },
|
||||
{ value: 'eggs-5', viewValue: 'Eggs' },
|
||||
{ value: 'pasta-6', viewValue: 'Pasta' },
|
||||
{ value: 'sushi-7', viewValue: 'Sushi' },
|
||||
];
|
||||
control = new FormControl();
|
||||
isRequired: boolean;
|
||||
|
||||
+244
-15
@@ -12,7 +12,7 @@ import {
|
||||
QueryList,
|
||||
Renderer,
|
||||
ViewEncapsulation,
|
||||
ViewChild
|
||||
ViewChild,
|
||||
} from '@angular/core';
|
||||
import {MdOption} from './option';
|
||||
import {ENTER, SPACE} from '../core/keyboard/keycodes';
|
||||
@@ -22,7 +22,48 @@ import {Subscription} from 'rxjs/Subscription';
|
||||
import {transformPlaceholder, transformPanel, fadeInContent} from './select-animations';
|
||||
import {ControlValueAccessor, NgControl} from '@angular/forms';
|
||||
import {coerceBooleanProperty} from '../core/coersion/boolean-property';
|
||||
import {ConnectedOverlayPositionChange} from '../core/overlay/position/connected-position';
|
||||
import {ConnectedOverlayDirective} from '../core/overlay/overlay-directives';
|
||||
import {ViewportRuler} from '../core/overlay/position/viewport-ruler';
|
||||
|
||||
/**
|
||||
* The following style constants are necessary to save here in order
|
||||
* to properly calculate the alignment of the selected option over
|
||||
* the trigger element.
|
||||
*/
|
||||
|
||||
/** The fixed height of every option element. */
|
||||
export const SELECT_OPTION_HEIGHT = 48;
|
||||
|
||||
/** The max height of the select's overlay panel */
|
||||
export const SELECT_PANEL_MAX_HEIGHT = 256;
|
||||
|
||||
/** The max number of options visible at once in the select panel. */
|
||||
export const SELECT_MAX_OPTIONS_DISPLAYED = 5;
|
||||
|
||||
/** The fixed height of the select's trigger element. */
|
||||
export const 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.
|
||||
* (SELECT_OPTION_HEIGHT (48) - SELECT_TRIGGER_HEIGHT (30)) / 2 = 9
|
||||
*/
|
||||
export const SELECT_OPTION_HEIGHT_ADJUSTMENT = 9;
|
||||
|
||||
/** The panel's padding on the x-axis */
|
||||
export const SELECT_PANEL_PADDING_X = 16;
|
||||
|
||||
/**
|
||||
* The panel's padding on the y-axis. This padding indicates there are more
|
||||
* options available if you scroll.
|
||||
*/
|
||||
export const 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.
|
||||
*/
|
||||
export const SELECT_PANEL_VIEWPORT_PADDING = 8;
|
||||
|
||||
@Component({
|
||||
moduleId: module.id,
|
||||
@@ -71,11 +112,14 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
/** Whether the select is disabled. */
|
||||
private _disabled: boolean = false;
|
||||
|
||||
/** The scroll position of the overlay panel, calculated to center the selected option. */
|
||||
private _scrollTop = 0;
|
||||
|
||||
/** Manages keyboard events for options in the panel. */
|
||||
_keyManager: ListKeyManager;
|
||||
|
||||
/** View -> model callback called when value changes */
|
||||
_onChange: (value: any) => void;
|
||||
_onChange = (value: any) => {};
|
||||
|
||||
/** View -> model callback called when select has been touched */
|
||||
_onTouched = () => {};
|
||||
@@ -86,6 +130,20 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
/** The value of the select panel's transform-origin property. */
|
||||
_transformOrigin: string = 'top';
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
_offsetX = 0;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
_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
|
||||
@@ -108,6 +166,7 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
];
|
||||
|
||||
@ViewChild('trigger') trigger: ElementRef;
|
||||
@ViewChild(ConnectedOverlayDirective) overlayDir: ConnectedOverlayDirective;
|
||||
@ContentChildren(MdOption) options: QueryList<MdOption>;
|
||||
|
||||
@Input() placeholder: string;
|
||||
@@ -134,8 +193,8 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
@Output() onClose = new EventEmitter();
|
||||
|
||||
constructor(private _element: ElementRef, private _renderer: Renderer,
|
||||
@Optional() private _dir: Dir, @Optional() public _control: NgControl,
|
||||
private _ngZone: NgZone) {
|
||||
private _ngZone: NgZone, private _viewportRuler: ViewportRuler,
|
||||
@Optional() private _dir: Dir, @Optional() public _control: NgControl) {
|
||||
if (this._control) {
|
||||
this._control.valueAccessor = this;
|
||||
}
|
||||
@@ -163,6 +222,7 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
this._calculateOverlayPosition();
|
||||
this._panelOpen = true;
|
||||
}
|
||||
|
||||
@@ -237,7 +297,7 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
* the overlay width to the trigger width.
|
||||
*/
|
||||
_getWidth(): number {
|
||||
return this.trigger.nativeElement.getBoundingClientRect().width;
|
||||
return this._getTriggerRect().width;
|
||||
}
|
||||
|
||||
/** The animation state of the placeholder. */
|
||||
@@ -249,11 +309,6 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
}
|
||||
}
|
||||
|
||||
/** The animation state of the overlay panel. */
|
||||
_getPanelState(): string {
|
||||
return this._isRtl() ? `${this._transformOrigin}-rtl` : `${this._transformOrigin}-ltr`;
|
||||
}
|
||||
|
||||
/** Ensures the panel opens if activated by the keyboard. */
|
||||
_handleKeydown(event: KeyboardEvent): void {
|
||||
if (event.keyCode === ENTER || event.keyCode === SPACE) {
|
||||
@@ -289,12 +344,20 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
return this.disabled ? '-1' : '0';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the transform-origin property of the panel to ensure that it
|
||||
* animates in the correct direction based on its positioning.
|
||||
* 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.
|
||||
*/
|
||||
_updateTransformOrigin(pos: ConnectedOverlayPositionChange): void {
|
||||
this._transformOrigin = pos.connectionPair.originY;
|
||||
_setScrollTop(): void {
|
||||
const scrollContainer =
|
||||
this.overlayDir.overlayRef.overlayElement.querySelector('.md-select-panel');
|
||||
scrollContainer.scrollTop = this._scrollTop;
|
||||
}
|
||||
|
||||
private _getTriggerRect(): ClientRect {
|
||||
return this.trigger.nativeElement.getBoundingClientRect();
|
||||
}
|
||||
|
||||
/** Sets up a key manager to listen to keyboard events on the overlay panel. */
|
||||
@@ -375,4 +438,170 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
|
||||
}, undefined);
|
||||
}
|
||||
|
||||
/** Calculates the scroll position and x- and y-offsets of the overlay panel. */
|
||||
private _calculateOverlayPosition(): void {
|
||||
this._offsetX = this._isRtl() ? SELECT_PANEL_PADDING_X : -SELECT_PANEL_PADDING_X;
|
||||
|
||||
const panelHeight =
|
||||
Math.min(this.options.length * SELECT_OPTION_HEIGHT, SELECT_PANEL_MAX_HEIGHT);
|
||||
const scrollContainerHeight = this.options.length * SELECT_OPTION_HEIGHT;
|
||||
|
||||
// The farthest the panel can be scrolled before it hits the bottom
|
||||
const maxScroll = scrollContainerHeight - panelHeight;
|
||||
|
||||
if (this.selected) {
|
||||
const selectedIndex = this._getOptionIndex(this.selected);
|
||||
// We must maintain a scroll buffer so the selected option will be scrolled to the
|
||||
// center of the overlay panel rather than the top.
|
||||
const scrollBuffer = panelHeight / 2;
|
||||
this._scrollTop = this._calculateOverlayScroll(selectedIndex, scrollBuffer, maxScroll);
|
||||
this._offsetY = this._calculateOverlayOffset(selectedIndex, 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.
|
||||
this._offsetY = (SELECT_OPTION_HEIGHT - SELECT_TRIGGER_HEIGHT) / 2 * -1;
|
||||
}
|
||||
|
||||
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.
|
||||
*/
|
||||
_calculateOverlayScroll(selectedIndex: number, scrollBuffer: number,
|
||||
maxScroll: number): number {
|
||||
const optionOffsetFromScrollTop = SELECT_OPTION_HEIGHT * selectedIndex;
|
||||
const halfOptionHeight = SELECT_OPTION_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.
|
||||
const optimalScrollPosition = optionOffsetFromScrollTop - scrollBuffer + halfOptionHeight;
|
||||
return clampValue(0, optimalScrollPosition, maxScroll);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private _calculateOverlayOffset(selectedIndex: number, scrollBuffer: number,
|
||||
maxScroll: number): number {
|
||||
let optionOffsetFromPanelTop: number;
|
||||
|
||||
if (this._scrollTop === 0) {
|
||||
optionOffsetFromPanelTop = selectedIndex * SELECT_OPTION_HEIGHT;
|
||||
} else if (this._scrollTop === maxScroll) {
|
||||
const firstDisplayedIndex = this.options.length - SELECT_MAX_OPTIONS_DISPLAYED;
|
||||
const 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_OPTION_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_OPTION_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.
|
||||
*/
|
||||
private _checkOverlayWithinViewport(maxScroll: number): void {
|
||||
const viewportRect = this._viewportRuler.getViewportRect();
|
||||
const triggerRect = this._getTriggerRect();
|
||||
|
||||
const topSpaceAvailable =
|
||||
triggerRect.top - viewportRect.top - SELECT_PANEL_VIEWPORT_PADDING;
|
||||
const bottomSpaceAvailable =
|
||||
viewportRect.bottom - triggerRect.bottom - SELECT_PANEL_VIEWPORT_PADDING;
|
||||
|
||||
const panelHeightTop = Math.abs(this._offsetY);
|
||||
const totalPanelHeight =
|
||||
Math.min(this.options.length * SELECT_OPTION_HEIGHT, SELECT_PANEL_MAX_HEIGHT);
|
||||
const 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. */
|
||||
private _adjustPanelUp(panelHeightBottom: number, bottomSpaceAvailable: number) {
|
||||
const 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. */
|
||||
private _adjustPanelDown(panelHeightTop: number, topSpaceAvailable: number,
|
||||
maxScroll: number) {
|
||||
const 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. */
|
||||
private _getOriginBasedOnOption(): string {
|
||||
const originY =
|
||||
Math.abs(this._offsetY) - SELECT_OPTION_HEIGHT_ADJUSTMENT + SELECT_OPTION_HEIGHT / 2;
|
||||
return `50% ${originY}px 0px`;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/** Clamps a value n between min and max values. */
|
||||
function clampValue(min: number, n: number, max: number): number {
|
||||
return Math.min(Math.max(min, n), max);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user