Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(autocomplete): add fallback positions #2705

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 51 additions & 6 deletions src/demo-app/autocomplete/autocomplete-demo.html
Original file line number Diff line number Diff line change
@@ -1,9 +1,54 @@
Space above cards: <input type="number" [formControl]="topHeightCtrl">
<div [style.height.px]="topHeightCtrl.value"></div>
<div class="demo-autocomplete">
<md-input-container>
<input mdInput placeholder="State" [mdAutocomplete]="auto">
</md-input-container>
<md-card>
<div>Reactive value: {{ stateCtrl.value }}</div>
<div>Reactive dirty: {{ stateCtrl.dirty }}</div>

<md-autocomplete #auto="mdAutocomplete">
<md-option *ngFor="let state of states" [value]="state.code"> {{ state.name }} </md-option>
</md-autocomplete>
<md-input-container>
<input mdInput placeholder="State" [mdAutocomplete]="reactiveAuto" [formControl]="stateCtrl">
</md-input-container>

<md-card-actions>
<button md-button (click)="stateCtrl.reset()">RESET</button>
<button md-button (click)="stateCtrl.setValue('California')">SET VALUE</button>
<button md-button (click)="stateCtrl.enabled ? stateCtrl.disable() : stateCtrl.enable()">
TOGGLE DISABLED
</button>
</md-card-actions>

</md-card>

<md-card>
<div>Template-driven value (currentState): {{ currentState }}</div>
<div>Template-driven dirty: {{ modelDir.dirty }}</div>

<md-input-container>
<input mdInput placeholder="State" [mdAutocomplete]="tdAuto" [(ngModel)]="currentState" #modelDir="ngModel"
(ngModelChange)="this.tdStates = filterStates(currentState)" [disabled]="tdDisabled">
</md-input-container>

<md-card-actions>
<button md-button (click)="modelDir.reset()">RESET</button>
<button md-button (click)="currentState='California'">SET VALUE</button>
<button md-button (click)="tdDisabled=!tdDisabled">
TOGGLE DISABLED
</button>
</md-card-actions>

</md-card>
</div>

<md-autocomplete #reactiveAuto="mdAutocomplete">
<md-option *ngFor="let state of reactiveStates" [value]="state.name">
<span>{{ state.name }}</span>
<span class="demo-secondary-text"> ({{state.code}}) </span>
</md-option>
</md-autocomplete>

<md-autocomplete #tdAuto="mdAutocomplete">
<md-option *ngFor="let state of tdStates" [value]="state.name">
<span>{{ state.name }}</span>
<span class="demo-secondary-text"> ({{state.code}}) </span>
</md-option>
</md-autocomplete>
19 changes: 18 additions & 1 deletion src/demo-app/autocomplete/autocomplete-demo.scss
Original file line number Diff line number Diff line change
@@ -1 +1,18 @@
.demo-autocomplete {}
.demo-autocomplete {
display: flex;
flex-flow: row wrap;

md-card {
width: 350px;
margin: 24px;
}

md-input-container {
margin-top: 16px;
}
}

.demo-secondary-text {
color: rgba(0, 0, 0, 0.54);
margin-left: 8px;
}
34 changes: 32 additions & 2 deletions src/demo-app/autocomplete/autocomplete-demo.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import {Component} from '@angular/core';
import {Component, OnDestroy, ViewEncapsulation} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Subscription} from 'rxjs/Subscription';

