UNPKG

@mobilelivenpm/fds-angular-qa

Version:

This library was generated with [Nx](https://nx.dev).

1,148 lines (1,141 loc) 282 kB
import * as i0 from '@angular/core'; import { EventEmitter, Component, Input, Output, forwardRef, ChangeDetectionStrategy, ViewEncapsulation, ChangeDetectorRef, ViewChild, Directive, TemplateRef, ElementRef, ContentChild, ContentChildren, InjectionToken, SecurityContext, Renderer2, Inject, PLATFORM_ID, Optional, HostBinding, HostListener, NgZone, ViewContainerRef, ViewChildren, Injectable, SkipSelf, QueryList, Self, Injector, IterableDiffers, NgModule, Type } from '@angular/core'; import { isPlatformServer, DOCUMENT, CommonModule, Location } from '@angular/common'; import { NG_VALUE_ACCESSOR, NgControl } from '@angular/forms'; import tippy from 'tippy.js'; import { DomSanitizer } from '@angular/platform-browser'; import { FocusMonitor, ListKeyManager, FocusTrapFactory, ConfigurableFocusTrapFactory } from '@angular/cdk/a11y'; import { Directionality } from '@angular/cdk/bidi'; import { coerceBooleanProperty, coerceNumberProperty } from '@angular/cdk/coercion'; import { hasModifierKey, DOWN_ARROW, RIGHT_ARROW, UP_ARROW, LEFT_ARROW, HOME, END, PAGE_DOWN, PAGE_UP, ESCAPE } from '@angular/cdk/keycodes'; import { ANIMATION_MODULE_TYPE } from '@angular/platform-browser/animations'; import { normalizePassiveListenerOptions } from '@angular/cdk/platform'; import { Subscription, Subject, defer, of } from 'rxjs'; import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling'; import { UniqueSelectionDispatcher } from '@angular/cdk/collections'; import { trigger, state, style, transition, animate } from '@angular/animations'; import { CdkStepLabel, CdkStep, STEPPER_GLOBAL_OPTIONS, CdkStepper, CdkStepHeader, CdkStepperNext, CdkStepperPrevious } from '@angular/cdk/stepper'; import { takeUntil, distinctUntilChanged, filter, take, startWith } from 'rxjs/operators'; import { BasePortalOutlet, CdkPortalOutlet, ComponentPortal, TemplatePortal, PortalModule } from '@angular/cdk/portal'; import { Overlay, OverlayConfig, OverlayContainer, OverlayModule } from '@angular/cdk/overlay'; class ButtonComponent { constructor() { this.type = 'button'; this.iconPos = 'left'; // @ContentChildren(PrimeTemplate) templates: QueryList<any>; this.onClick = new EventEmitter(); this.onFocus = new EventEmitter(); this.onBlur = new EventEmitter(); } ngAfterContentInit() { // this.templates.forEach((item) => { // switch (item.getType()) { // case 'content': // this.contentTemplate = item.template; // break; // // default: // this.contentTemplate = item.template; // break; // } // }); } } ButtonComponent.decorators = [ { type: Component, args: [{ selector: 'fds-button', template: "<button\n [attr.type]=\"type\"\n [class]=\"className\"\n [ngStyle]=\"style\"\n [attr.aria-disabled]=\"ariaDisabled\"\n [ngClass]=\"{\n btn: true,\n 'p-button-icon-only': icon && !label,\n 'p-button-vertical':\n (iconPos === 'top' || iconPos === 'bottom') && label\n }\"\n (click)=\"onClick.emit($event)\"\n (focus)=\"onFocus.emit($event)\"\n (blur)=\"onBlur.emit($event)\"\n>\n <ng-content></ng-content>\n <ng-container *ngTemplateOutlet=\"contentTemplate\"></ng-container>\n <span\n [ngClass]=\"{\n 'p-button-icon': true,\n 'p-button-icon-left': iconPos === 'left' && label,\n 'p-button-icon-right': iconPos === 'right' && label,\n 'p-button-icon-top': iconPos === 'top' && label,\n 'p-button-icon-bottom': iconPos === 'bottom' && label\n }\"\n [class]=\"icon\"\n *ngIf=\"icon\"\n [attr.aria-hidden]=\"true\"\n ></span>\n <span class=\"p-button-label\" [attr.aria-hidden]=\"icon && !label\">{{\n label || '&nbsp;'\n }}</span>\n <span [ngClass]=\"'p-badge'\" *ngIf=\"badge\" [class]=\"badgeClass\">{{\n badge\n }}</span>\n</button>", styles: [""] },] } ]; ButtonComponent.propDecorators = { type: [{ type: Input }], iconPos: [{ type: Input }], icon: [{ type: Input }], badge: [{ type: Input }], label: [{ type: Input }], ariaDisabled: [{ type: Input }], style: [{ type: Input }], className: [{ type: Input }], badgeClass: [{ type: Input }], onClick: [{ type: Output }], onFocus: [{ type: Output }], onBlur: [{ type: Output }] }; const CHECKBOX_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CheckboxComponent), multi: true }; class CheckboxComponent { constructor(cd) { this.cd = cd; this.checkboxIcon = ''; this.onChange = new EventEmitter(); this.onModelChange = () => { }; this.onModelTouched = () => { }; this.focused = false; this.checked = false; } onClick(event, checkbox, focus) { event.preventDefault(); if (this.disabled || this.readonly) { return; } this.checked = !this.checked; this.updateModel(event); if (focus) { checkbox.focus(); } } updateModel(event) { if (!this.binary) { if (this.checked) this.addValue(); else this.removeValue(); this.onModelChange(this.model); if (this.formControl) { this.formControl.setValue(this.model); } } else { this.onModelChange(this.checked); } this.onChange.emit({ checked: this.checked, originalEvent: event }); } handleChange(event) { if (!this.readonly) { this.checked = event.target.checked; this.updateModel(event); } } isChecked() { if (this.binary) return this.model; else return this.model && this.model.indexOf(this.value) > -1; } removeValue() { this.model = this.model.filter(val => val !== this.value); } addValue() { if (this.model) this.model = [...this.model, this.value]; else this.model = [this.value]; } onFocus() { this.focused = true; } onBlur() { this.focused = false; this.onModelTouched(); } focus() { this.inputViewChild.nativeElement.focus(); } writeValue(model) { this.model = model; this.checked = this.isChecked(); this.cd.markForCheck(); } registerOnChange(fn) { this.onModelChange = fn; } registerOnTouched(fn) { this.onModelTouched = fn; } setDisabledState(val) { this.disabled = val; this.cd.markForCheck(); } } CheckboxComponent.decorators = [ { type: Component, args: [{ selector: 'fds-checkbox', template: "<div\n [ngStyle]=\"style\"\n [ngClass]=\"{\n formCheck: true,\n 'fds-checkbox-checked': checked,\n 'fds-checkbox-disabled': disabled,\n 'fds-checkbox-focused': focused\n }\"\n [class]=\"styleClass\"\n>\n <div class=\"checkBox checkBox--curved\">\n <input\n #cb\n type=\"checkbox\"\n class=\"checkBox\"\n [attr.id]=\"inputId\"\n [attr.name]=\"name\"\n [readonly]=\"readonly\"\n [value]=\"value\"\n [checked]=\"checked\"\n (focus)=\"onFocus()\"\n (blur)=\"onBlur()\"\n (change)=\"handleChange($event)\"\n [disabled]=\"disabled\"\n [attr.tabindex]=\"tabindex\"\n [attr.aria-labelledby]=\"ariaLabelledBy\"\n [attr.required]=\"required\"\n />\n <span class=\"checkboxFake\"></span>\n </div>\n <!-- TODO this div is not rendered and not read by screen reader -->\n <!-- <div\n class=\"fds-checkbox-box\"\n (click)=\"onClick($event, cb, true)\"\n [ngClass]=\"{\n 'fds-highlight': checked,\n 'fds-disabled': disabled,\n 'fds-focus': focused\n }\"\n role=\"checkbox\"\n [attr.aria-checked]=\"checked\"\n >\n <span\n class=\"fds-checkbox-icon\"\n [ngClass]=\"checked ? checkboxIcon : null\"\n ></span>\n </div> -->\n <label\n (click)=\"onClick($event, cb, true)\"\n [class]=\"labelStyleClass\"\n [ngClass]=\"{\n 'fds-checkbox-label checkLabel': true,\n 'fds-checkbox-label-active': checked,\n 'fds-disabled': disabled,\n 'fds-checkbox-label-focus': focused\n }\"\n *ngIf=\"label\"\n [attr.for]=\"inputId\"\n >{{ label }}</label\n >\n</div>", providers: [CHECKBOX_VALUE_ACCESSOR], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, styles: [""] },] } ]; CheckboxComponent.ctorParameters = () => [ { type: ChangeDetectorRef } ]; CheckboxComponent.propDecorators = { value: [{ type: Input }], name: [{ type: Input }], disabled: [{ type: Input }], binary: [{ type: Input }], label: [{ type: Input }], ariaLabelledBy: [{ type: Input }], tabindex: [{ type: Input }], inputId: [{ type: Input }], style: [{ type: Input }], styleClass: [{ type: Input }], labelStyleClass: [{ type: Input }], formControl: [{ type: Input }], checkboxIcon: [{ type: Input }], readonly: [{ type: Input }], required: [{ type: Input }], inputViewChild: [{ type: ViewChild, args: ['cb',] }], onChange: [{ type: Output }] }; class Header { } Header.decorators = [ { type: Component, args: [{ selector: 'fds-header', template: '<ng-content></ng-content>' },] } ]; class Footer { } Footer.decorators = [ { type: Component, args: [{ selector: 'fds-footer', template: '<ng-content></ng-content>' },] } ]; class Template { constructor(template) { this.template = template; } getType() { return this.name; } } Template.decorators = [ { type: Directive, args: [{ selector: '[fdsTemplate]' },] } ]; Template.ctorParameters = () => [ { type: TemplateRef } ]; Template.propDecorators = { type: [{ type: Input }], name: [{ type: Input, args: ['fdsTemplate',] }] }; class CardComponent { constructor(el) { this.el = el; } ngAfterContentInit() { this.templates.forEach(item => { switch (item.getType()) { case 'header': this.headerTemplate = item.template; break; case 'content': this.contentTemplate = item.template; break; case 'footer': this.footerTemplate = item.template; break; default: this.contentTemplate = item.template; break; } }); } } CardComponent.decorators = [ { type: Component, args: [{ selector: 'fds-card', template: "<div class=\"fds-card\" [ngStyle]=\"style\" [class]=\"cardClass\">\n <div\n class=\"fds-card-head\"\n [class]=\"headerClass\"\n *ngIf=\"headerFacet || headerTemplate\"\n >\n <ng-content select=\"fds-header\"></ng-content>\n <ng-container *ngTemplateOutlet=\"headerTemplate\"></ng-container>\n </div>\n <div class=\"fds-card-body\" [class]=\"bodyClass\">\n <ng-content></ng-content>\n <ng-container *ngTemplateOutlet=\"contentTemplate\"></ng-container>\n </div>\n <div\n class=\"fds-card-footer\"\n [class]=\"footerClass\"\n *ngIf=\"footerFacet || footerTemplate\"\n >\n <ng-content select=\"fds-footer\"></ng-content>\n <ng-container *ngTemplateOutlet=\"footerTemplate\"></ng-container>\n </div>\n</div>", styles: [""] },] } ]; CardComponent.ctorParameters = () => [ { type: ElementRef } ]; CardComponent.propDecorators = { style: [{ type: Input }], cardClass: [{ type: Input }], headerClass: [{ type: Input }], bodyClass: [{ type: Input }], footerClass: [{ type: Input }], headerFacet: [{ type: ContentChild, args: [Header,] }], footerFacet: [{ type: ContentChild, args: [Footer,] }], templates: [{ type: ContentChildren, args: [Template,] }] }; let uidIterator = 0; /** Injection token to be used to override the default options for `matPopover`. */ const FDS_POPOVER_DEFAULT_OPTIONS = new InjectionToken('mat-tooltip-default-options', { providedIn: 'root', factory: FDS_POPOVER_DEFAULT_OPTIONS_FACTORY }); /** @docs-private */ function FDS_POPOVER_DEFAULT_OPTIONS_FACTORY() { return { closeBtnScreenReadersText: 'Close button', placement: 'top', theme: 'dark', animation: 'shift-away' }; } class PopoverDirective { constructor(elementRef, renderer, domSanitizer, platform, _defaultOptions) { this.elementRef = elementRef; this.renderer = renderer; this.domSanitizer = domSanitizer; this.platform = platform; this._defaultOptions = _defaultOptions; this.fdsPopover = {}; this.tabindex = '0'; this.fdsPopoverUID = `fdsPopover` + uidIterator++; this.defProps = { arrow: true, maxWidth: 'auto', allowHTML: true, interactive: true, interactiveBorder: 50, trigger: 'manual' }; this.config = {}; } onClick() { if (this.tippyInstance) { if (!this.tippyInstance.state.isVisible) { this.tippyInstance.show(); } else { this.tippyInstance.hide(); } } } documentClick(e) { if (e.dataset && e.dataset.popoverId === this.fdsPopoverUID) { this.tippyInstance.hide(); } } ngOnInit() { if (isPlatformServer(this.platform)) return; this.initTippy(); } ngOnDestroy() { this.tippyInstance.destroy(); } ngOnChanges(changes) { if (!this.tippyInstance) return; if (changes['fdsPopover']) { // ReInit when any input was changed this.initTippy(); } else if (changes['fdsPopoverBody'] || changes['fdsPopoverTitle']) { this.updateTippyContent(); } } /** * Popover initialize */ initTippy() { if (this.tippyInstance) { this.tippyInstance.destroy(); } tippy(this.elementRef.nativeElement, this.getConfig()); this.setTippyInstance(); } updateTippyContent() { const { content } = this.getConfig(); this.tippyInstance.setContent(content); } getConfig() { const config = Object.assign(Object.assign(Object.assign({}, this.defProps), this._defaultOptions), this.fdsPopover); config.content = this.getTemplate(config.theme, config.closeBtnScreenReadersText); return config; } getTemplate(theme = 'dark', closeBtnText) { const classList = [ 'd--flex', 'align--items--start', 'p--3', 'curved', theme ]; return `<div class="${classList.join(' ')}" data-type="popover" tabindex="0" style="opacity: 1; visibility: visible; position:static;"> <span></span> <span tabindex="0"> ${this.getTitle() ? `<strong class="title">${this.getTitle()}</strong>` : ``} ${this.getBody()} </span> <a href="javascript:void(0)" tabindex="0" type="button" class="btn--close ml--3" data-popover-id="${this.fdsPopoverUID}"> <span class="icon icon-cross-circle" data-popover-id="${this.fdsPopoverUID}"> <span class="sr--only">${closeBtnText}</span> </span> </a> </div>`; } getTitle() { return this.domSanitizer.sanitize(SecurityContext.HTML, this.fdsPopoverTitle); } getBody() { return this.domSanitizer.sanitize(SecurityContext.HTML, this.fdsPopoverBody); } setTippyInstance() { this.tippyInstance = this.elementRef.nativeElement._tippy; } } PopoverDirective.decorators = [ { type: Directive, args: [{ selector: '[fdsPopover],[fdsPopoverBody]' },] } ]; PopoverDirective.ctorParameters = () => [ { type: ElementRef }, { type: Renderer2 }, { type: DomSanitizer }, { type: Object, decorators: [{ type: Inject, args: [PLATFORM_ID,] }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [FDS_POPOVER_DEFAULT_OPTIONS,] }] } ]; PopoverDirective.propDecorators = { fdsPopover: [{ type: Input }], fdsPopoverBody: [{ type: Input }], fdsPopoverTitle: [{ type: Input }], tabindex: [{ type: HostBinding, args: ['attr.tabindex',] }, { type: Input }], onClick: [{ type: HostListener, args: ['click',] }, { type: HostListener, args: ['keydown.space',] }, { type: HostListener, args: ['keydown.enter',] }], documentClick: [{ type: HostListener, args: ['document:click', ['$event.target'],] }] }; class ProgressComponent { constructor() { this.min = 0; this.max = 100; this.value = 0; this.showLabel = false; } ngOnInit() { } _getWidth() { const widthPercent = Math.floor(((this.value - this.min) / (this.max - this.min)) * 100); return Math.min(100, Math.max(0, widthPercent)); } _getLabelStyle() { // Label should not go out of boundaries, add compensation for min/max values if (this.value == this.min) { return { transform: 'none' }; } else if (this.value == this.max) { return { transform: 'translateX(-100%)' }; } return {}; } formatValue(value) { if (this.displayWith) { return this.displayWith(value); } return value || 0; } } ProgressComponent.decorators = [ { type: Component, args: [{ selector: 'fds-progress', template: "<div class=\"progress mb--5\">\n <div\n class=\"progress-bar progress-primary\"\n [style.width.%]=\"_getWidth()\"\n role=\"progressbar\"\n [attr.aria-valuenow]=\"value\"\n [attr.aria-valuemin]=\"min\"\n [attr.aria-valuemax]=\"max\"\n >\n <span\n role=\"alert\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n class=\"pt--2 px--2\"\n *ngIf=\"showLabel\"\n [ngStyle]=\"_getLabelStyle()\"\n >{{ formatValue(value) }}</span\n >\n </div>\n</div>", styles: [""] },] } ]; ProgressComponent.ctorParameters = () => []; ProgressComponent.propDecorators = { min: [{ type: Input }], max: [{ type: Input }], value: [{ type: Input }], showLabel: [{ type: Input }], displayWith: [{ type: Input }] }; const activeEventOptions = normalizePassiveListenerOptions({ passive: false }); /** * Visually, a 30px separation between tick marks looks best. This is very subjective but it is * the default separation we chose. */ const MIN_AUTO_TICK_SEPARATION = 30; /** The thumb gap size for a disabled slider. */ const DISABLED_THUMB_GAP = 7; /** The thumb gap size for a non-active slider at its minimum value. */ const MIN_VALUE_NONACTIVE_THUMB_GAP = 7; /** The thumb gap size for an active slider at its minimum value. */ const MIN_VALUE_ACTIVE_THUMB_GAP = 10; /** * Provider Expression that allows slider to register as a ControlValueAccessor. * This allows it to support [(ngModel)] and [formControl]. * @docs-private */ const MAT_SLIDER_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RangeSliderComponent), multi: true }; /** A simple change event emitted by the MatSlider component. */ class SliderChange { } /** * Allows users to select from a range of values by moving the slider thumb. It is similar in * behavior to the native `<input type="range">` element. */ class RangeSliderComponent { constructor(_elementRef, _focusMonitor, _changeDetectorRef, _dir, _ngZone, _document, _animationMode) { this._elementRef = _elementRef; this._focusMonitor = _focusMonitor; this._changeDetectorRef = _changeDetectorRef; this._dir = _dir; this._ngZone = _ngZone; this._animationMode = _animationMode; /** * Show min max labels */ this.showMinMaxLabels = false; /** Event emitted when the slider value has changed. */ this.change = new EventEmitter(); /** Event emitted when the slider thumb moves. */ this.input = new EventEmitter(); /** * Emits when the raw value of the slider changes. This is here primarily * to facilitate the two-way binding for the `value` input. * @docs-private */ this.valueChange = new EventEmitter(); /** * Whether or not the thumb is sliding. * Used to determine if there should be a transition for the thumb and fill track. */ this._isSliding = false; /** * Whether or not the slider is active (clicked or sliding). * Used to shrink and grow the thumb as according to the Material Design spec. */ this._isActive = false; /** The size of a tick interval as a percentage of the size of the track. */ this._tickIntervalPercent = 0; /** The dimensions of the slider. */ this._sliderDimensions = null; /** Subscription to the Directionality change EventEmitter. */ this._dirChangeSubscription = Subscription.EMPTY; this._disabled = false; this._tabIndex = 0; this._invert = false; this._max = 100; this._min = 0; this._step = 1; this._thumbLabel = false; this._tickInterval = 0; this._value = null; this._percent = 0; /** onTouch function registered via registerOnTouch (ControlValueAccessor). */ this.onTouched = () => { }; this._controlValueAccessorChangeFn = () => { }; /** Called when the user has put their pointer down on the slider. */ this._pointerDown = (event) => { // Don't do anything if the slider is disabled or the // user is using anything other than the main mouse button. if (this.disabled || this._isSliding || (!isTouchEvent(event) && event.button !== 0)) { return; } this._ngZone.run(() => { const oldValue = this.value; const pointerPosition = getPointerPositionOnPage(event); this._isSliding = true; this._lastPointerEvent = event; event.preventDefault(); this._focusHostElement(); this._onMouseenter(); // Simulate mouseenter in case this is a mobile device. this._bindGlobalEvents(event); this._focusHostElement(); this._updateValueFromPosition(pointerPosition); this._valueOnSlideStart = oldValue; // Emit a change and input event if the value changed. if (oldValue != this.value) { this._emitInputEvent(); } }); }; /** * Called when the user has moved their pointer after * starting to drag. Bound on the document level. */ this._pointerMove = (event) => { if (this._isSliding) { // Prevent the slide from selecting anything else. event.preventDefault(); const oldValue = this.value; this._lastPointerEvent = event; this._updateValueFromPosition(getPointerPositionOnPage(event)); // Native range elements always emit `input` events when the value changed while sliding. if (oldValue != this.value) { this._emitInputEvent(); } } }; /** Called when the user has lifted their pointer. Bound on the document level. */ this._pointerUp = (event) => { if (this._isSliding) { event.preventDefault(); this._removeGlobalEvents(); this._isSliding = false; if (this._valueOnSlideStart != this.value && !this.disabled) { this._emitChangeEvent(); } this._valueOnSlideStart = this._lastPointerEvent = null; } }; /** Called when the window has lost focus. */ this._windowBlur = () => { // If the window is blurred while dragging we need to stop dragging because the // browser won't dispatch the `mouseup` and `touchend` events anymore. if (this._lastPointerEvent) { this._pointerUp(this._lastPointerEvent); } }; this._document = _document; } get disabled() { return this._disabled; } set disabled(value) { this._disabled = coerceBooleanProperty(value); } get tabIndex() { return this.disabled ? -1 : this._tabIndex; } set tabIndex(value) { // If the specified tabIndex value is null or undefined, fall back to the default value. this._tabIndex = value != null ? coerceNumberProperty(value) : 0; } /** Whether the slider is inverted. */ get invert() { return this._invert; } set invert(value) { this._invert = coerceBooleanProperty(value); } /** The maximum value that the slider can have. */ get max() { return this._max; } set max(v) { this._max = coerceNumberProperty(v, this._max); this._percent = this._calculatePercentage(this._value); // Since this also modifies the percentage, we need to let the change detection know. this._changeDetectorRef.markForCheck(); } /** The minimum value that the slider can have. */ get min() { return this._min; } set min(v) { this._min = coerceNumberProperty(v, this._min); // If the value wasn't explicitly set by the user, set it to the min. if (this._value === null) { this.value = this._min; } this._percent = this._calculatePercentage(this._value); // Since this also modifies the percentage, we need to let the change detection know. this._changeDetectorRef.markForCheck(); } /** The values at which the thumb will snap. */ get step() { return this._step; } set step(v) { this._step = coerceNumberProperty(v, this._step); if (this._step % 1 !== 0) { this._roundToDecimal = this._step.toString().split('.').pop().length; } // Since this could modify the label, we need to notify the change detection. this._changeDetectorRef.markForCheck(); } /** Whether or not to show the thumb label. */ get thumbLabel() { return this._thumbLabel; } set thumbLabel(value) { this._thumbLabel = coerceBooleanProperty(value); } /** * How often to show ticks. Relative to the step so that a tick always appears on a step. * Ex: Tick interval of 4 with a step of 3 will draw a tick every 4 steps (every 12 values). */ get tickInterval() { return this._tickInterval; } set tickInterval(value) { if (value === 'auto') { this._tickInterval = 'auto'; } else if (typeof value === 'number' || typeof value === 'string') { this._tickInterval = coerceNumberProperty(value, this._tickInterval); } else { this._tickInterval = 0; } } /** Value of the slider. */ get value() { // If the value needs to be read and it is still uninitialized, initialize it to the min. if (this._value === null) { this.value = this._min; } return this._value; } set value(v) { if (v !== this._value) { let value = coerceNumberProperty(v); // While incrementing by a decimal we can end up with values like 33.300000000000004. // Truncate it to ensure that it matches the label and to make it easier to work with. if (this._roundToDecimal) { value = parseFloat(value.toFixed(this._roundToDecimal)); } this._value = value; this._percent = this._calculatePercentage(this._value); // Since this also modifies the percentage, we need to let the change detection know. this._changeDetectorRef.markForCheck(); } } /** The percentage of the slider that coincides with the value. */ get percent() { return this._clamp(this._percent); } /** set focus to the host element */ focus(options) { this._focusHostElement(options); } /** blur the host element */ blur() { this._blurHostElement(); } /** * Whether the axis of the slider is inverted. * (i.e. whether moving the thumb in the positive x or y direction decreases the slider's value). */ _shouldInvertAxis() { // Standard non-inverted mode for a vertical slider should be dragging the thumb from bottom to // top. However from a y-axis standpoint this is inverted. return this.invert; } /** Whether the slider is at its minimum value. */ _isMinValue() { return this.percent === 0; } /** * The amount of space to leave between the slider thumb and the track fill & track background * elements. */ _getThumbGap() { if (this.disabled) { return DISABLED_THUMB_GAP; } if (this._isMinValue() && !this.thumbLabel) { return this._isActive ? MIN_VALUE_ACTIVE_THUMB_GAP : MIN_VALUE_NONACTIVE_THUMB_GAP; } return 0; } /** CSS styles for the track background element. */ _getTrackBackgroundStyles() { const axis = 'X'; const scale = `${1 - this.percent}, 1, 1`; const sign = this._shouldInvertMouseCoords() ? '-' : ''; return { // scale3d avoids some rendering issues in Chrome. See #12071. transform: `translate${axis}(${sign}${this._getThumbGap()}px) scale3d(${scale})` }; } /** CSS styles for the track fill element. */ _getTrackFillStyles() { const percent = this.percent; const axis = 'X'; const scale = `${percent}, 1, 1`; const sign = this._shouldInvertMouseCoords() ? '' : '-'; return { // scale3d avoids some rendering issues in Chrome. See #12071. transform: `translate${axis}(${sign}${this._getThumbGap()}px) scale3d(${scale})`, // iOS Safari has a bug where it won't re-render elements which start of as `scale(0)` until // something forces a style recalculation on it. Since we'll end up with `scale(0)` when // the value of the slider is 0, we can easily get into this situation. We force a // recalculation by changing the element's `display` when it goes from 0 to any other value. display: percent === 0 ? 'none' : '' }; } /** CSS styles for the ticks container element. */ _getTicksContainerStyles() { let axis = 'X'; // For a horizontal slider in RTL languages we push the ticks container off the left edge // instead of the right edge to avoid causing a horizontal scrollbar to appear. let sign = this._getDirection() == 'rtl' ? '' : '-'; let offset = (this._tickIntervalPercent / 2) * 100; return { transform: `translate${axis}(${sign}${offset}%)` }; } /** CSS styles for the ticks element. */ _getTicksStyles() { let tickSize = this._tickIntervalPercent * 100; let backgroundSize = `${tickSize}% 2px`; let axis = 'X'; // Depending on the direction we pushed the ticks container, push the ticks the opposite // direction to re-center them but clip off the end edge. In RTL languages we need to flip the // ticks 180 degrees so we're really cutting off the end edge abd not the start. let sign = this._getDirection() == 'rtl' ? '-' : ''; let rotate = this._getDirection() == 'rtl' ? ' rotate(180deg)' : ''; let styles = { backgroundSize: backgroundSize, // Without translateZ ticks sometimes jitter as the slider moves on Chrome & Firefox. transform: `translateZ(0) translate${axis}(${sign}${tickSize / 2}%)${rotate}` }; if (this._isMinValue() && this._getThumbGap()) { const side = this._shouldInvertAxis() ? 'Right' : 'Left'; styles[`padding${side}`] = `${this._getThumbGap()}px`; } return styles; } _getThumbContainerStyles() { const shouldInvertAxis = this._shouldInvertAxis(); let axis = 'X'; // For a horizontal slider in RTL languages we push the thumb container off the left edge // instead of the right edge to avoid causing a horizontal scrollbar to appear. let invertOffset = this._getDirection() == 'rtl' ? !shouldInvertAxis : shouldInvertAxis; let offset = (invertOffset ? this.percent : 1 - this.percent) * 100; return { transform: `translate${axis}(-${offset}%)` }; } /** * Whether mouse events should be converted to a slider position by calculating their distance * from the right or bottom edge of the slider as opposed to the top or left. */ _shouldInvertMouseCoords() { const shouldInvertAxis = this._shouldInvertAxis(); return this._getDirection() == 'rtl' ? !shouldInvertAxis : shouldInvertAxis; } ngAfterViewInit() { this._ngZone.runOutsideAngular(() => { const element = this._sliderWrapper.nativeElement; element.addEventListener('mousedown', this._pointerDown, activeEventOptions); element.addEventListener('touchstart', this._pointerDown, activeEventOptions); }); this._focusMonitor .monitor(this._sliderWrapper, true) .subscribe((origin) => { this._isActive = !!origin && origin !== 'keyboard'; this._changeDetectorRef.detectChanges(); }); if (this._dir) { this._dirChangeSubscription = this._dir.change.subscribe(() => { this._changeDetectorRef.markForCheck(); }); } } ngOnDestroy() { // There is no _sliderWrapper element when component is dynamically created and didn't attached to the DOM if (this._sliderWrapper) { const element = this._sliderWrapper.nativeElement; element.removeEventListener('mousedown', this._pointerDown, activeEventOptions); element.removeEventListener('touchstart', this._pointerDown, activeEventOptions); } this._lastPointerEvent = null; this._removeGlobalEvents(); this._focusMonitor.stopMonitoring(this._sliderWrapper); this._dirChangeSubscription.unsubscribe(); } _onMouseenter() { if (this.disabled) { return; } // We save the dimensions of the slider here so we can use them to update the spacing of the // ticks and determine where on the slider click and slide events happen. this._sliderDimensions = this._getSliderDimensions(); this._updateTickIntervalPercent(); } _onFocus() { // We save the dimensions of the slider here so we can use them to update the spacing of the // ticks and determine where on the slider click and slide events happen. this._sliderDimensions = this._getSliderDimensions(); this._updateTickIntervalPercent(); } _onBlur() { this.onTouched(); } _onKeydown(event) { if (this.disabled || hasModifierKey(event)) { return; } const oldValue = this.value; switch (event.keyCode) { case PAGE_UP: this._increment(10); break; case PAGE_DOWN: this._increment(-10); break; case END: this.value = this.max; break; case HOME: this.value = this.min; break; case LEFT_ARROW: // NOTE: For a sighted user it would make more sense that when they press an arrow key on an // inverted slider the thumb moves in that direction. However for a blind user, nothing // about the slider indicates that it is inverted. They will expect left to be decrement, // regardless of how it appears on the screen. For speakers ofRTL languages, they probably // expect left to mean increment. Therefore we flip the meaning of the side arrow keys for // RTL. For inverted sliders we prefer a good a11y experience to having it "look right" for // sighted users, therefore we do not swap the meaning. this._increment(this._getDirection() == 'rtl' ? 1 : -1); break; case UP_ARROW: this._increment(1); break; case RIGHT_ARROW: // See comment on LEFT_ARROW about the conditions under which we flip the meaning. this._increment(this._getDirection() == 'rtl' ? -1 : 1); break; case DOWN_ARROW: this._increment(-1); break; default: // Return if the key is not one that we explicitly handle to avoid calling preventDefault on // it. return; } if (oldValue != this.value) { this._emitInputEvent(); this._emitChangeEvent(); } this._isSliding = true; event.preventDefault(); } _onKeyup() { this._isSliding = false; } /** * Sets the model value. Implemented as part of ControlValueAccessor. * @param value */ writeValue(value) { this.value = value; } /** * Registers a callback to be triggered when the value has changed. * Implemented as part of ControlValueAccessor. * @param fn Callback to be registered. */ registerOnChange(fn) { this._controlValueAccessorChangeFn = fn; } /** * Registers a callback to be triggered when the component is touched. * Implemented as part of ControlValueAccessor. * @param fn Callback to be registered. */ registerOnTouched(fn) { this.onTouched = fn; } /** * Sets whether the component should be disabled. * Implemented as part of ControlValueAccessor. * @param isDisabled */ setDisabledState(isDisabled) { this.disabled = isDisabled; } /** The language direction for this slider element. */ _getDirection() { return this._dir && this._dir.value == 'rtl' ? 'rtl' : 'ltr'; } /** Use defaultView of injected document if available or fallback to global window reference */ _getWindow() { return this._document.defaultView || window; } /** * Binds our global move and end events. They're bound at the document level and only while * dragging so that the user doesn't have to keep their pointer exactly over the slider * as they're swiping across the screen. */ _bindGlobalEvents(triggerEvent) { // Note that we bind the events to the `document`, because it allows us to capture // drag cancel events where the user's pointer is outside the browser window. const document = this._document; const isTouch = isTouchEvent(triggerEvent); const moveEventName = isTouch ? 'touchmove' : 'mousemove'; const endEventName = isTouch ? 'touchend' : 'mouseup'; document.addEventListener(moveEventName, this._pointerMove, activeEventOptions); document.addEventListener(endEventName, this._pointerUp, activeEventOptions); if (isTouch) { document.addEventListener('touchcancel', this._pointerUp, activeEventOptions); } const window = this._getWindow(); if (typeof window !== 'undefined' && window) { window.addEventListener('blur', this._windowBlur); } } /** Removes any global event listeners that we may have added. */ _removeGlobalEvents() { const document = this._document; document.removeEventListener('mousemove', this._pointerMove, activeEventOptions); document.removeEventListener('mouseup', this._pointerUp, activeEventOptions); document.removeEventListener('touchmove', this._pointerMove, activeEventOptions); document.removeEventListener('touchend', this._pointerUp, activeEventOptions); document.removeEventListener('touchcancel', this._pointerUp, activeEventOptions); const window = this._getWindow(); if (typeof window !== 'undefined' && window) { window.removeEventListener('blur', this._windowBlur); } } /** Increments the slider by the given number of steps (negative number decrements). */ _increment(numSteps) { this.value = this._clamp((this.value || 0) + this.step * numSteps, this.min, this.max); } /** Calculate the new value from the new physical location. The value will always be snapped. */ _updateValueFromPosition(pos) { if (!this._sliderDimensions) { return; } let offset = this._sliderDimensions.left; let size = this._sliderDimensions.width; let posComponent = pos.x; // The exact value is calculated from the event and used to find the closest snap value. let percent = this._clamp((posComponent - offset) / size); if (this._shouldInvertMouseCoords()) { percent = 1 - percent; } // Since the steps may not divide cleanly into the max value, if the user // slid to 0 or 100 percent, we jump to the min/max value. This approach // is slightly more intuitive than using `Math.ceil` below, because it // follows the user's pointer closer. if (percent === 0) { this.value = this.min; } else if (percent === 1) { this.value = this.max; } else { const exactValue = this._calculateValue(percent); // This calculation finds the closest step by finding the closest // whole number divisible by the step relative to the min. const closestValue = Math.round((exactValue - this.min) / this.step) * this.step + this.min; // The value needs to snap to the min and max. this.value = this._clamp(closestValue, this.min, this.max); } } /** Emits a change event if the current value is different from the last emitted value. */ _emitChangeEvent() { this._controlValueAccessorChangeFn(this.value); this.valueChange.emit(this.value); this.change.emit(this._createChangeEvent()); } /** Emits an input event when the current value is different from the last emitted value. */ _emitInputEvent() { this.input.emit(this._createChangeEvent()); } /** Updates the amount of space between ticks as a percentage of the width of the slider. */ _updateTickIntervalPercent() { if (!this.tickInterval || !this._sliderDimensions) { return; } if (this.tickInterval == 'auto') { let trackSize = this._sliderDimensions.width; let pixelsPerStep = (trackSize * this.step) / (this.max - this.min); let stepsPerTick = Math.ceil(MIN_AUTO_TICK_SEPARATION / pixelsPerStep); let pixelsPerTick = stepsPerTick * this.step; this._tickIntervalPercent = pixelsPerTick / trackSize; } else { this._tickIntervalPercent = (this.tickInterval * this.step) / (this.max - this.min); } } /** Creates a slider change object from the specified value. */ _createChangeEvent(value = this.value) { let event = new SliderChange(); event.source = this; event.value = value; return event; } /** Calculates the percentage of the slider that a value is. */ _calculatePercentage(value) { return ((value || 0) - this.min) / (this.max - this.min); } /** Calculates the value a percentage of the slider corresponds to. */ _calculateValue(percentage) { return this.min + percentage * (this.max - this.min); } /** Return a number between two numbers. */ _clamp(value, min = 0, max = 1) { return Math.max(min, Math.min(value, max)); } /** * Get the bounding client rect of the slider track element. * The track is used rather than the native element to ignore the extra space that the thumb can * take up. */ _getSliderDimensions() { return this._sliderWrapper ? this._sliderWrapper.nativeElement.getBoundingClientRect() : null; } /** * Focuses the native element. * Currently only used to allow a blur event to fire but will be used with keyboard input later. */ _focusHostElement(options) { this._sliderWrapper.nativeElement.focus(options); } /** Blurs the native element. */ _blurHostElement() { this._sliderWrapper.nativeElement.blur(); } /** The value to be used for display purposes. */ formatValue(value) { if (this.displayWith) { // Value is never null but since setters and getters cannot have // different types, the value getter is also typed to return null. return this.displayWith(value); } // Note that this could be improved further by rounding something like 0.999 to 1 or // 0.899 to 0.9, however it is very performance sensitive, because it gets called on // every change detection cycle. if (this._roundToDecimal && value && value % 1 !== 0) { return value.toFixed(this._roundToDecimal); } return value || 0; } } RangeSliderComponent.decorators = [ { type: Component, args: [{ selector: 'fds-range-slider', template: "<div\n class=\"d--flex justify--content--between pb-3 slider-labels\"\n *ngIf=\"showMinMaxLabels\"\n>\n <span class=\"slider-label-min\">{{ formatValue(min) }}</span>\n <span class=\"slider-label-max\">{{ formatValue(max) }}</span>\n</div>\n<!--\n// On Safari starting to slide temporarily triggers text selection mode which\n// show the wrong cursor. We prevent it by stopping the `selectstart` event.\n \"(selectstart)\": \"$event.preventDefault()\",\n-->\n<div\n class=\"slider-wrapper\"\n #sliderWrapper\n (focus)=\"_onFocus()\"\n (blur)=\"_onBlur()\"\n (keydown)=\"_onKeydown($event)\"\n (keyup)=\"_onKeyup()\"\n (mouseenter)=\"_onMouseenter()\"\n (selectstart)=\"$event.preventDefault()\"\n role=\"slider\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n [tabIndex]=\"tabIndex\"\n [attr.aria-disabled]=\"disabled\"\n [attr.aria-valuemax]=\"max\"\n [attr.aria-valuemin]=\"min\"\n [attr.aria-valuenow]=\"value\"\n [attr.aria-orientation]=\"'horizontal'\"\n>\n <div class=\"slider-track-wrapper\">\n <div class=\"slider-track-background\"></div>\n <div class=\"slider-track-fill\" [ngStyle]=\"_getTrackFillStyles()\"></div>\n </div>\n <div class=\"slider-ticks-container\">\n <div class=\"slider-ticks\" [ngStyle]=\"_getTicksContainerStyles()\"></div>\n </div>\n <div class=\"slider-thumb-container\" [ngStyle]=\"_getThumbContainerStyles()\">\n <div class=\"slider-focus-ring\"></div>\n <div class=\"slider-thumb\"></div>\n <div class=\"slider-thumb-label\">\n <span class=\"slider-thumb-label-text\">{{ formatValue(value) }}</span>\n </div>\n </div>\n</div>", providers: [MAT_SLIDER_VALUE_ACCESSOR], host: { class: 'slider focus-indicator', '[class.slider-disabled]': 'disabled', '[class.slider-has-ticks]': 'tickInterval', '[class.slider-horizontal]': 'true', '[class.slider-axis-inverted]': '_shouldInvertAxis()', // Class binding which is only used by the test harness as there is no other // way for the harness to detect if mouse coordinates need to be inverted. '[class.slider-invert-mouse-coords]': '_shouldInvertMouseCoords()', '[class.slider-sliding]': '_isSliding', '[class.slider-thumb-label-showing]': 'thumbLabel', '[class.slider-min-value]': '_isMinValue()', '[class.slider-hide-last-tick]': 'disabled || _isMinValue() && _getThumbGap() && _shouldInvertAxis()', '[class._animation-noopable]': '_animationMode === "NoopAnimations"' }, encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, styles: [""] },] } ]; RangeSliderComponent.ctorParameters = () => [ { type: ElementRef }, { type: FocusMonitor }, { type