@Component({
moduleId: module.id,
selector: 'autocomplete-demo',
templateUrl: 'autocomplete-demo.html',
styleUrls: ['autocomplete-demo.css'],
encapsulation: ViewEncapsulation.None
})
export class AutocompleteDemo {
export class AutocompleteDemo implements OnDestroy {
stateCtrl = new FormControl();
currentState = '';
topHeightCtrl = new FormControl(0);

reactiveStates: any[];
tdStates: any[];

reactiveValueSub: Subscription;
tdDisabled = false;

states = [
{code: 'AL', name: 'Alabama'},
{code: 'AZ', name: 'Arizona'},
Expand Down Expand Up @@ -35,4 +48,21 @@ export class AutocompleteDemo {
{code: 'WI', name: 'Wisconsin'},
{code: 'WY', name: 'Wyoming'},
];

constructor() {
this.reactiveStates = this.states;
this.tdStates = this.states;
this.reactiveValueSub =
this.stateCtrl.valueChanges.subscribe(val => this.reactiveStates = this.filterStates(val));

}

filterStates(val: string) {
return val ? this.states.filter((s) => s.name.match(new RegExp(val, 'gi'))) : this.states;
}

ngOnDestroy() {
this.reactiveValueSub.unsubscribe();
}

}
6 changes: 4 additions & 2 deletions src/lib/autocomplete/_autocomplete-theme.scss
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
$foreground: map-get($theme, foreground);
$background: map-get($theme, background);

md-option {
.md-autocomplete-panel {
background: md-color($background, card);
color: md-color($foreground, text);
}

&.md-selected {
md-option {
&.md-selected:not(.md-active) {
background: md-color($background, card);
color: md-color($foreground, text);
}
Expand Down
127 changes: 110 additions & 17 deletions src/lib/autocomplete/autocomplete-trigger.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,57 @@
import {Directive, ElementRef, Input, ViewContainerRef, OnDestroy} from '@angular/core';
import {
AfterContentInit, Directive, ElementRef, Input, ViewContainerRef, Optional, OnDestroy
} from '@angular/core';
import {NgControl} from '@angular/forms';
import {Overlay, OverlayRef, OverlayState, TemplatePortal} from '../core';
import {MdAutocomplete} from './autocomplete';
import {PositionStrategy} from '../core/overlay/position/position-strategy';
import {ConnectedPositionStrategy} from '../core/overlay/position/connected-position-strategy';
import {Observable} from 'rxjs/Observable';
import {MdOptionSelectEvent, MdOption} from '../core/option/option';
import {ActiveDescendantKeyManager} from '../core/a11y/activedescendant-key-manager';
import {ENTER} from '../core/keyboard/keycodes';
import {Subscription} from 'rxjs/Subscription';
import 'rxjs/add/observable/merge';

/** The panel needs a slight y-offset to ensure the input underline displays. */
export const MD_AUTOCOMPLETE_PANEL_OFFSET = 6;
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/switchMap';

@Directive({
selector: 'input[mdAutocomplete], input[matAutocomplete]',
host: {
'(focus)': 'openPanel()'
'(focus)': 'openPanel()',
'(keydown)': '_handleKeydown($event)',
'autocomplete': 'off'
}
})
export class MdAutocompleteTrigger implements OnDestroy {
export class MdAutocompleteTrigger implements AfterContentInit, OnDestroy {
private _overlayRef: OverlayRef;
private _portal: TemplatePortal;
private _panelOpen: boolean = false;

/** The subscription to events that close the autocomplete panel. */
private _closingActionsSubscription: Subscription;
/** The subscription to positioning changes in the autocomplete panel. */
private _panelPositionSub: Subscription;

/** Manages active item in option list based on key events. */
private _keyManager: ActiveDescendantKeyManager;

/* The autocomplete panel to be attached to this trigger. */
@Input('mdAutocomplete') autocomplete: MdAutocomplete;

constructor(private _element: ElementRef, private _overlay: Overlay,
private _viewContainerRef: ViewContainerRef) {}
private _viewContainerRef: ViewContainerRef,
@Optional() private _controlDir: NgControl) {}

ngAfterContentInit() {
this._keyManager = new ActiveDescendantKeyManager(this.autocomplete.options);
}

ngOnDestroy() { this._destroyPanel(); }
ngOnDestroy() {
if (this._panelPositionSub) {
this._panelPositionSub.unsubscribe();
}

this._destroyPanel();
}

/* Whether or not the autocomplete panel is open. */
get panelOpen(): boolean {
Expand All @@ -44,8 +66,7 @@ export class MdAutocompleteTrigger implements OnDestroy {

if (!this._overlayRef.hasAttached()) {
this._overlayRef.attach(this._portal);
this._closingActionsSubscription =
this.panelClosingActions.subscribe(() => this.closePanel());
this._subscribeToClosingActions();
}

this._panelOpen = true;
Expand All @@ -57,7 +78,6 @@ export class MdAutocompleteTrigger implements OnDestroy {
this._overlayRef.detach();
}

this._closingActionsSubscription.unsubscribe();
this._panelOpen = false;
}

Expand All @@ -66,15 +86,53 @@ export class MdAutocompleteTrigger implements OnDestroy {
* when an option is selected and when the backdrop is clicked.
*/
get panelClosingActions(): Observable<any> {
// TODO(kara): add tab event observable with keyboard event PR
return Observable.merge(...this.optionSelections, this._overlayRef.backdropClick());
return Observable.merge(
...this.optionSelections,
this._overlayRef.backdropClick(),
this._keyManager.tabOut
);
}

/** Stream of autocomplete option selections. */
get optionSelections(): Observable<any>[] {
return this.autocomplete.options.map(option => option.onSelect);
}

/** The currently active option, coerced to MdOption type. */
get activeOption(): MdOption {
return this._keyManager.activeItem as MdOption;
}

_handleKeydown(event: KeyboardEvent): void {
if (this.activeOption && event.keyCode === ENTER) {
this.activeOption._selectViaInteraction();
} else {
this.openPanel();
this._keyManager.onKeydown(event);
}
}

/**
* This method listens to a stream of panel closing actions and resets the
* stream every time the option list changes.
*/
private _subscribeToClosingActions(): void {
// Every time the option list changes...
this.autocomplete.options.changes
// and also at initialization, before there are any option changes...
.startWith(null)
// create a new stream of panelClosingActions, replacing any previous streams
// that were created, and flatten it so our stream only emits closing events...
.switchMap(() => {
this._resetActiveItem();
return this.panelClosingActions;
})
// when the first closing event occurs...
.first()
// set the value, close the panel, and complete.
.subscribe(event => this._setValueAndClose(event));
}

/** Destroys the autocomplete suggestion panel. */
private _destroyPanel(): void {
if (this._overlayRef) {
Expand All @@ -84,6 +142,22 @@ export class MdAutocompleteTrigger implements OnDestroy {
}
}

/**
* This method closes the panel, and if a value is specified, also sets the associated
* control to that value. It will also mark the control as dirty if this interaction
* stemmed from the user.
*/
private _setValueAndClose(event: MdOptionSelectEvent | null): void {
if (event) {
this._controlDir.control.setValue(event.source.value);
if (event.isUserInput) {
this._controlDir.control.markAsDirty();
}
}

this.closePanel();
}

private _createOverlay(): void {
this._portal = new TemplatePortal(this.autocomplete.template, this._viewContainerRef);
this._overlayRef = this._overlay.create(this._getOverlayConfig());
Expand All @@ -99,16 +173,35 @@ export class MdAutocompleteTrigger implements OnDestroy {
}

private _getOverlayPosition(): PositionStrategy {
return this._overlay.position().connectedTo(
const strategy = this._overlay.position().connectedTo(
this._element,
{originX: 'start', originY: 'bottom'}, {overlayX: 'start', overlayY: 'top'})
.withOffsetY(MD_AUTOCOMPLETE_PANEL_OFFSET);
.withFallbackPosition(
{originX: 'start', originY: 'top'}, {overlayX: 'start', overlayY: 'bottom'}
);
this._subscribeToPositionChanges(strategy);
return strategy;
}

/**
* This method subscribes to position changes in the autocomplete panel, so the panel's
* y-offset can be adjusted to match the new position.
*/
private _subscribeToPositionChanges(strategy: ConnectedPositionStrategy) {
this._panelPositionSub = strategy.onPositionChange.subscribe(change => {
this.autocomplete.positionY = change.connectionPair.originY === 'top' ? 'above' : 'below';
});
}

/** Returns the width of the input element, so the panel width can match it. */
private _getHostWidth(): number {
return this._element.nativeElement.getBoundingClientRect().width;
}

/** Reset active item to -1 so DOWN_ARROW event will activate the first option.*/
private _resetActiveItem(): void {
this._keyManager.setActiveItem(-1);
}

}

2 changes: 1 addition & 1 deletion src/lib/autocomplete/autocomplete.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<template>
<div class="md-autocomplete-panel">
<div class="md-autocomplete-panel" [ngClass]="_getPositionClass()">
<ng-content></ng-content>
</div>
</template>
23 changes: 23 additions & 0 deletions src/lib/autocomplete/autocomplete.scss
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
@import '../core/style/menu-common';

/**
* The max-height of the panel, currently matching md-select value.
* TODO: Check value with MD team.
*/
$md-autocomplete-panel-max-height: 256px !default;

/** When in "below" position, the panel needs a slight y-offset to ensure the input underline displays. */
$md-autocomplete-panel-below-offset: 6px !default;

/** When in "above" position, the panel needs a larger y-offset to ensure the label has room to display. */
$md-autocomplete-panel-above-offset: -24px !default;

.md-autocomplete-panel {
@include md-menu-base();

max-height: $md-autocomplete-panel-max-height;
position: relative;

&.md-autocomplete-panel-below {
top: $md-autocomplete-panel-below-offset;
}

&.md-autocomplete-panel-above {
top: $md-autocomplete-panel-above-offset;
}
}
Loading