_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
components/src/cdk-experimental/column-resize/column-resize-notifier.ts_0_2199
/** * @license * Copyright Google LLC 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.dev/license */ import {inject, Injectable} from '@angular/core'; import {Observable, Subject} from 'rxjs'; /** Indicates the width of a column. */ export interface ColumnSize { /** The ID/name of the column, as defined in CdkColumnDef. */ readonly columnId: string; /** The width in pixels of the column. */ readonly size: number; /** The width in pixels of the column prior to this update, if known. */ readonly previousSize?: number; } /** Interface describing column size changes. */ export interface ColumnSizeAction extends ColumnSize { /** * Whether the resize action should be applied instantaneously. False for events triggered during * a UI-triggered resize (such as with the mouse) until the mouse button is released. True * for all programmatically triggered resizes. */ readonly completeImmediately?: boolean; /** * Whether the resize action is being applied to a sticky/stickyEnd column. */ readonly isStickyColumn?: boolean; } /** * Originating source of column resize events within a table. * @docs-private */ @Injectable() export class ColumnResizeNotifierSource { /** Emits when an in-progress resize is canceled. */ readonly resizeCanceled = new Subject<ColumnSizeAction>(); /** Emits when a resize is applied. */ readonly resizeCompleted = new Subject<ColumnSize>(); /** Triggers a resize action. */ readonly triggerResize = new Subject<ColumnSizeAction>(); } /** Service for triggering column resizes imperatively or being notified of them. */ @Injectable() export class ColumnResizeNotifier { private readonly _source = inject(ColumnResizeNotifierSource); /** Emits whenever a column is resized. */ readonly resizeCompleted: Observable<ColumnSize> = this._source.resizeCompleted; /** Instantly resizes the specified column. */ resize(columnId: string, size: number): void { this._source.triggerResize.next({ columnId, size, completeImmediately: true, isStickyColumn: true, }); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2199, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-resize-notifier.ts" }
components/src/cdk-experimental/column-resize/resizable.ts_0_9238
/** * @license * Copyright Google LLC 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.dev/license */ import { AfterViewInit, Directive, ElementRef, Injector, NgZone, OnDestroy, Type, ViewContainerRef, ChangeDetectorRef, } from '@angular/core'; import {Directionality} from '@angular/cdk/bidi'; import {ComponentPortal} from '@angular/cdk/portal'; import {Overlay, OverlayRef} from '@angular/cdk/overlay'; import {CdkColumnDef, _CoalescedStyleScheduler} from '@angular/cdk/table'; import {merge, Subject} from 'rxjs'; import {filter, takeUntil} from 'rxjs/operators'; import {_closest} from '@angular/cdk-experimental/popover-edit'; import {HEADER_ROW_SELECTOR} from './selectors'; import {ResizeOverlayHandle} from './overlay-handle'; import {ColumnResize} from './column-resize'; import {ColumnSizeAction, ColumnResizeNotifierSource} from './column-resize-notifier'; import {HeaderRowEventDispatcher} from './event-dispatcher'; import {ResizeRef} from './resize-ref'; import {ResizeStrategy} from './resize-strategy'; const OVERLAY_ACTIVE_CLASS = 'cdk-resizable-overlay-thumb-active'; /** * Base class for Resizable directives which are applied to column headers to make those columns * resizable. */ @Directive() export abstract class Resizable<HandleComponent extends ResizeOverlayHandle> implements AfterViewInit, OnDestroy { protected minWidthPxInternal: number = 0; protected maxWidthPxInternal: number = Number.MAX_SAFE_INTEGER; protected inlineHandle?: HTMLElement; protected overlayRef?: OverlayRef; protected readonly destroyed = new Subject<void>(); protected abstract readonly columnDef: CdkColumnDef; protected abstract readonly columnResize: ColumnResize; protected abstract readonly directionality: Directionality; protected abstract readonly document: Document; protected abstract readonly elementRef: ElementRef; protected abstract readonly eventDispatcher: HeaderRowEventDispatcher; protected abstract readonly injector: Injector; protected abstract readonly ngZone: NgZone; protected abstract readonly overlay: Overlay; protected abstract readonly resizeNotifier: ColumnResizeNotifierSource; protected abstract readonly resizeStrategy: ResizeStrategy; protected abstract readonly styleScheduler: _CoalescedStyleScheduler; protected abstract readonly viewContainerRef: ViewContainerRef; protected abstract readonly changeDetectorRef: ChangeDetectorRef; private _viewInitialized = false; private _isDestroyed = false; /** The minimum width to allow the column to be sized to. */ get minWidthPx(): number { return this.minWidthPxInternal; } set minWidthPx(value: number) { this.minWidthPxInternal = value; this.columnResize.setResized(); if (this.elementRef.nativeElement && this._viewInitialized) { this._applyMinWidthPx(); } } /** The maximum width to allow the column to be sized to. */ get maxWidthPx(): number { return this.maxWidthPxInternal; } set maxWidthPx(value: number) { this.maxWidthPxInternal = value; this.columnResize.setResized(); if (this.elementRef.nativeElement && this._viewInitialized) { this._applyMaxWidthPx(); } } ngAfterViewInit() { this._listenForRowHoverEvents(); this._listenForResizeEvents(); this._appendInlineHandle(); this.styleScheduler.scheduleEnd(() => { if (this._isDestroyed) return; this._viewInitialized = true; this._applyMinWidthPx(); this._applyMaxWidthPx(); }); } ngOnDestroy(): void { this._isDestroyed = true; this.destroyed.next(); this.destroyed.complete(); this.inlineHandle?.remove(); this.overlayRef?.dispose(); } protected abstract getInlineHandleCssClassName(): string; protected abstract getOverlayHandleComponentType(): Type<HandleComponent>; private _createOverlayForHandle(): OverlayRef { // Use of overlays allows us to properly capture click events spanning parts // of two table cells and is also useful for displaying a resize thumb // over both cells and extending it down the table as needed. const isRtl = this.directionality.value === 'rtl'; const positionStrategy = this.overlay .position() .flexibleConnectedTo(this.elementRef.nativeElement!) .withFlexibleDimensions(false) .withGrowAfterOpen(false) .withPush(false) .withDefaultOffsetX(isRtl ? 1 : 0) .withPositions([ { originX: isRtl ? 'start' : 'end', originY: 'top', overlayX: 'center', overlayY: 'top', }, ]); return this.overlay.create({ // Always position the overlay based on left-indexed coordinates. direction: 'ltr', disposeOnNavigation: true, positionStrategy, scrollStrategy: this.overlay.scrollStrategies.reposition(), width: '16px', }); } private _listenForRowHoverEvents(): void { const element = this.elementRef.nativeElement!; const takeUntilDestroyed = takeUntil<boolean>(this.destroyed); this.eventDispatcher .resizeOverlayVisibleForHeaderRow(_closest(element, HEADER_ROW_SELECTOR)!) .pipe(takeUntilDestroyed) .subscribe(hoveringRow => { if (hoveringRow) { if (!this.overlayRef) { this.overlayRef = this._createOverlayForHandle(); } this._showHandleOverlay(); } else if (this.overlayRef) { // todo - can't detach during an active resize - need to work that out this.overlayRef.detach(); } }); } private _listenForResizeEvents() { const takeUntilDestroyed = takeUntil<ColumnSizeAction>(this.destroyed); merge(this.resizeNotifier.resizeCanceled, this.resizeNotifier.triggerResize) .pipe( takeUntilDestroyed, filter(columnSize => columnSize.columnId === this.columnDef.name), ) .subscribe(({size, previousSize, completeImmediately}) => { this.elementRef.nativeElement!.classList.add(OVERLAY_ACTIVE_CLASS); this._applySize(size, previousSize); if (completeImmediately) { this._completeResizeOperation(); } }); merge(this.resizeNotifier.resizeCanceled, this.resizeNotifier.resizeCompleted) .pipe(takeUntilDestroyed) .subscribe(columnSize => { this._cleanUpAfterResize(columnSize); }); } private _completeResizeOperation(): void { this.ngZone.run(() => { this.resizeNotifier.resizeCompleted.next({ columnId: this.columnDef.name, size: this.elementRef.nativeElement!.offsetWidth, }); }); } private _cleanUpAfterResize(columnSize: ColumnSizeAction): void { this.elementRef.nativeElement!.classList.remove(OVERLAY_ACTIVE_CLASS); if (this.overlayRef && this.overlayRef.hasAttached()) { this._updateOverlayHandleHeight(); this.overlayRef.updatePosition(); if (columnSize.columnId === this.columnDef.name) { this.inlineHandle!.focus(); } } } private _createHandlePortal(): ComponentPortal<HandleComponent> { const injector = Injector.create({ parent: this.injector, providers: [ { provide: ResizeRef, useValue: new ResizeRef( this.elementRef, this.overlayRef!, this.minWidthPx, this.maxWidthPx, ), }, ], }); return new ComponentPortal( this.getOverlayHandleComponentType(), this.viewContainerRef, injector, ); } private _showHandleOverlay(): void { this._updateOverlayHandleHeight(); this.overlayRef!.attach(this._createHandlePortal()); // Needed to ensure that all of the lifecycle hooks inside the overlay run immediately. this.changeDetectorRef.markForCheck(); } private _updateOverlayHandleHeight() { this.overlayRef!.updateSize({height: this.elementRef.nativeElement!.offsetHeight}); } private _applySize(sizeInPixels: number, previousSize?: number): void { const sizeToApply = Math.min(Math.max(sizeInPixels, this.minWidthPx, 0), this.maxWidthPx); this.resizeStrategy.applyColumnSize( this.columnDef.cssClassFriendlyName, this.elementRef.nativeElement!, sizeToApply, previousSize, ); } private _applyMinWidthPx(): void { this.resizeStrategy.applyMinColumnSize( this.columnDef.cssClassFriendlyName, this.elementRef.nativeElement, this.minWidthPx, ); } private _applyMaxWidthPx(): void { this.resizeStrategy.applyMaxColumnSize( this.columnDef.cssClassFriendlyName, this.elementRef.nativeElement, this.maxWidthPx, ); } private _appendInlineHandle(): void { this.styleScheduler.schedule(() => { this.inlineHandle = this.document.createElement('div'); this.inlineHandle.tabIndex = 0; this.inlineHandle.className = this.getInlineHandleCssClassName(); // TODO: Apply correct aria role (probably slider) after a11y spec questions resolved. this.elementRef.nativeElement!.appendChild(this.inlineHandle); }); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 9238, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/resizable.ts" }
components/src/cdk-experimental/column-resize/column-resize-module.ts_0_1251
/** * @license * Copyright Google LLC 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.dev/license */ import {NgModule} from '@angular/core'; import {CdkColumnResize} from './column-resize-directives/column-resize'; import {CdkColumnResizeFlex} from './column-resize-directives/column-resize-flex'; import {CdkDefaultEnabledColumnResize} from './column-resize-directives/default-enabled-column-resize'; import {CdkDefaultEnabledColumnResizeFlex} from './column-resize-directives/default-enabled-column-resize-flex'; /** * One of two NgModules for use with CdkColumnResize. * When using this module, columns are resizable by default. */ @NgModule({ imports: [CdkDefaultEnabledColumnResize, CdkDefaultEnabledColumnResizeFlex], exports: [CdkDefaultEnabledColumnResize, CdkDefaultEnabledColumnResizeFlex], }) export class CdkColumnResizeDefaultEnabledModule {} /** * One of two NgModules for use with CdkColumnResize. * When using this module, columns are not resizable by default. */ @NgModule({ imports: [CdkColumnResize, CdkColumnResizeFlex], exports: [CdkColumnResize, CdkColumnResizeFlex], }) export class CdkColumnResizeModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 1251, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-resize-module.ts" }
components/src/cdk-experimental/column-resize/overlay-handle.ts_0_7220
/** * @license * Copyright Google LLC 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.dev/license */ import {AfterViewInit, Directive, ElementRef, OnDestroy, NgZone} from '@angular/core'; import {coerceCssPixelValue} from '@angular/cdk/coercion'; import {Directionality} from '@angular/cdk/bidi'; import {ESCAPE} from '@angular/cdk/keycodes'; import {CdkColumnDef, _CoalescedStyleScheduler} from '@angular/cdk/table'; import {fromEvent, Subject, merge} from 'rxjs'; import { distinctUntilChanged, filter, map, mapTo, pairwise, startWith, takeUntil, } from 'rxjs/operators'; import {_closest} from '@angular/cdk-experimental/popover-edit'; import {HEADER_CELL_SELECTOR} from './selectors'; import {ColumnResizeNotifierSource} from './column-resize-notifier'; import {HeaderRowEventDispatcher} from './event-dispatcher'; import {ResizeRef} from './resize-ref'; // TODO: Take another look at using cdk drag drop. IIRC I ran into a couple // good reasons for not using it but I don't remember what they were at this point. /** * Base class for a component shown over the edge of a resizable column that is responsible * for handling column resize mouse events and displaying any visible UI on the column edge. */ @Directive() export abstract class ResizeOverlayHandle implements AfterViewInit, OnDestroy { protected readonly destroyed = new Subject<void>(); protected abstract readonly columnDef: CdkColumnDef; protected abstract readonly document: Document; protected abstract readonly directionality: Directionality; protected abstract readonly elementRef: ElementRef; protected abstract readonly eventDispatcher: HeaderRowEventDispatcher; protected abstract readonly ngZone: NgZone; protected abstract readonly resizeNotifier: ColumnResizeNotifierSource; protected abstract readonly resizeRef: ResizeRef; protected abstract readonly styleScheduler: _CoalescedStyleScheduler; ngAfterViewInit() { this._listenForMouseEvents(); } ngOnDestroy() { this.destroyed.next(); this.destroyed.complete(); } private _listenForMouseEvents() { this.ngZone.runOutsideAngular(() => { fromEvent<MouseEvent>(this.elementRef.nativeElement!, 'mouseenter') .pipe(mapTo(this.resizeRef.origin.nativeElement!), takeUntil(this.destroyed)) .subscribe(cell => this.eventDispatcher.headerCellHovered.next(cell)); fromEvent<MouseEvent>(this.elementRef.nativeElement!, 'mouseleave') .pipe( map( event => event.relatedTarget && _closest(event.relatedTarget as Element, HEADER_CELL_SELECTOR), ), takeUntil(this.destroyed), ) .subscribe(cell => this.eventDispatcher.headerCellHovered.next(cell)); fromEvent<MouseEvent>(this.elementRef.nativeElement!, 'mousedown') .pipe(takeUntil(this.destroyed)) .subscribe(mousedownEvent => { this._dragStarted(mousedownEvent); }); }); } private _dragStarted(mousedownEvent: MouseEvent) { // Only allow dragging using the left mouse button. if (mousedownEvent.button !== 0) { return; } const mouseup = fromEvent<MouseEvent>(this.document, 'mouseup'); const mousemove = fromEvent<MouseEvent>(this.document, 'mousemove'); const escape = fromEvent<KeyboardEvent>(this.document, 'keyup').pipe( filter(event => event.keyCode === ESCAPE), ); const startX = mousedownEvent.screenX; const initialSize = this._getOriginWidth(); let overlayOffset = 0; let originOffset = this._getOriginOffset(); let size = initialSize; let overshot = 0; this.updateResizeActive(true); mouseup.pipe(takeUntil(merge(escape, this.destroyed))).subscribe(({screenX}) => { this.styleScheduler.scheduleEnd(() => { this._notifyResizeEnded(size, screenX !== startX); }); }); escape.pipe(takeUntil(merge(mouseup, this.destroyed))).subscribe(() => { this._notifyResizeEnded(initialSize); }); mousemove .pipe( map(({screenX}) => screenX), startWith(startX), distinctUntilChanged(), pairwise(), takeUntil(merge(mouseup, escape, this.destroyed)), ) .subscribe(([prevX, currX]) => { let deltaX = currX - prevX; // If the mouse moved further than the resize was able to match, limit the // movement of the overlay to match the actual size and position of the origin. if (overshot !== 0) { if ((overshot < 0 && deltaX < 0) || (overshot > 0 && deltaX > 0)) { overshot += deltaX; return; } else { const remainingOvershot = overshot + deltaX; overshot = overshot > 0 ? Math.max(remainingOvershot, 0) : Math.min(remainingOvershot, 0); deltaX = remainingOvershot - overshot; if (deltaX === 0) { return; } } } let computedNewSize: number = size + (this._isLtr() ? deltaX : -deltaX); computedNewSize = Math.min( Math.max(computedNewSize, this.resizeRef.minWidthPx, 0), this.resizeRef.maxWidthPx, ); this.resizeNotifier.triggerResize.next({ columnId: this.columnDef.name, size: computedNewSize, previousSize: size, isStickyColumn: this.columnDef.sticky || this.columnDef.stickyEnd, }); this.styleScheduler.scheduleEnd(() => { const originNewSize = this._getOriginWidth(); const originNewOffset = this._getOriginOffset(); const originOffsetDeltaX = originNewOffset - originOffset; const originSizeDeltaX = originNewSize - size; size = originNewSize; originOffset = originNewOffset; overshot += deltaX + (this._isLtr() ? -originSizeDeltaX : originSizeDeltaX); overlayOffset += originOffsetDeltaX + (this._isLtr() ? originSizeDeltaX : 0); this._updateOverlayOffset(overlayOffset); }); }); } protected updateResizeActive(active: boolean): void { this.eventDispatcher.overlayHandleActiveForCell.next( active ? this.resizeRef.origin.nativeElement! : null, ); } private _getOriginWidth(): number { return this.resizeRef.origin.nativeElement!.offsetWidth; } private _getOriginOffset(): number { return this.resizeRef.origin.nativeElement!.offsetLeft; } private _updateOverlayOffset(offset: number): void { this.resizeRef.overlayRef.overlayElement.style.transform = `translateX(${coerceCssPixelValue( offset, )})`; } private _isLtr(): boolean { return this.directionality.value === 'ltr'; } private _notifyResizeEnded(size: number, completedSuccessfully = false): void { this.updateResizeActive(false); this.ngZone.run(() => { const sizeMessage = {columnId: this.columnDef.name, size}; if (completedSuccessfully) { this.resizeNotifier.resizeCompleted.next(sizeMessage); } else { this.resizeNotifier.resizeCanceled.next(sizeMessage); } }); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 7220, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/overlay-handle.ts" }
components/src/cdk-experimental/column-resize/public-api.ts_0_794
/** * @license * Copyright Google LLC 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.dev/license */ export * from './column-resize'; export * from './column-resize-directives/column-resize'; export * from './column-resize-directives/column-resize-flex'; export * from './column-resize-directives/default-enabled-column-resize'; export * from './column-resize-directives/default-enabled-column-resize-flex'; export * from './column-resize-module'; export * from './column-resize-notifier'; export * from './column-size-store'; export * from './event-dispatcher'; export * from './resizable'; export * from './resize-ref'; export * from './resize-strategy'; export * from './overlay-handle';
{ "commit_id": "ea0d1ba7b", "end_byte": 794, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/public-api.ts" }
components/src/cdk-experimental/column-resize/selectors.ts_0_534
/** * @license * Copyright Google LLC 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.dev/license */ // TODO: Figure out how to remove `mat-` classes from the CDK part of the // column resize implementation. export const HEADER_CELL_SELECTOR = '.cdk-header-cell, .mat-header-cell'; export const HEADER_ROW_SELECTOR = '.cdk-header-row, .mat-header-row'; export const RESIZE_OVERLAY_SELECTOR = '.mat-column-resize-overlay-thumb';
{ "commit_id": "ea0d1ba7b", "end_byte": 534, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/selectors.ts" }
components/src/cdk-experimental/column-resize/event-dispatcher.ts_0_3282
/** * @license * Copyright Google LLC 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.dev/license */ import {Injectable, NgZone, inject} from '@angular/core'; import {combineLatest, MonoTypeOperatorFunction, Observable, Subject} from 'rxjs'; import {distinctUntilChanged, map, share, skip, startWith} from 'rxjs/operators'; import {_closest} from '@angular/cdk-experimental/popover-edit'; import {HEADER_ROW_SELECTOR} from './selectors'; /** Coordinates events between the column resize directives. */ @Injectable() export class HeaderRowEventDispatcher { private readonly _ngZone = inject(NgZone); /** * Emits the currently hovered header cell or null when no header cells are hovered. * Exposed publicly for events to feed in, but subscribers should use headerCellHoveredDistinct, * defined below. */ readonly headerCellHovered = new Subject<Element | null>(); /** * Emits the header cell for which a user-triggered resize is active or null * when no resize is in progress. */ readonly overlayHandleActiveForCell = new Subject<Element | null>(); /** Distinct and shared version of headerCellHovered. */ readonly headerCellHoveredDistinct = this.headerCellHovered.pipe(distinctUntilChanged(), share()); /** * Emits the header that is currently hovered or hosting an active resize event (with active * taking precedence). */ readonly headerRowHoveredOrActiveDistinct = combineLatest([ this.headerCellHoveredDistinct.pipe( map(cell => _closest(cell, HEADER_ROW_SELECTOR)), startWith(null), distinctUntilChanged(), ), this.overlayHandleActiveForCell.pipe( map(cell => _closest(cell, HEADER_ROW_SELECTOR)), startWith(null), distinctUntilChanged(), ), ]).pipe( skip(1), // Ignore initial [null, null] emission. map(([hovered, active]) => active || hovered), distinctUntilChanged(), share(), ); private readonly _headerRowHoveredOrActiveDistinctReenterZone = this.headerRowHoveredOrActiveDistinct.pipe(this._enterZone(), share()); // Optimization: Share row events observable with subsequent callers. // At startup, calls will be sequential by row (and typically there's only one). private _lastSeenRow: Element | null = null; private _lastSeenRowHover: Observable<boolean> | null = null; /** * Emits whether the specified row should show its overlay controls. * Emission occurs within the NgZone. */ resizeOverlayVisibleForHeaderRow(row: Element): Observable<boolean> { if (row !== this._lastSeenRow) { this._lastSeenRow = row; this._lastSeenRowHover = this._headerRowHoveredOrActiveDistinctReenterZone.pipe( map(hoveredRow => hoveredRow === row), distinctUntilChanged(), share(), ); } return this._lastSeenRowHover!; } private _enterZone<T>(): MonoTypeOperatorFunction<T> { return (source: Observable<T>) => new Observable<T>(observer => source.subscribe({ next: value => this._ngZone.run(() => observer.next(value)), error: err => observer.error(err), complete: () => observer.complete(), }), ); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3282, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/event-dispatcher.ts" }
components/src/cdk-experimental/column-resize/BUILD.bazel_0_543
load("//tools:defaults.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) ng_module( name = "column-resize", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk-experimental/popover-edit", "//src/cdk/bidi", "//src/cdk/coercion", "//src/cdk/keycodes", "//src/cdk/overlay", "//src/cdk/portal", "//src/cdk/table", "@npm//@angular/common", "@npm//@angular/core", "@npm//rxjs", ], )
{ "commit_id": "ea0d1ba7b", "end_byte": 543, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/BUILD.bazel" }
components/src/cdk-experimental/column-resize/resize-ref.ts_0_531
/** * @license * Copyright Google LLC 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.dev/license */ import {ElementRef} from '@angular/core'; import {OverlayRef} from '@angular/cdk/overlay'; /** Tracks state of resize events in progress. */ export class ResizeRef { constructor( readonly origin: ElementRef, readonly overlayRef: OverlayRef, readonly minWidthPx: number, readonly maxWidthPx: number, ) {} }
{ "commit_id": "ea0d1ba7b", "end_byte": 531, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/resize-ref.ts" }
components/src/cdk-experimental/column-resize/index.ts_0_234
/** * @license * Copyright Google LLC 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.dev/license */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/index.ts" }
components/src/cdk-experimental/column-resize/column-size-store.ts_0_684
/** * @license * Copyright Google LLC 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.dev/license */ import {Injectable} from '@angular/core'; /** * Can be provided by the host application to enable persistence of column resize state. */ @Injectable() export abstract class ColumnSizeStore { /** Returns the persisted size of the specified column in the specified table. */ abstract getSize(tableId: string, columnId: string): number; /** Persists the size of the specified column in the specified table. */ abstract setSize(tableId: string, columnId: string): void; }
{ "commit_id": "ea0d1ba7b", "end_byte": 684, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-size-store.ts" }
components/src/cdk-experimental/column-resize/column-resize-directives/column-resize.ts_0_1287
/** * @license * Copyright Google LLC 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.dev/license */ import {Directive, ElementRef, NgZone, inject} from '@angular/core'; import {CdkTable} from '@angular/cdk/table'; import {ColumnResize} from '../column-resize'; import {ColumnResizeNotifier, ColumnResizeNotifierSource} from '../column-resize-notifier'; import {HeaderRowEventDispatcher} from '../event-dispatcher'; import {TABLE_PROVIDERS} from './constants'; /** * Explicitly enables column resizing for a table-based cdk-table. * Individual columns must be annotated specifically. */ @Directive({ selector: 'table[cdk-table][columnResize]', providers: [...TABLE_PROVIDERS, {provide: ColumnResize, useExisting: CdkColumnResize}], }) export class CdkColumnResize extends ColumnResize { readonly columnResizeNotifier = inject(ColumnResizeNotifier); readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected readonly eventDispatcher = inject(HeaderRowEventDispatcher); protected readonly ngZone = inject(NgZone); protected readonly notifier = inject(ColumnResizeNotifierSource); protected readonly table = inject<CdkTable<unknown>>(CdkTable); }
{ "commit_id": "ea0d1ba7b", "end_byte": 1287, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-resize-directives/column-resize.ts" }
components/src/cdk-experimental/column-resize/column-resize-directives/column-resize-flex.ts_0_1288
/** * @license * Copyright Google LLC 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.dev/license */ import {Directive, ElementRef, NgZone, inject} from '@angular/core'; import {CdkTable} from '@angular/cdk/table'; import {ColumnResize} from '../column-resize'; import {ColumnResizeNotifier, ColumnResizeNotifierSource} from '../column-resize-notifier'; import {HeaderRowEventDispatcher} from '../event-dispatcher'; import {FLEX_PROVIDERS} from './constants'; /** * Explicitly enables column resizing for a flexbox-based cdk-table. * Individual columns must be annotated specifically. */ @Directive({ selector: 'cdk-table[columnResize]', providers: [...FLEX_PROVIDERS, {provide: ColumnResize, useExisting: CdkColumnResizeFlex}], }) export class CdkColumnResizeFlex extends ColumnResize { readonly columnResizeNotifier = inject(ColumnResizeNotifier); readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected readonly eventDispatcher = inject(HeaderRowEventDispatcher); protected readonly ngZone = inject(NgZone); protected readonly notifier = inject(ColumnResizeNotifierSource); protected readonly table = inject<CdkTable<unknown>>(CdkTable); }
{ "commit_id": "ea0d1ba7b", "end_byte": 1288, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-resize-directives/column-resize-flex.ts" }
components/src/cdk-experimental/column-resize/column-resize-directives/default-enabled-column-resize-flex.ts_0_1310
/** * @license * Copyright Google LLC 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.dev/license */ import {Directive, ElementRef, NgZone, inject} from '@angular/core'; import {CdkTable} from '@angular/cdk/table'; import {ColumnResize} from '../column-resize'; import {ColumnResizeNotifier, ColumnResizeNotifierSource} from '../column-resize-notifier'; import {HeaderRowEventDispatcher} from '../event-dispatcher'; import {FLEX_PROVIDERS} from './constants'; /** * Implicitly enables column resizing for a flex cdk-table. * Individual columns will be resizable unless opted out. */ @Directive({ selector: 'cdk-table', providers: [ ...FLEX_PROVIDERS, {provide: ColumnResize, useExisting: CdkDefaultEnabledColumnResizeFlex}, ], }) export class CdkDefaultEnabledColumnResizeFlex extends ColumnResize { readonly columnResizeNotifier = inject(ColumnResizeNotifier); readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected readonly eventDispatcher = inject(HeaderRowEventDispatcher); protected readonly ngZone = inject(NgZone); protected readonly notifier = inject(ColumnResizeNotifierSource); protected readonly table = inject<CdkTable<unknown>>(CdkTable); }
{ "commit_id": "ea0d1ba7b", "end_byte": 1310, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-resize-directives/default-enabled-column-resize-flex.ts" }
components/src/cdk-experimental/column-resize/column-resize-directives/constants.ts_0_835
/** * @license * Copyright Google LLC 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.dev/license */ import {Provider} from '@angular/core'; import {ColumnResizeNotifier, ColumnResizeNotifierSource} from '../column-resize-notifier'; import {HeaderRowEventDispatcher} from '../event-dispatcher'; import { TABLE_LAYOUT_FIXED_RESIZE_STRATEGY_PROVIDER, FLEX_RESIZE_STRATEGY_PROVIDER, } from '../resize-strategy'; const PROVIDERS: Provider[] = [ ColumnResizeNotifier, HeaderRowEventDispatcher, ColumnResizeNotifierSource, ]; export const TABLE_PROVIDERS: Provider[] = [ ...PROVIDERS, TABLE_LAYOUT_FIXED_RESIZE_STRATEGY_PROVIDER, ]; export const FLEX_PROVIDERS: Provider[] = [...PROVIDERS, FLEX_RESIZE_STRATEGY_PROVIDER];
{ "commit_id": "ea0d1ba7b", "end_byte": 835, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-resize-directives/constants.ts" }
components/src/cdk-experimental/column-resize/column-resize-directives/default-enabled-column-resize.ts_0_1318
/** * @license * Copyright Google LLC 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.dev/license */ import {Directive, ElementRef, NgZone, inject} from '@angular/core'; import {CdkTable} from '@angular/cdk/table'; import {ColumnResize} from '../column-resize'; import {ColumnResizeNotifier, ColumnResizeNotifierSource} from '../column-resize-notifier'; import {HeaderRowEventDispatcher} from '../event-dispatcher'; import {TABLE_PROVIDERS} from './constants'; /** * Implicitly enables column resizing for a table-based cdk-table. * Individual columns will be resizable unless opted out. */ @Directive({ selector: 'table[cdk-table]', providers: [ ...TABLE_PROVIDERS, {provide: ColumnResize, useExisting: CdkDefaultEnabledColumnResize}, ], }) export class CdkDefaultEnabledColumnResize extends ColumnResize { readonly columnResizeNotifier = inject(ColumnResizeNotifier); readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected readonly eventDispatcher = inject(HeaderRowEventDispatcher); protected readonly ngZone = inject(NgZone); protected readonly notifier = inject(ColumnResizeNotifierSource); protected readonly table = inject<CdkTable<unknown>>(CdkTable); }
{ "commit_id": "ea0d1ba7b", "end_byte": 1318, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-resize-directives/default-enabled-column-resize.ts" }
components/src/cdk-experimental/scrolling/virtual-scroll.e2e.spec.ts_0_5509
import {browser, by, element, ElementFinder} from 'protractor'; import {ILocation, ISize} from 'selenium-webdriver'; declare var window: any; describe('autosize cdk-virtual-scroll', () => { let viewport: ElementFinder; describe('with uniform items', () => { beforeEach(async () => { await browser.get('/virtual-scroll'); viewport = element(by.css('.demo-virtual-scroll-uniform-size cdk-virtual-scroll-viewport')); }); it('should scroll down slowly', async () => { await browser.executeAsyncScript(smoothScrollViewportTo, viewport, 2000); const offScreen = element(by.css('.demo-virtual-scroll-uniform-size [data-index="39"]')); const onScreen = element(by.css('.demo-virtual-scroll-uniform-size [data-index="40"]')); expect(await isVisibleInViewport(offScreen, viewport)).toBe(false); expect(await isVisibleInViewport(onScreen, viewport)).toBe(true); }); it('should jump scroll position down and slowly scroll back up', async () => { // The estimate of the total content size is exactly correct, so we wind up scrolled to the // same place as if we slowly scrolled down. await browser.executeAsyncScript(scrollViewportTo, viewport, 2000); const offScreen = element(by.css('.demo-virtual-scroll-uniform-size [data-index="39"]')); const onScreen = element(by.css('.demo-virtual-scroll-uniform-size [data-index="40"]')); expect(await isVisibleInViewport(offScreen, viewport)).toBe(false); expect(await isVisibleInViewport(onScreen, viewport)).toBe(true); // As we slowly scroll back up we should wind up back at the start of the content. await browser.executeAsyncScript(smoothScrollViewportTo, viewport, 0); const first = element(by.css('.demo-virtual-scroll-uniform-size [data-index="0"]')); expect(await isVisibleInViewport(first, viewport)).toBe(true); }); }); describe('with variable size', () => { beforeEach(async () => { await browser.get('/virtual-scroll'); viewport = element(by.css('.demo-virtual-scroll-variable-size cdk-virtual-scroll-viewport')); }); it('should scroll down slowly', async () => { await browser.executeAsyncScript(smoothScrollViewportTo, viewport, 2000); const offScreen = element(by.css('.demo-virtual-scroll-variable-size [data-index="19"]')); const onScreen = element(by.css('.demo-virtual-scroll-variable-size [data-index="20"]')); expect(await isVisibleInViewport(offScreen, viewport)).toBe(false); expect(await isVisibleInViewport(onScreen, viewport)).toBe(true); }); it('should jump scroll position down and slowly scroll back up', async () => { // The estimate of the total content size is slightly different than the actual, so we don't // wind up in the same spot as if we scrolled slowly down. await browser.executeAsyncScript(scrollViewportTo, viewport, 2000); const offScreen = element(by.css('.demo-virtual-scroll-variable-size [data-index="18"]')); const onScreen = element(by.css('.demo-virtual-scroll-variable-size [data-index="19"]')); expect(await isVisibleInViewport(offScreen, viewport)).toBe(false); expect(await isVisibleInViewport(onScreen, viewport)).toBe(true); // As we slowly scroll back up we should wind up back at the start of the content. As we // scroll the error from when we jumped the scroll position should be slowly corrected. await browser.executeAsyncScript(smoothScrollViewportTo, viewport, 0); const first = element(by.css('.demo-virtual-scroll-variable-size [data-index="0"]')); expect(await isVisibleInViewport(first, viewport)).toBe(true); }); }); }); /** Checks if the given element is visible in the given viewport. */ async function isVisibleInViewport(el: ElementFinder, viewport: ElementFinder): Promise<boolean> { if ( !(await el.isPresent()) || !(await el.isDisplayed()) || !(await viewport.isPresent()) || !(await viewport.isDisplayed()) ) { return false; } const viewportRect = getRect(await viewport.getLocation(), await viewport.getSize()); const elRect = getRect(await el.getLocation(), await el.getSize()); return ( elRect.left < viewportRect.right && elRect.right > viewportRect.left && elRect.top < viewportRect.bottom && elRect.bottom > viewportRect.top ); } /** Gets the rect for an element given its location ans size. */ function getRect( location: ILocation, size: ISize, ): {top: number; left: number; bottom: number; right: number} { return { top: location.y, left: location.x, bottom: location.y + size.height, right: location.x + size.width, }; } /** Immediately scrolls the viewport to the given offset. */ function scrollViewportTo(viewportEl: any, offset: number, done: () => void) { viewportEl.scrollTop = offset; window.requestAnimationFrame(() => done()); } /** Smoothly scrolls the viewport to the given offset, 25px at a time. */ function smoothScrollViewportTo(viewportEl: any, offset: number, done: () => void) { let promise = Promise.resolve(); let curOffset = viewportEl.scrollTop; do { const co = (curOffset += Math.min(25, Math.max(-25, offset - curOffset))); promise = promise.then( () => new Promise<void>(resolve => { viewportEl.scrollTop = co; window.requestAnimationFrame(() => resolve()); }), ); } while (curOffset != offset); promise.then(() => done()); }
{ "commit_id": "ea0d1ba7b", "end_byte": 5509, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/virtual-scroll.e2e.spec.ts" }
components/src/cdk-experimental/scrolling/virtual-scroll-viewport.spec.ts_0_4049
import {CdkVirtualScrollViewport, ScrollingModule} from '@angular/cdk/scrolling'; import {Component, Input, ViewChild, ViewEncapsulation} from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, flush, waitForAsync} from '@angular/core/testing'; import {ScrollingModule as ExperimentalScrollingModule} from './scrolling-module'; describe('CdkVirtualScrollViewport', () => { describe('with AutoSizeVirtualScrollStrategy', () => { let fixture: ComponentFixture<AutoSizeVirtualScroll>; let testComponent: AutoSizeVirtualScroll; let viewport: CdkVirtualScrollViewport; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ScrollingModule, ExperimentalScrollingModule, AutoSizeVirtualScroll], }); })); beforeEach(() => { fixture = TestBed.createComponent(AutoSizeVirtualScroll); testComponent = fixture.componentInstance; viewport = testComponent.viewport; }); it('should render initial state for uniform items', fakeAsync(() => { finishInit(fixture); const contentWrapper = viewport.elementRef.nativeElement.querySelector( '.cdk-virtual-scroll-content-wrapper', )!; expect(contentWrapper.children.length) .withContext('should render 4 50px items to fill 200px space') .toBe(4); })); it('should render extra content if first item is smaller than average', fakeAsync(() => { testComponent.items = [50, 200, 200, 200, 200, 200]; finishInit(fixture); const contentWrapper = viewport.elementRef.nativeElement.querySelector( '.cdk-virtual-scroll-content-wrapper', )!; expect(contentWrapper.children.length) .withContext( 'should render 4 items to fill 200px space based on 50px ' + 'estimate from first item', ) .toBe(4); })); it('should throw if maxBufferPx is less than minBufferPx', fakeAsync(() => { expect(() => { testComponent.minBufferPx = 100; testComponent.maxBufferPx = 99; finishInit(fixture); }).toThrowError( 'CDK virtual scroll: maxBufferPx must be greater than or equal to minBufferPx', ); })); // TODO(mmalerba): Add test that it corrects the initial render if it didn't render enough, // once it actually does that. }); }); /** Finish initializing the virtual scroll component at the beginning of a test. */ function finishInit(fixture: ComponentFixture<any>) { // On the first cycle we render and measure the viewport. fixture.detectChanges(); flush(); // On the second cycle we render the items. fixture.detectChanges(); flush(); } @Component({ template: ` <cdk-virtual-scroll-viewport autosize [minBufferPx]="minBufferPx" [maxBufferPx]="maxBufferPx" [orientation]="orientation" [style.height.px]="viewportHeight" [style.width.px]="viewportWidth"> <div class="item" *cdkVirtualFor="let size of items; let i = index" [style.height.px]="size" [style.width.px]="size"> {{i}} - {{size}} </div> </cdk-virtual-scroll-viewport> `, styles: ` .cdk-virtual-scroll-content-wrapper { display: flex; flex-direction: column; } .cdk-virtual-scroll-orientation-horizontal .cdk-virtual-scroll-content-wrapper { flex-direction: row; } `, encapsulation: ViewEncapsulation.None, standalone: true, imports: [ScrollingModule, ExperimentalScrollingModule], }) class AutoSizeVirtualScroll { @ViewChild(CdkVirtualScrollViewport, {static: true}) viewport: CdkVirtualScrollViewport; @Input() orientation = 'vertical'; @Input() viewportSize = 200; @Input() viewportCrossSize = 100; @Input() minBufferPx = 0; @Input() maxBufferPx = 0; @Input() items = Array(10).fill(50); get viewportWidth() { return this.orientation == 'horizontal' ? this.viewportSize : this.viewportCrossSize; } get viewportHeight() { return this.orientation == 'horizontal' ? this.viewportCrossSize : this.viewportSize; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 4049, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/virtual-scroll-viewport.spec.ts" }
components/src/cdk-experimental/scrolling/public-api.ts_0_284
/** * @license * Copyright Google LLC 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.dev/license */ export * from './auto-size-virtual-scroll'; export * from './scrolling-module';
{ "commit_id": "ea0d1ba7b", "end_byte": 284, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/public-api.ts" }
components/src/cdk-experimental/scrolling/scrolling-module.ts_0_439
/** * @license * Copyright Google LLC 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.dev/license */ import {NgModule} from '@angular/core'; import {CdkAutoSizeVirtualScroll} from './auto-size-virtual-scroll'; @NgModule({ imports: [CdkAutoSizeVirtualScroll], exports: [CdkAutoSizeVirtualScroll], }) export class ScrollingModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 439, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/scrolling-module.ts" }
components/src/cdk-experimental/scrolling/scrolling.md_0_1279
**Warning: this component is still experimental. It may have bugs and the API may change at any time** ### Scrolling over items with different sizes When the items have different or unknown sizes, you can use the `AutoSizeVirtualScrollStrategy`. This can be added to your viewport by using the `autosize` directive. ```html <cdk-virtual-scroll-viewport autosize> ... </cdk-virtual-scroll-viewport> ``` The `autosize` strategy is configured through two inputs: `minBufferPx` and `maxBufferPx`. **`minBufferPx`** determines the minimum space outside virtual scrolling viewport that will be filled with content. Increasing this will increase the amount of content a user will see before more content must be rendered. However, too large a value will cause more content to be rendered than is necessary. **`maxBufferPx`** determines the amount of content that will be added incrementally as the viewport is scrolled. This should be greater than the size of `minBufferPx` so that one "render" is needed at a time. ```html <cdk-virtual-scroll-viewport autosize minBufferPx="50" maxBufferPx="100"> ... </cdk-virtual-scroll-viewport> ``` Because the auto size strategy needs to measure the size of the elements, its performance may not be as good as the fixed size strategy.
{ "commit_id": "ea0d1ba7b", "end_byte": 1279, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/scrolling.md" }
components/src/cdk-experimental/scrolling/BUILD.bazel_0_1016
load("//src/e2e-app:test_suite.bzl", "e2e_test_suite") load("//tools:defaults.bzl", "ng_e2e_test_library", "ng_module", "ng_test_library", "ng_web_test_suite") package(default_visibility = ["//visibility:public"]) ng_module( name = "scrolling", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src:dev_mode_types", "//src/cdk/coercion", "//src/cdk/collections", "//src/cdk/scrolling", "@npm//@angular/core", "@npm//rxjs", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":scrolling", "//src/cdk/scrolling", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], ) ng_e2e_test_library( name = "e2e_test_sources", srcs = glob(["**/*.e2e.spec.ts"]), ) e2e_test_suite( name = "e2e_tests", deps = [ ":e2e_test_sources", ], )
{ "commit_id": "ea0d1ba7b", "end_byte": 1016, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/BUILD.bazel" }
components/src/cdk-experimental/scrolling/index.ts_0_234
/** * @license * Copyright Google LLC 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.dev/license */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/index.ts" }
components/src/cdk-experimental/scrolling/auto-size-virtual-scroll.ts_0_6480
/** * @license * Copyright Google LLC 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.dev/license */ import {coerceNumberProperty, NumberInput} from '@angular/cdk/coercion'; import {ListRange} from '@angular/cdk/collections'; import { CdkVirtualScrollViewport, VIRTUAL_SCROLL_STRATEGY, VirtualScrollStrategy, } from '@angular/cdk/scrolling'; import {Directive, forwardRef, Input, OnChanges} from '@angular/core'; import {Observable} from 'rxjs'; /** * A class that tracks the size of items that have been seen and uses it to estimate the average * item size. */ export class ItemSizeAverager { /** The total amount of weight behind the current average. */ private _totalWeight = 0; /** The current average item size. */ private _averageItemSize: number; /** The default size to use for items when no data is available. */ private _defaultItemSize: number; /** @param defaultItemSize The default size to use for items when no data is available. */ constructor(defaultItemSize = 50) { this._defaultItemSize = defaultItemSize; this._averageItemSize = defaultItemSize; } /** Returns the average item size. */ getAverageItemSize(): number { return this._averageItemSize; } /** * Adds a measurement sample for the estimator to consider. * @param range The measured range. * @param size The measured size of the given range in pixels. */ addSample(range: ListRange, size: number) { const newTotalWeight = this._totalWeight + range.end - range.start; if (newTotalWeight) { const newAverageItemSize = (size + this._averageItemSize * this._totalWeight) / newTotalWeight; if (newAverageItemSize) { this._averageItemSize = newAverageItemSize; this._totalWeight = newTotalWeight; } } } /** Resets the averager. */ reset() { this._averageItemSize = this._defaultItemSize; this._totalWeight = 0; } } /** Virtual scrolling strategy for lists with items of unknown or dynamic size. */ export class AutoSizeVirtualScrollStrategy implements VirtualScrollStrategy { /** @docs-private Implemented as part of VirtualScrollStrategy. */ scrolledIndexChange = new Observable<number>(() => { // TODO(mmalerba): Implement. if (typeof ngDevMode === 'undefined' || ngDevMode) { throw Error( 'cdk-virtual-scroll: scrolledIndexChange is currently not supported for the' + ' autosize scroll strategy', ); } }); /** The attached viewport. */ private _viewport: CdkVirtualScrollViewport | null = null; /** The minimum amount of buffer rendered beyond the viewport (in pixels). */ private _minBufferPx: number; /** The number of buffer items to render beyond the edge of the viewport (in pixels). */ private _maxBufferPx: number; /** The estimator used to estimate the size of unseen items. */ private _averager: ItemSizeAverager; /** The last measured scroll offset of the viewport. */ private _lastScrollOffset: number; /** The last measured size of the rendered content in the viewport. */ private _lastRenderedContentSize: number; /** The last measured size of the rendered content in the viewport. */ private _lastRenderedContentOffset: number; /** * The number of consecutive cycles where removing extra items has failed. Failure here means that * we estimated how many items we could safely remove, but our estimate turned out to be too much * and it wasn't safe to remove that many elements. */ private _removalFailures = 0; /** * @param minBufferPx The minimum amount of buffer rendered beyond the viewport (in pixels). * If the amount of buffer dips below this number, more items will be rendered. * @param maxBufferPx The number of pixels worth of buffer to shoot for when rendering new items. * If the actual amount turns out to be less it will not necessarily trigger an additional * rendering cycle (as long as the amount of buffer is still greater than `minBufferPx`). * @param averager The averager used to estimate the size of unseen items. */ constructor(minBufferPx: number, maxBufferPx: number, averager = new ItemSizeAverager()) { this._minBufferPx = minBufferPx; this._maxBufferPx = maxBufferPx; this._averager = averager; } /** * Attaches this scroll strategy to a viewport. * @param viewport The viewport to attach this strategy to. */ attach(viewport: CdkVirtualScrollViewport) { this._averager.reset(); this._viewport = viewport; this._renderContentForCurrentOffset(); } /** Detaches this scroll strategy from the currently attached viewport. */ detach() { this._viewport = null; } /** @docs-private Implemented as part of VirtualScrollStrategy. */ onContentScrolled() { if (this._viewport) { this._updateRenderedContentAfterScroll(); } } /** @docs-private Implemented as part of VirtualScrollStrategy. */ onDataLengthChanged() { if (this._viewport) { this._renderContentForCurrentOffset(); this._checkRenderedContentSize(); } } /** @docs-private Implemented as part of VirtualScrollStrategy. */ onContentRendered() { if (this._viewport) { this._checkRenderedContentSize(); } } /** @docs-private Implemented as part of VirtualScrollStrategy. */ onRenderedOffsetChanged() { if (this._viewport) { this._checkRenderedContentOffset(); } } /** Scroll to the offset for the given index. */ scrollToIndex(): void { if (typeof ngDevMode === 'undefined' || ngDevMode) { // TODO(mmalerba): Implement. throw Error( 'cdk-virtual-scroll: scrollToIndex is currently not supported for the autosize' + ' scroll strategy', ); } } /** * Update the buffer parameters. * @param minBufferPx The minimum amount of buffer rendered beyond the viewport (in pixels). * @param maxBufferPx The number of buffer items to render beyond the edge of the viewport (in * pixels). */ updateBufferSize(minBufferPx: number, maxBufferPx: number) { if (maxBufferPx < minBufferPx) { throw Error('CDK virtual scroll: maxBufferPx must be greater than or equal to minBufferPx'); } this._minBufferPx = minBufferPx; this._maxBufferPx = maxBufferPx; } /** Update the rendered content after the user scrolls. */
{ "commit_id": "ea0d1ba7b", "end_byte": 6480, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/auto-size-virtual-scroll.ts" }
components/src/cdk-experimental/scrolling/auto-size-virtual-scroll.ts_6483_15474
private _updateRenderedContentAfterScroll() { const viewport = this._viewport!; // The current scroll offset. const scrollOffset = viewport.measureScrollOffset(); // The delta between the current scroll offset and the previously recorded scroll offset. let scrollDelta = scrollOffset - this._lastScrollOffset; // The magnitude of the scroll delta. let scrollMagnitude = Math.abs(scrollDelta); // The currently rendered range. const renderedRange = viewport.getRenderedRange(); // If we're scrolling toward the top, we need to account for the fact that the predicted amount // of content and the actual amount of scrollable space may differ. We address this by slowly // correcting the difference on each scroll event. let offsetCorrection = 0; if (scrollDelta < 0) { // The content offset we would expect based on the average item size. const predictedOffset = renderedRange.start * this._averager.getAverageItemSize(); // The difference between the predicted size of the un-rendered content at the beginning and // the actual available space to scroll over. We need to reduce this to zero by the time the // user scrolls to the top. // - 0 indicates that the predicted size and available space are the same. // - A negative number that the predicted size is smaller than the available space. // - A positive number indicates the predicted size is larger than the available space const offsetDifference = predictedOffset - this._lastRenderedContentOffset; // The amount of difference to correct during this scroll event. We calculate this as a // percentage of the total difference based on the percentage of the distance toward the top // that the user scrolled. offsetCorrection = Math.round( offsetDifference * Math.max(0, Math.min(1, scrollMagnitude / (scrollOffset + scrollMagnitude))), ); // Based on the offset correction above, we pretend that the scroll delta was bigger or // smaller than it actually was, this way we can start to eliminate the difference. scrollDelta = scrollDelta - offsetCorrection; scrollMagnitude = Math.abs(scrollDelta); } // The current amount of buffer past the start of the viewport. const startBuffer = this._lastScrollOffset - this._lastRenderedContentOffset; // The current amount of buffer past the end of the viewport. const endBuffer = this._lastRenderedContentOffset + this._lastRenderedContentSize - (this._lastScrollOffset + viewport.getViewportSize()); // The amount of unfilled space that should be filled on the side the user is scrolling toward // in order to safely absorb the scroll delta. const underscan = scrollMagnitude + this._minBufferPx - (scrollDelta < 0 ? startBuffer : endBuffer); // Check if there's unfilled space that we need to render new elements to fill. if (underscan > 0) { // Check if the scroll magnitude was larger than the viewport size. In this case the user // won't notice a discontinuity if we just jump to the new estimated position in the list. // However, if the scroll magnitude is smaller than the viewport the user might notice some // jitteriness if we just jump to the estimated position. Instead we make sure to scroll by // the same number of pixels as the scroll magnitude. if (scrollMagnitude >= viewport.getViewportSize()) { this._renderContentForCurrentOffset(); } else { // The number of new items to render on the side the user is scrolling towards. Rather than // just filling the underscan space, we actually fill enough to have a buffer size of // `maxBufferPx`. This gives us a little wiggle room in case our item size estimate is off. const addItems = Math.max( 0, Math.ceil( (underscan - this._minBufferPx + this._maxBufferPx) / this._averager.getAverageItemSize(), ), ); // The amount of filled space beyond what is necessary on the side the user is scrolling // away from. const overscan = (scrollDelta < 0 ? endBuffer : startBuffer) - this._minBufferPx + scrollMagnitude; // The number of currently rendered items to remove on the side the user is scrolling away // from. If removal has failed in recent cycles we are less aggressive in how much we try to // remove. const unboundedRemoveItems = Math.floor( overscan / this._averager.getAverageItemSize() / (this._removalFailures + 1), ); const removeItems = Math.min( renderedRange.end - renderedRange.start, Math.max(0, unboundedRemoveItems), ); // The new range we will tell the viewport to render. We first expand it to include the new // items we want rendered, we then contract the opposite side to remove items we no longer // want rendered. const range = this._expandRange( renderedRange, scrollDelta < 0 ? addItems : 0, scrollDelta > 0 ? addItems : 0, ); if (scrollDelta < 0) { range.end = Math.max(range.start + 1, range.end - removeItems); } else { range.start = Math.min(range.end - 1, range.start + removeItems); } // The new offset we want to set on the rendered content. To determine this we measure the // number of pixels we removed and then adjust the offset to the start of the rendered // content or to the end of the rendered content accordingly (whichever one doesn't require // that the newly added items to be rendered to calculate.) let contentOffset: number; let contentOffsetTo: 'to-start' | 'to-end'; if (scrollDelta < 0) { let removedSize = viewport.measureRangeSize({ start: range.end, end: renderedRange.end, }); // Check that we're not removing too much. if (removedSize <= overscan) { contentOffset = this._lastRenderedContentOffset + this._lastRenderedContentSize - removedSize; this._removalFailures = 0; } else { // If the removal is more than the overscan can absorb just undo it and record the fact // that the removal failed so we can be less aggressive next time. range.end = renderedRange.end; contentOffset = this._lastRenderedContentOffset + this._lastRenderedContentSize; this._removalFailures++; } contentOffsetTo = 'to-end'; } else { const removedSize = viewport.measureRangeSize({ start: renderedRange.start, end: range.start, }); // Check that we're not removing too much. if (removedSize <= overscan) { contentOffset = this._lastRenderedContentOffset + removedSize; this._removalFailures = 0; } else { // If the removal is more than the overscan can absorb just undo it and record the fact // that the removal failed so we can be less aggressive next time. range.start = renderedRange.start; contentOffset = this._lastRenderedContentOffset; this._removalFailures++; } contentOffsetTo = 'to-start'; } // Set the range and offset we calculated above. viewport.setRenderedRange(range); viewport.setRenderedContentOffset(contentOffset + offsetCorrection, contentOffsetTo); } } else if (offsetCorrection) { // Even if the rendered range didn't change, we may still need to adjust the content offset to // simulate scrolling slightly slower or faster than the user actually scrolled. viewport.setRenderedContentOffset(this._lastRenderedContentOffset + offsetCorrection); } // Save the scroll offset to be compared to the new value on the next scroll event. this._lastScrollOffset = scrollOffset; } /** * Checks the size of the currently rendered content and uses it to update the estimated item size * and estimated total content size. */ private _checkRenderedContentSize() { const viewport = this._viewport!; this._lastRenderedContentSize = viewport.measureRenderedContentSize(); this._averager.addSample(viewport.getRenderedRange(), this._lastRenderedContentSize); this._updateTotalContentSize(this._lastRenderedContentSize); } /** Checks the currently rendered content offset and saves the value for later use. */ private _checkRenderedContentOffset() { const viewport = this._viewport!; this._lastRenderedContentOffset = viewport.getOffsetToRenderedContentStart()!; } /** * Recalculates the rendered content based on our estimate of what should be shown at the current * scroll offset. */
{ "commit_id": "ea0d1ba7b", "end_byte": 15474, "start_byte": 6483, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/auto-size-virtual-scroll.ts" }
components/src/cdk-experimental/scrolling/auto-size-virtual-scroll.ts_15477_20257
private _renderContentForCurrentOffset() { const viewport = this._viewport!; const scrollOffset = viewport.measureScrollOffset(); this._lastScrollOffset = scrollOffset; this._removalFailures = 0; const itemSize = this._averager.getAverageItemSize(); const firstVisibleIndex = Math.min( viewport.getDataLength() - 1, Math.floor(scrollOffset / itemSize), ); const bufferSize = Math.ceil(this._maxBufferPx / itemSize); const range = this._expandRange( this._getVisibleRangeForIndex(firstVisibleIndex), bufferSize, bufferSize, ); viewport.setRenderedRange(range); viewport.setRenderedContentOffset(itemSize * range.start); } // TODO: maybe move to base class, can probably share with fixed size strategy. /** * Gets the visible range of data for the given start index. If the start index is too close to * the end of the list it may be backed up to ensure the estimated size of the range is enough to * fill the viewport. * Note: must not be called if `this._viewport` is null * @param startIndex The index to start the range at * @return a range estimated to be large enough to fill the viewport when rendered. */ private _getVisibleRangeForIndex(startIndex: number): ListRange { const viewport = this._viewport!; const range: ListRange = { start: startIndex, end: startIndex + Math.ceil(viewport.getViewportSize() / this._averager.getAverageItemSize()), }; const extra = range.end - viewport.getDataLength(); if (extra > 0) { range.start = Math.max(0, range.start - extra); } return range; } // TODO: maybe move to base class, can probably share with fixed size strategy. /** * Expand the given range by the given amount in either direction. * Note: must not be called if `this._viewport` is null * @param range The range to expand * @param expandStart The number of items to expand the start of the range by. * @param expandEnd The number of items to expand the end of the range by. * @return The expanded range. */ private _expandRange(range: ListRange, expandStart: number, expandEnd: number): ListRange { const viewport = this._viewport!; const start = Math.max(0, range.start - expandStart); const end = Math.min(viewport.getDataLength(), range.end + expandEnd); return {start, end}; } /** Update the viewport's total content size. */ private _updateTotalContentSize(renderedContentSize: number) { const viewport = this._viewport!; const renderedRange = viewport.getRenderedRange(); const totalSize = renderedContentSize + (viewport.getDataLength() - (renderedRange.end - renderedRange.start)) * this._averager.getAverageItemSize(); viewport.setTotalContentSize(totalSize); } } /** * Provider factory for `AutoSizeVirtualScrollStrategy` that simply extracts the already created * `AutoSizeVirtualScrollStrategy` from the given directive. * @param autoSizeDir The instance of `CdkAutoSizeVirtualScroll` to extract the * `AutoSizeVirtualScrollStrategy` from. */ export function _autoSizeVirtualScrollStrategyFactory(autoSizeDir: CdkAutoSizeVirtualScroll) { return autoSizeDir._scrollStrategy; } /** A virtual scroll strategy that supports unknown or dynamic size items. */ @Directive({ selector: 'cdk-virtual-scroll-viewport[autosize]', providers: [ { provide: VIRTUAL_SCROLL_STRATEGY, useFactory: _autoSizeVirtualScrollStrategyFactory, deps: [forwardRef(() => CdkAutoSizeVirtualScroll)], }, ], }) export class CdkAutoSizeVirtualScroll implements OnChanges { /** * The minimum amount of buffer rendered beyond the viewport (in pixels). * If the amount of buffer dips below this number, more items will be rendered. Defaults to 100px. */ @Input() get minBufferPx(): number { return this._minBufferPx; } set minBufferPx(value: NumberInput) { this._minBufferPx = coerceNumberProperty(value); } _minBufferPx = 100; /** * The number of pixels worth of buffer to shoot for when rendering new items. * If the actual amount turns out to be less it will not necessarily trigger an additional * rendering cycle (as long as the amount of buffer is still greater than `minBufferPx`). * Defaults to 200px. */ @Input() get maxBufferPx(): number { return this._maxBufferPx; } set maxBufferPx(value: NumberInput) { this._maxBufferPx = coerceNumberProperty(value); } _maxBufferPx = 200; /** The scroll strategy used by this directive. */ _scrollStrategy = new AutoSizeVirtualScrollStrategy(this.minBufferPx, this.maxBufferPx); ngOnChanges() { this._scrollStrategy.updateBufferSize(this.minBufferPx, this.maxBufferPx); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 20257, "start_byte": 15477, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/scrolling/auto-size-virtual-scroll.ts" }
components/src/cdk-experimental/popover-edit/table-directives.ts_0_6430
/** * @license * Copyright Google LLC 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.dev/license */ import {FocusTrap} from '@angular/cdk/a11y'; import {OverlayRef, OverlaySizeConfig, PositionStrategy} from '@angular/cdk/overlay'; import {TemplatePortal} from '@angular/cdk/portal'; import { afterRender, AfterViewInit, Directive, ElementRef, EmbeddedViewRef, NgZone, OnDestroy, TemplateRef, ViewContainerRef, inject, } from '@angular/core'; import {fromEvent, fromEventPattern, merge, Subject} from 'rxjs'; import { debounceTime, filter, map, mapTo, share, startWith, takeUntil, throttleTime, withLatestFrom, } from 'rxjs/operators'; import {CELL_SELECTOR, EDIT_PANE_CLASS, EDIT_PANE_SELECTOR, ROW_SELECTOR} from './constants'; import {EditEventDispatcher, HoverContentState} from './edit-event-dispatcher'; import {EditServices} from './edit-services'; import {FocusDispatcher} from './focus-dispatcher'; import { FocusEscapeNotifier, FocusEscapeNotifierDirection, FocusEscapeNotifierFactory, } from './focus-escape-notifier'; import {closest} from './polyfill'; import {EditRef} from './edit-ref'; /** * Describes the number of columns before and after the originating cell that the * edit popup should span. In left to right locales, before means left and after means * right. In right to left locales before means right and after means left. */ export interface CdkPopoverEditColspan { before?: number; after?: number; } /** Used for rate-limiting mousemove events. */ const MOUSE_MOVE_THROTTLE_TIME_MS = 10; /** * A directive that must be attached to enable editability on a table. * It is responsible for setting up delegated event handlers and providing the * EditEventDispatcher service for use by the other edit directives. */ @Directive({ selector: 'table[editable], cdk-table[editable], mat-table[editable]', providers: [EditEventDispatcher, EditServices], }) export class CdkEditable implements AfterViewInit, OnDestroy { protected readonly elementRef = inject(ElementRef); protected readonly editEventDispatcher = inject<EditEventDispatcher<EditRef<unknown>>>(EditEventDispatcher); protected readonly focusDispatcher = inject(FocusDispatcher); protected readonly ngZone = inject(NgZone); protected readonly destroyed = new Subject<void>(); private _rendered = new Subject(); constructor() { afterRender(() => { this._rendered.next(); }); } ngAfterViewInit(): void { this._listenForTableEvents(); } ngOnDestroy(): void { this.destroyed.next(); this.destroyed.complete(); this._rendered.complete(); } private _listenForTableEvents(): void { const element = this.elementRef.nativeElement; const toClosest = (selector: string) => map((event: UIEvent) => closest(event.target, selector)); this.ngZone.runOutsideAngular(() => { // Track mouse movement over the table to hide/show hover content. fromEvent<MouseEvent>(element, 'mouseover') .pipe(toClosest(ROW_SELECTOR), takeUntil(this.destroyed)) .subscribe(this.editEventDispatcher.hovering); fromEvent<MouseEvent>(element, 'mouseleave') .pipe(mapTo(null), takeUntil(this.destroyed)) .subscribe(this.editEventDispatcher.hovering); fromEvent<MouseEvent>(element, 'mousemove') .pipe( throttleTime(MOUSE_MOVE_THROTTLE_TIME_MS), toClosest(ROW_SELECTOR), takeUntil(this.destroyed), ) .subscribe(this.editEventDispatcher.mouseMove); // Track focus within the table to hide/show/make focusable hover content. fromEventPattern<FocusEvent>( handler => element.addEventListener('focus', handler, true), handler => element.removeEventListener('focus', handler, true), ) .pipe(toClosest(ROW_SELECTOR), share(), takeUntil(this.destroyed)) .subscribe(this.editEventDispatcher.focused); merge( fromEventPattern<FocusEvent>( handler => element.addEventListener('blur', handler, true), handler => element.removeEventListener('blur', handler, true), ), fromEvent<KeyboardEvent>(element, 'keydown').pipe(filter(event => event.key === 'Escape')), ) .pipe(mapTo(null), share(), takeUntil(this.destroyed)) .subscribe(this.editEventDispatcher.focused); // Keep track of rows within the table. This is used to know which rows with hover content // are first or last in the table. They are kept focusable in case focus enters from above // or below the table. this._rendered .pipe( // Avoid some timing inconsistencies since Angular v19. debounceTime(0), // Optimization: ignore dom changes while focus is within the table as we already // ensure that rows above and below the focused/active row are tabbable. withLatestFrom(this.editEventDispatcher.editingOrFocused), filter(([_, activeRow]) => activeRow == null), map(() => element.querySelectorAll(ROW_SELECTOR)), share(), takeUntil(this.destroyed), ) .subscribe(this.editEventDispatcher.allRows); fromEvent<KeyboardEvent>(element, 'keydown') .pipe( filter(event => event.key === 'Enter'), toClosest(CELL_SELECTOR), takeUntil(this.destroyed), ) .subscribe(this.editEventDispatcher.editing); // Keydown must be used here or else key auto-repeat does not work properly on some platforms. fromEvent<KeyboardEvent>(element, 'keydown') .pipe(takeUntil(this.destroyed)) .subscribe(this.focusDispatcher.keyObserver); }); } } const POPOVER_EDIT_HOST_BINDINGS = { '[attr.tabindex]': 'disabled ? null : 0', 'class': 'cdk-popover-edit-cell', '[attr.aria-haspopup]': '!disabled', }; const POPOVER_EDIT_INPUTS = [ {name: 'template', alias: 'cdkPopoverEdit'}, {name: 'context', alias: 'cdkPopoverEditContext'}, {name: 'colspan', alias: 'cdkPopoverEditColspan'}, {name: 'disabled', alias: 'cdkPopoverEditDisabled'}, {name: 'ariaLabel', alias: 'cdkPopoverEditAriaLabel'}, ]; /** * Attaches an ng-template to a cell and shows it when instructed to by the * EditEventDispatcher service. * Makes the cell focusable. */
{ "commit_id": "ea0d1ba7b", "end_byte": 6430, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/table-directives.ts" }
components/src/cdk-experimental/popover-edit/table-directives.ts_6431_14151
@Directive({ selector: '[cdkPopoverEdit]:not([cdkPopoverEditTabOut])', host: POPOVER_EDIT_HOST_BINDINGS, inputs: POPOVER_EDIT_INPUTS, }) export class CdkPopoverEdit<C> implements AfterViewInit, OnDestroy { protected readonly services = inject(EditServices); protected readonly elementRef = inject(ElementRef); protected readonly viewContainerRef = inject(ViewContainerRef); /** The edit lens template shown over the cell on edit. */ template: TemplateRef<any> | null = null; /** * Implicit context to pass along to the template. Can be omitted if the template * is defined within the cell. */ context?: C; /** Aria label to set on the popover dialog element. */ ariaLabel?: string; /** * Specifies that the popup should cover additional table cells before and/or after * this one. */ get colspan(): CdkPopoverEditColspan { return this._colspan; } set colspan(value: CdkPopoverEditColspan) { this._colspan = value; // Recompute positioning when the colspan changes. if (this.overlayRef) { this.overlayRef.updatePositionStrategy(this._getPositionStrategy()); if (this.overlayRef.hasAttached()) { this._updateOverlaySize(); } } } private _colspan: CdkPopoverEditColspan = {}; /** Whether popover edit is disabled for this cell. */ get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = value; if (value) { this.services.editEventDispatcher.doneEditingCell(this.elementRef.nativeElement!); this.services.editEventDispatcher.disabledCells.set(this.elementRef.nativeElement!, true); } else { this.services.editEventDispatcher.disabledCells.delete(this.elementRef.nativeElement!); } } private _disabled = false; protected focusTrap?: FocusTrap; protected overlayRef?: OverlayRef; protected readonly destroyed = new Subject<void>(); ngAfterViewInit(): void { this._startListeningToEditEvents(); } ngOnDestroy(): void { this.destroyed.next(); this.destroyed.complete(); if (this.focusTrap) { this.focusTrap.destroy(); this.focusTrap = undefined; } if (this.overlayRef) { this.overlayRef.dispose(); } } protected initFocusTrap(): void { this.focusTrap = this.services.focusTrapFactory.create(this.overlayRef!.overlayElement); } protected closeEditOverlay(): void { this.services.editEventDispatcher.doneEditingCell(this.elementRef.nativeElement!); } protected panelClass(): string { return EDIT_PANE_CLASS; } private _startListeningToEditEvents(): void { this.services.editEventDispatcher .editingCell(this.elementRef.nativeElement!) .pipe(takeUntil(this.destroyed)) .subscribe(open => { if (open && this.template) { if (!this.overlayRef) { this._createEditOverlay(); } this._showEditOverlay(); } else if (this.overlayRef) { this._maybeReturnFocusToCell(); this.overlayRef.detach(); } }); } private _createEditOverlay(): void { this.overlayRef = this.services.overlay.create({ disposeOnNavigation: true, panelClass: this.panelClass(), positionStrategy: this._getPositionStrategy(), scrollStrategy: this.services.overlay.scrollStrategies.reposition(), direction: this.services.directionality, }); this.initFocusTrap(); this.overlayRef.overlayElement.setAttribute('role', 'dialog'); if (this.ariaLabel) { this.overlayRef.overlayElement.setAttribute('aria-label', this.ariaLabel); } this.overlayRef.detachments().subscribe(() => this.closeEditOverlay()); } private _showEditOverlay(): void { this.overlayRef!.attach( new TemplatePortal(this.template!, this.viewContainerRef, {$implicit: this.context}), ); // We have to defer trapping focus, because doing so too early can cause the form inside // the overlay to be submitted immediately if it was opened on an Enter keydown event. this.services.ngZone.runOutsideAngular(() => { setTimeout(() => { this.focusTrap!.focusInitialElement(); }); }); // Update the size of the popup initially and on subsequent changes to // scroll position and viewport size. merge(this.services.scrollDispatcher.scrolled(), this.services.viewportRuler.change()) .pipe(startWith(null), takeUntil(merge(this.overlayRef!.detachments(), this.destroyed))) .subscribe(() => { this._updateOverlaySize(); }); } private _getOverlayCells(): HTMLElement[] { const cell = closest(this.elementRef.nativeElement!, CELL_SELECTOR) as HTMLElement; if (!this._colspan.before && !this._colspan.after) { return [cell]; } const row = closest(this.elementRef.nativeElement!, ROW_SELECTOR)!; const rowCells = Array.from(row.querySelectorAll(CELL_SELECTOR)) as HTMLElement[]; const ownIndex = rowCells.indexOf(cell); return rowCells.slice( ownIndex - (this._colspan.before || 0), ownIndex + (this._colspan.after || 0) + 1, ); } private _getPositionStrategy(): PositionStrategy { const cells = this._getOverlayCells(); return this.services.overlay .position() .flexibleConnectedTo(cells[0]) .withGrowAfterOpen() .withPush() .withViewportMargin(16) .withPositions([ { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top', }, ]); } private _updateOverlaySize(): void { this.overlayRef!.updateSize(this._sizeConfigForCells(this._getOverlayCells())); } private _maybeReturnFocusToCell(): void { if (closest(document.activeElement, EDIT_PANE_SELECTOR) === this.overlayRef!.overlayElement) { this.elementRef.nativeElement!.focus(); } } private _sizeConfigForCells(cells: HTMLElement[]): OverlaySizeConfig { if (cells.length === 0) { return {}; } if (cells.length === 1) { return {width: cells[0].getBoundingClientRect().width}; } let firstCell, lastCell; if (this.services.directionality.value === 'ltr') { firstCell = cells[0]; lastCell = cells[cells.length - 1]; } else { lastCell = cells[0]; firstCell = cells[cells.length - 1]; } return {width: lastCell.getBoundingClientRect().right - firstCell.getBoundingClientRect().left}; } } /** * Attaches an ng-template to a cell and shows it when instructed to by the * EditEventDispatcher service. * Makes the cell focusable. */ @Directive({ selector: '[cdkPopoverEdit][cdkPopoverEditTabOut]', host: POPOVER_EDIT_HOST_BINDINGS, inputs: POPOVER_EDIT_INPUTS, }) export class CdkPopoverEditTabOut<C> extends CdkPopoverEdit<C> { protected readonly focusEscapeNotifierFactory = inject(FocusEscapeNotifierFactory); protected override focusTrap?: FocusEscapeNotifier = undefined; protected override initFocusTrap(): void { this.focusTrap = this.focusEscapeNotifierFactory.create(this.overlayRef!.overlayElement); this.focusTrap .escapes() .pipe(takeUntil(this.destroyed)) .subscribe(direction => { this.services.editEventDispatcher.editRef?.blur(); this.services.focusDispatcher.moveFocusHorizontally( closest(this.elementRef.nativeElement!, CELL_SELECTOR) as HTMLElement, direction === FocusEscapeNotifierDirection.START ? -1 : 1, ); this.closeEditOverlay(); }); } } /** * A structural directive that shows its contents when the table row containing * it is hovered or when an element in the row has focus. */
{ "commit_id": "ea0d1ba7b", "end_byte": 14151, "start_byte": 6431, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/table-directives.ts" }
components/src/cdk-experimental/popover-edit/table-directives.ts_14152_18118
@Directive({ selector: '[cdkRowHoverContent]', }) export class CdkRowHoverContent implements AfterViewInit, OnDestroy { protected readonly services = inject(EditServices); protected readonly elementRef = inject(ElementRef); protected readonly templateRef = inject<TemplateRef<any>>(TemplateRef); protected readonly viewContainerRef = inject(ViewContainerRef); protected readonly destroyed = new Subject<void>(); protected viewRef: EmbeddedViewRef<any> | null = null; private _row?: Element; ngAfterViewInit(): void { this._row = closest(this.elementRef.nativeElement!, ROW_SELECTOR)!; this.services.editEventDispatcher.registerRowWithHoverContent(this._row); this._listenForHoverAndFocusEvents(); } ngOnDestroy(): void { this.destroyed.next(); this.destroyed.complete(); if (this.viewRef) { this.viewRef.destroy(); } if (this._row) { this.services.editEventDispatcher.deregisterRowWithHoverContent(this._row); } } /** * Called immediately after the hover content is created and added to the dom. * In the CDK version, this is a noop but subclasses such as MatRowHoverContent use this * to prepare/style the inserted element. */ protected initElement(_: HTMLElement): void {} /** * Called when the hover content needs to be focusable to preserve a reasonable tab ordering * but should not yet be shown. */ protected makeElementHiddenButFocusable(element: HTMLElement): void { element.style.opacity = '0'; } /** * Called when the hover content needs to be focusable to preserve a reasonable tab ordering * but should not yet be shown. */ protected makeElementVisible(element: HTMLElement): void { element.style.opacity = ''; } private _listenForHoverAndFocusEvents(): void { this.services.editEventDispatcher .hoverOrFocusOnRow(this._row!) .pipe(takeUntil(this.destroyed)) .subscribe(eventState => { // When in FOCUSABLE state, add the hover content to the dom but make it transparent so // that it is in the tab order relative to the currently focused row. if (eventState === HoverContentState.ON || eventState === HoverContentState.FOCUSABLE) { if (!this.viewRef) { this.viewRef = this.viewContainerRef.createEmbeddedView(this.templateRef, {}); this.initElement(this.viewRef.rootNodes[0] as HTMLElement); this.viewRef.markForCheck(); } else if (this.viewContainerRef.indexOf(this.viewRef) === -1) { this.viewContainerRef.insert(this.viewRef!); this.viewRef.markForCheck(); } if (eventState === HoverContentState.ON) { this.makeElementVisible(this.viewRef.rootNodes[0] as HTMLElement); } else { this.makeElementHiddenButFocusable(this.viewRef.rootNodes[0] as HTMLElement); } } else if (this.viewRef) { this.viewContainerRef.detach(this.viewContainerRef.indexOf(this.viewRef)); } }); } } /** * Opens the closest edit popover to this element, whether it's associated with this exact * element or an ancestor element. */ @Directive({ selector: '[cdkEditOpen]', host: { '(click)': 'openEdit($event)', }, }) export class CdkEditOpen { protected readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected readonly editEventDispatcher = inject<EditEventDispatcher<EditRef<unknown>>>(EditEventDispatcher); constructor() { const elementRef = this.elementRef; const nativeElement = elementRef.nativeElement; // Prevent accidental form submits. if (nativeElement.nodeName === 'BUTTON' && !nativeElement.getAttribute('type')) { nativeElement.setAttribute('type', 'button'); } } openEdit(evt: Event): void { this.editEventDispatcher.editing.next(closest(this.elementRef.nativeElement!, CELL_SELECTOR)); evt.stopPropagation(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 18118, "start_byte": 14152, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/table-directives.ts" }
components/src/cdk-experimental/popover-edit/popover-edit-module.ts_0_829
/** * @license * Copyright Google LLC 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.dev/license */ import {NgModule} from '@angular/core'; import {OverlayModule} from '@angular/cdk/overlay'; import { CdkPopoverEdit, CdkPopoverEditTabOut, CdkRowHoverContent, CdkEditable, CdkEditOpen, } from './table-directives'; import {CdkEditControl, CdkEditRevert, CdkEditClose} from './lens-directives'; const EXPORTED_DECLARATIONS = [ CdkPopoverEdit, CdkPopoverEditTabOut, CdkRowHoverContent, CdkEditControl, CdkEditRevert, CdkEditClose, CdkEditable, CdkEditOpen, ]; @NgModule({ imports: [OverlayModule, ...EXPORTED_DECLARATIONS], exports: EXPORTED_DECLARATIONS, }) export class CdkPopoverEditModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 829, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/popover-edit-module.ts" }
components/src/cdk-experimental/popover-edit/polyfill.ts_0_623
/** * @license * Copyright Google LLC 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.dev/license */ /** closest implementation that is able to start from non-Element Nodes. */ export function closest( element: EventTarget | Element | null | undefined, selector: string, ): Element | null { if (!(element instanceof Node)) { return null; } let curr: Node | null = element; while (curr != null && !(curr instanceof Element)) { curr = curr.parentNode; } return curr?.closest(selector) ?? null; }
{ "commit_id": "ea0d1ba7b", "end_byte": 623, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/polyfill.ts" }
components/src/cdk-experimental/popover-edit/public-api.ts_0_602
/** * @license * Copyright Google LLC 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.dev/license */ export * from './edit-event-dispatcher'; export * from './edit-ref'; export * from './focus-dispatcher'; export * from './form-value-container'; export * from './lens-directives'; export * from './popover-edit-module'; export * from './table-directives'; // Private to Angular Components export {CELL_SELECTOR as _CELL_SELECTOR} from './constants'; export {closest as _closest} from './polyfill';
{ "commit_id": "ea0d1ba7b", "end_byte": 602, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/public-api.ts" }
components/src/cdk-experimental/popover-edit/focus-escape-notifier.ts_0_2251
/** * @license * Copyright Google LLC 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.dev/license */ import {Injectable, NgZone, inject} from '@angular/core'; import {DOCUMENT} from '@angular/common'; import {FocusTrap, InteractivityChecker} from '@angular/cdk/a11y'; import {Observable, Subject} from 'rxjs'; /** Value indicating whether focus left the target area before or after the enclosed elements. */ export enum FocusEscapeNotifierDirection { START, END, } /** * Like FocusTrap, but rather than trapping focus within a dom region, notifies subscribers when * focus leaves the region. */ export class FocusEscapeNotifier extends FocusTrap { private readonly _escapeSubject = new Subject<FocusEscapeNotifierDirection>(); constructor( element: HTMLElement, checker: InteractivityChecker, ngZone: NgZone, document: Document, ) { super(element, checker, ngZone, document, true /* deferAnchors */); // The focus trap adds "anchors" at the beginning and end of a trapped region that redirect // focus. We override that redirect behavior here with simply emitting on a stream. this.startAnchorListener = () => { this._escapeSubject.next(FocusEscapeNotifierDirection.START); return true; }; this.endAnchorListener = () => { this._escapeSubject.next(FocusEscapeNotifierDirection.END); return true; }; this.attachAnchors(); } escapes(): Observable<FocusEscapeNotifierDirection> { return this._escapeSubject; } } /** Factory that allows easy instantiation of focus escape notifiers. */ @Injectable({providedIn: 'root'}) export class FocusEscapeNotifierFactory { private _checker = inject(InteractivityChecker); private _ngZone = inject(NgZone); private _document = inject(DOCUMENT); /** * Creates a focus escape notifier region around the given element. * @param element The element around which focus will be monitored. * @returns The created focus escape notifier instance. */ create(element: HTMLElement): FocusEscapeNotifier { return new FocusEscapeNotifier(element, this._checker, this._ngZone, this._document); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2251, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/focus-escape-notifier.ts" }
components/src/cdk-experimental/popover-edit/form-value-container.ts_0_1031
/** * @license * Copyright Google LLC 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.dev/license */ export interface Entry<FormValue> { value?: FormValue; } /** * A convenience class for preserving unsaved form state while an edit lens is closed. * * Example usage: * class MyComponent { * readonly nameEditValues = new FormValueContainer&lt;Item, {name: string}&gt;(); * } * * &lt;form cdkEditControl [(cdkEditControlPreservedFormValue)]="nameEditValues.for(item).value"&gt; */ export class FormValueContainer<Key extends object, FormValue> { private _formValues = new WeakMap<Key, Entry<FormValue>>(); for(key: Key): Entry<FormValue> { const _formValues = this._formValues; let entry = _formValues.get(key); if (!entry) { // Expose entry as an object so that we can [(two-way)] bind to its value member entry = {}; _formValues.set(key, entry); } return entry; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1031, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/form-value-container.ts" }
components/src/cdk-experimental/popover-edit/edit-event-dispatcher.ts_0_1389
/** * @license * Copyright Google LLC 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.dev/license */ import {Injectable, NgZone, inject} from '@angular/core'; import {combineLatest, MonoTypeOperatorFunction, Observable, pipe, Subject} from 'rxjs'; import { audit, auditTime, debounceTime, distinctUntilChanged, filter, map, skip, startWith, shareReplay, } from 'rxjs/operators'; import {CELL_SELECTOR, ROW_SELECTOR} from './constants'; import {closest} from './polyfill'; /** The delay applied to mouse events before hiding or showing hover content. */ const MOUSE_EVENT_DELAY_MS = 40; /** The delay for reacting to focus/blur changes. */ const FOCUS_DELAY = 0; /** * The possible states for hover content: * OFF - Not rendered. * FOCUSABLE - Rendered in the dom and styled for its contents to be focusable but invisible. * ON - Rendered and fully visible. */ export enum HoverContentState { OFF = 0, FOCUSABLE, ON, } // Note: this class is generic, rather than referencing EditRef directly, in order to avoid // circular imports. If we were to reference it here, importing the registry into the // class that is registering itself will introduce a circular import. /** * Service for sharing delegated events and state for triggering table edits. */
{ "commit_id": "ea0d1ba7b", "end_byte": 1389, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/edit-event-dispatcher.ts" }
components/src/cdk-experimental/popover-edit/edit-event-dispatcher.ts_1390_9211
@Injectable() export class EditEventDispatcher<R> { private readonly _ngZone = inject(NgZone); /** A subject that indicates which table cell is currently editing (unless it is disabled). */ readonly editing = new Subject<Element | null>(); /** A subject that indicates which table row is currently hovered. */ readonly hovering = new Subject<Element | null>(); /** A subject that indicates which table row currently contains focus. */ readonly focused = new Subject<Element | null>(); /** A subject that indicates all elements in the table matching ROW_SELECTOR. */ readonly allRows = new Subject<NodeList>(); /** A subject that emits mouse move events from the table indicating the targeted row. */ readonly mouseMove = new Subject<Element | null>(); // TODO: Use WeakSet once IE11 support is dropped. /** * Tracks the currently disabled editable cells - edit calls will be ignored * for these cells. */ readonly disabledCells = new WeakMap<Element, boolean>(); /** The EditRef for the currently active edit lens (if any). */ get editRef(): R | null { return this._editRef; } private _editRef: R | null = null; // Optimization: Precompute common pipeable operators used per row/cell. private readonly _distinctUntilChanged = distinctUntilChanged< Element | HoverContentState | boolean | null >(); private readonly _startWithNull = startWith<Element | null>(null); private readonly _distinctShare = pipe( this._distinctUntilChanged as MonoTypeOperatorFunction<HoverContentState>, shareReplay(1), ); private readonly _startWithNullDistinct = pipe( this._startWithNull, this._distinctUntilChanged as MonoTypeOperatorFunction<Element | null>, ); readonly editingAndEnabled = this.editing.pipe( filter(cell => cell == null || !this.disabledCells.has(cell)), shareReplay(1), ); /** An observable that emits the row containing focus or an active edit. */ readonly editingOrFocused = combineLatest([ this.editingAndEnabled.pipe( map(cell => closest(cell, ROW_SELECTOR)), this._startWithNull, ), this.focused.pipe(this._startWithNull), ]).pipe( map(([editingRow, focusedRow]) => focusedRow || editingRow), this._distinctUntilChanged as MonoTypeOperatorFunction<Element | null>, auditTime(FOCUS_DELAY), // Use audit to skip over blur events to the next focused element. this._distinctUntilChanged as MonoTypeOperatorFunction<Element | null>, shareReplay(1), ); /** Tracks rows that contain hover content with a reference count. */ private _rowsWithHoverContent = new WeakMap<Element, number>(); /** The table cell that has an active edit lens (or null). */ private _currentlyEditing: Element | null = null; /** The combined set of row hover content states organized by row. */ private readonly _hoveredContentStateDistinct = combineLatest([ this._getFirstRowWithHoverContent(), this._getLastRowWithHoverContent(), this.editingOrFocused, this.hovering.pipe( distinctUntilChanged(), audit(row => this.mouseMove.pipe( filter(mouseMoveRow => row === mouseMoveRow), this._startWithNull, debounceTime(MOUSE_EVENT_DELAY_MS), ), ), this._startWithNullDistinct, ), ]).pipe( skip(1), // Skip the initial emission of [null, null, null, null]. map(computeHoverContentState), distinctUntilChanged(areMapEntriesEqual), // Optimization: Enter the zone before shareReplay so that we trigger a single // ApplicationRef.tick for all row updates. this._enterZone(), shareReplay(1), ); private readonly _editingAndEnabledDistinct = this.editingAndEnabled.pipe( distinctUntilChanged(), this._enterZone(), shareReplay(1), ); // Optimization: Share row events observable with subsequent callers. // At startup, calls will be sequential by row. private _lastSeenRow: Element | null = null; private _lastSeenRowHoverOrFocus: Observable<HoverContentState> | null = null; constructor() { this._editingAndEnabledDistinct.subscribe(cell => { this._currentlyEditing = cell; }); } /** * Gets an Observable that emits true when the specified element's cell * is editing and false when not. */ editingCell(element: Element | EventTarget): Observable<boolean> { let cell: Element | null = null; return this._editingAndEnabledDistinct.pipe( map(editCell => editCell === (cell || (cell = closest(element, CELL_SELECTOR)))), this._distinctUntilChanged as MonoTypeOperatorFunction<boolean>, ); } /** * Stops editing for the specified cell. If the specified cell is not the current * edit cell, does nothing. */ doneEditingCell(element: Element | EventTarget): void { const cell = closest(element, CELL_SELECTOR); if (this._currentlyEditing === cell) { this.editing.next(null); } } /** Sets the currently active EditRef. */ setActiveEditRef(ref: R) { this._editRef = ref; } /** Unset the currently active EditRef, if the specified editRef is active. */ unsetActiveEditRef(ref: R) { if (this._editRef !== ref) { return; } this._editRef = null; } /** Adds the specified table row to be tracked for first/last row comparisons. */ registerRowWithHoverContent(row: Element): void { this._rowsWithHoverContent.set(row, (this._rowsWithHoverContent.get(row) || 0) + 1); } /** * Reference decrements and ultimately removes the specified table row from first/last row * comparisons. */ deregisterRowWithHoverContent(row: Element): void { const refCount = this._rowsWithHoverContent.get(row) || 0; if (refCount <= 1) { this._rowsWithHoverContent.delete(row); } else { this._rowsWithHoverContent.set(row, refCount - 1); } } /** * Gets an Observable that emits true when the specified element's row * contains the focused element or is being hovered over and false when not. * Hovering is defined as when the mouse has momentarily stopped moving over the cell. */ hoverOrFocusOnRow(row: Element): Observable<HoverContentState> { if (row !== this._lastSeenRow) { this._lastSeenRow = row; this._lastSeenRowHoverOrFocus = this._hoveredContentStateDistinct.pipe( map(state => state.get(row) || HoverContentState.OFF), this._distinctShare, ); } return this._lastSeenRowHoverOrFocus!; } /** * RxJS operator that enters the Angular zone, used to reduce boilerplate in * re-entering the zone for stream pipelines. */ private _enterZone<T>(): MonoTypeOperatorFunction<T> { return (source: Observable<T>) => new Observable<T>(observer => source.subscribe({ next: value => this._ngZone.run(() => observer.next(value)), error: err => observer.error(err), complete: () => observer.complete(), }), ); } private _getFirstRowWithHoverContent(): Observable<Element | null> { return this._mapAllRowsToSingleRow(rows => { for (let i = 0, row; (row = rows[i]); i++) { if (this._rowsWithHoverContent.has(row as Element)) { return row as Element; } } return null; }); } private _getLastRowWithHoverContent(): Observable<Element | null> { return this._mapAllRowsToSingleRow(rows => { for (let i = rows.length - 1, row; (row = rows[i]); i--) { if (this._rowsWithHoverContent.has(row as Element)) { return row as Element; } } return null; }); } private _mapAllRowsToSingleRow( mapper: (rows: NodeList) => Element | null, ): Observable<Element | null> { return this.allRows.pipe(map(mapper), this._startWithNullDistinct); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 9211, "start_byte": 1390, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/edit-event-dispatcher.ts" }
components/src/cdk-experimental/popover-edit/edit-event-dispatcher.ts_9213_10252
function computeHoverContentState([ firstRow, lastRow, activeRow, hoverRow, ]: (Element | null)[]): Map<Element, HoverContentState> { const hoverContentState = new Map<Element, HoverContentState>(); // Add focusable rows. for (const focussableRow of [ firstRow, lastRow, activeRow && activeRow.previousElementSibling, activeRow && activeRow.nextElementSibling, ]) { if (focussableRow) { hoverContentState.set(focussableRow as Element, HoverContentState.FOCUSABLE); } } // Add/overwrite with fully visible rows. for (const onRow of [activeRow, hoverRow]) { if (onRow) { hoverContentState.set(onRow, HoverContentState.ON); } } return hoverContentState; } function areMapEntriesEqual<K, V>(a: Map<K, V>, b: Map<K, V>): boolean { if (a.size !== b.size) { return false; } // TODO: use Map.prototype.entries once we're off IE11. for (const aKey of Array.from(a.keys())) { if (b.get(aKey) !== a.get(aKey)) { return false; } } return true; }
{ "commit_id": "ea0d1ba7b", "end_byte": 10252, "start_byte": 9213, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/edit-event-dispatcher.ts" }
components/src/cdk-experimental/popover-edit/lens-directives.ts_0_6050
/** * @license * Copyright Google LLC 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.dev/license */ import {Subject} from 'rxjs'; import {Directive, ElementRef, EventEmitter, OnDestroy, OnInit, Input, inject} from '@angular/core'; import {hasModifierKey} from '@angular/cdk/keycodes'; import {EDIT_PANE_SELECTOR} from './constants'; import {closest} from './polyfill'; import {EditRef} from './edit-ref'; /** Options for what do to when the user clicks outside of an edit lens. */ export type PopoverEditClickOutBehavior = 'close' | 'submit' | 'noop'; /** * A directive that attaches to a form within the edit lens. * It coordinates the form state with the table-wide edit system and handles * closing the edit lens when the form is submitted or the user clicks * out. */ @Directive({ selector: 'form[cdkEditControl]', inputs: [ {name: 'clickOutBehavior', alias: 'cdkEditControlClickOutBehavior'}, {name: 'preservedFormValue', alias: 'cdkEditControlPreservedFormValue'}, {name: 'ignoreSubmitUnlessValid', alias: 'cdkEditControlIgnoreSubmitUnlessValid'}, ], outputs: ['preservedFormValueChange: cdkEditControlPreservedFormValueChange'], providers: [EditRef], host: { '(ngSubmit)': 'handleFormSubmit()', '(document:click)': 'handlePossibleClickOut($event)', '(keydown)': '_handleKeydown($event)', }, }) export class CdkEditControl<FormValue> implements OnDestroy, OnInit { protected readonly elementRef = inject(ElementRef); readonly editRef = inject<EditRef<FormValue>>(EditRef); protected readonly destroyed = new Subject<void>(); /** * Specifies what should happen when the user clicks outside of the edit lens. * The default behavior is to close the lens without submitting the form. */ clickOutBehavior: PopoverEditClickOutBehavior = 'close'; /** * A two-way binding for storing unsubmitted form state. If not provided * then form state will be discarded on close. The PeristBy directive is offered * as a convenient shortcut for these bindings. */ preservedFormValue?: FormValue; readonly preservedFormValueChange = new EventEmitter<FormValue>(); /** * Determines whether the lens will close on form submit if the form is not in a valid * state. By default the lens will remain open. */ ignoreSubmitUnlessValid = true; ngOnInit(): void { this.editRef.init(this.preservedFormValue); this.editRef.finalValue.subscribe(this.preservedFormValueChange); this.editRef.blurred.subscribe(() => this._handleBlur()); } ngOnDestroy(): void { this.destroyed.next(); this.destroyed.complete(); } /** * Called when the form submits. If ignoreSubmitUnlessValid is true, checks * the form for validity before proceeding. * Updates the revert state with the latest submitted value then closes the edit. */ handleFormSubmit(): void { if (this.ignoreSubmitUnlessValid && !this.editRef.isValid()) { return; } this.editRef.updateRevertValue(); this.editRef.close(); } /** Called on Escape keyup. Closes the edit. */ close(): void { // todo - allow this behavior to be customized as well, such as calling // reset before close this.editRef.close(); } /** * Called on click anywhere in the document. * If the click was outside of the lens, trigger the specified click out behavior. */ handlePossibleClickOut(evt: Event): void { if (closest(evt.target, EDIT_PANE_SELECTOR)) { return; } switch (this.clickOutBehavior) { case 'submit': // Manually cause the form to submit before closing. this._triggerFormSubmit(); this.editRef.close(); break; case 'close': this.editRef.close(); break; default: break; } } _handleKeydown(event: KeyboardEvent) { if (event.key === 'Escape' && !hasModifierKey(event)) { this.close(); event.preventDefault(); } } /** Triggers submit on tab out if clickOutBehavior is 'submit'. */ private _handleBlur(): void { if (this.clickOutBehavior === 'submit') { // Manually cause the form to submit before closing. this._triggerFormSubmit(); } } private _triggerFormSubmit() { this.elementRef.nativeElement!.dispatchEvent(new Event('submit')); } } /** Reverts the form to its initial or previously submitted state on click. */ @Directive({ selector: 'button[cdkEditRevert]', host: { 'type': 'button', '(click)': 'revertEdit()', }, }) export class CdkEditRevert<FormValue> { protected readonly editRef = inject<EditRef<FormValue>>(EditRef); /** Type of the button. Defaults to `button` to avoid accident form submits. */ @Input() type: string = 'button'; revertEdit(): void { this.editRef.reset(); } } /** Closes the lens on click. */ @Directive({ selector: '[cdkEditClose]', host: { '(click)': 'closeEdit()', '(keydown.enter)': 'closeEdit()', '(keydown.space)': 'closeEdit()', }, }) export class CdkEditClose<FormValue> { protected readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected readonly editRef = inject<EditRef<FormValue>>(EditRef); constructor() { const nativeElement = this.elementRef.nativeElement; // Prevent accidental form submits. if (nativeElement.nodeName === 'BUTTON' && !nativeElement.getAttribute('type')) { nativeElement.setAttribute('type', 'button'); } } closeEdit(): void { // Note that we use `click` here, rather than a keyboard event, because some screen readers // will emit a fake click event instead of an enter keyboard event on buttons. For the keyboard // events we use `keydown`, rather than `keyup`, because we use `keydown` to open the overlay // as well. If we were to use `keyup`, the user could end up opening and closing within // the same event sequence if focus was moved quickly. this.editRef.close(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 6050, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/lens-directives.ts" }
components/src/cdk-experimental/popover-edit/constants.ts_0_862
/** * @license * Copyright Google LLC 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.dev/license */ /** Selector for finding table cells. */ export const CELL_SELECTOR = '.cdk-cell, .mat-cell, td'; /** Selector for finding editable table cells. */ export const EDITABLE_CELL_SELECTOR = '.cdk-popover-edit-cell, .mat-popover-edit-cell'; /** Selector for finding table rows. */ export const ROW_SELECTOR = '.cdk-row, .mat-row, tr'; /** Selector for finding the table element. */ export const TABLE_SELECTOR = 'table, cdk-table, mat-table'; /** CSS class added to the edit lens pane. */ export const EDIT_PANE_CLASS = 'cdk-edit-pane'; /** Selector for finding the edit lens pane. */ export const EDIT_PANE_SELECTOR = `.${EDIT_PANE_CLASS}, .mat-edit-pane`;
{ "commit_id": "ea0d1ba7b", "end_byte": 862, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/constants.ts" }
components/src/cdk-experimental/popover-edit/edit-ref.ts_0_2959
/** * @license * Copyright Google LLC 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.dev/license */ import {Injectable, OnDestroy, afterNextRender, inject, Injector} from '@angular/core'; import {ControlContainer} from '@angular/forms'; import {Observable, Subject} from 'rxjs'; import {EditEventDispatcher} from './edit-event-dispatcher'; /** * Used for communication between the form within the edit lens and the * table that launched it. Provided by CdkEditControl within the lens. */ @Injectable() export class EditRef<FormValue> implements OnDestroy { private readonly _form = inject(ControlContainer, {self: true}); private readonly _editEventDispatcher = inject<EditEventDispatcher<EditRef<FormValue>>>(EditEventDispatcher); /** Emits the final value of this edit instance before closing. */ private readonly _finalValueSubject = new Subject<FormValue>(); readonly finalValue: Observable<FormValue> = this._finalValueSubject; /** Emits when the user tabs out of this edit lens before closing. */ private readonly _blurredSubject = new Subject<void>(); readonly blurred: Observable<void> = this._blurredSubject; /** The value to set the form back to on revert. */ private _revertFormValue: FormValue; private _injector = inject(Injector); constructor() { this._editEventDispatcher.setActiveEditRef(this); } /** * Called by the host directive's OnInit hook. Reads the initial state of the * form and overrides it with persisted state from previous openings, if * applicable. */ init(previousFormValue: FormValue | undefined): void { // Wait for the next render before caching the initial value. // This ensures that all form controls have been initialized. afterNextRender( () => { this.updateRevertValue(); if (previousFormValue) { this.reset(previousFormValue); } }, {injector: this._injector}, ); } ngOnDestroy(): void { this._editEventDispatcher.unsetActiveEditRef(this); this._finalValueSubject.next(this._form.value); this._finalValueSubject.complete(); } /** Whether the attached form is in a valid state. */ isValid(): boolean | null { return this._form.valid; } /** Set the form's current value as what it will be set to on revert/reset. */ updateRevertValue(): void { this._revertFormValue = this._form.value; } /** Tells the table to close the edit popup. */ close(): void { this._editEventDispatcher.editing.next(null); } /** Notifies the active edit that the user has moved focus out of the lens. */ blur(): void { this._blurredSubject.next(); } /** * Resets the form value to the specified value or the previously set * revert value. */ reset(value?: FormValue): void { this._form.reset(value || this._revertFormValue); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2959, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/edit-ref.ts" }
components/src/cdk-experimental/popover-edit/BUILD.bazel_0_1105
load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite") package(default_visibility = ["//visibility:public"]) ng_module( name = "popover-edit", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/a11y", "//src/cdk/bidi", "//src/cdk/keycodes", "//src/cdk/overlay", "//src/cdk/portal", "//src/cdk/scrolling", "@npm//@angular/common", "@npm//@angular/core", "@npm//@angular/forms", "@npm//rxjs", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":popover-edit", "//src/cdk/bidi", "//src/cdk/collections", "//src/cdk/keycodes", "//src/cdk/overlay", "//src/cdk/table", "//src/cdk/testing/private", "@npm//@angular/common", "@npm//@angular/forms", "@npm//rxjs", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], )
{ "commit_id": "ea0d1ba7b", "end_byte": 1105, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/BUILD.bazel" }
components/src/cdk-experimental/popover-edit/focus-dispatcher.ts_0_3244
/** * @license * Copyright Google LLC 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.dev/license */ import {Directionality} from '@angular/cdk/bidi'; import {LEFT_ARROW, UP_ARROW, RIGHT_ARROW, DOWN_ARROW} from '@angular/cdk/keycodes'; import {Injectable, inject} from '@angular/core'; import {PartialObserver} from 'rxjs'; import {EDITABLE_CELL_SELECTOR, ROW_SELECTOR, TABLE_SELECTOR} from './constants'; import {closest} from './polyfill'; /** * Service responsible for moving cell focus around in response to keyboard events. * May be overridden to customize the keyboard behavior of popover edit. */ @Injectable({providedIn: 'root'}) export class FocusDispatcher { protected readonly directionality = inject(Directionality); /** Observes keydown events triggered from the table. */ readonly keyObserver: PartialObserver<KeyboardEvent>; constructor() { this.keyObserver = {next: event => this.handleKeyboardEvent(event)}; } /** * Moves focus to earlier or later cells (in dom order) by offset cells relative to * currentCell. */ moveFocusHorizontally(currentCell: HTMLElement, offset: number): void { const cells = Array.from( closest(currentCell, TABLE_SELECTOR)!.querySelectorAll(EDITABLE_CELL_SELECTOR), ) as HTMLElement[]; const currentIndex = cells.indexOf(currentCell); const newIndex = currentIndex + offset; if (cells[newIndex]) { cells[newIndex].focus(); } } /** Moves focus to up or down by row by offset cells relative to currentCell. */ moveFocusVertically(currentCell: HTMLElement, offset: number): void { const currentRow = closest(currentCell, ROW_SELECTOR)!; const rows = Array.from(closest(currentRow, TABLE_SELECTOR)!.querySelectorAll(ROW_SELECTOR)); const currentRowIndex = rows.indexOf(currentRow); const currentIndexWithinRow = Array.from( currentRow.querySelectorAll(EDITABLE_CELL_SELECTOR), ).indexOf(currentCell); const newRowIndex = currentRowIndex + offset; if (rows[newRowIndex]) { const rowToFocus = Array.from( rows[newRowIndex].querySelectorAll(EDITABLE_CELL_SELECTOR), ) as HTMLElement[]; if (rowToFocus[currentIndexWithinRow]) { rowToFocus[currentIndexWithinRow].focus(); } } } /** Translates arrow keydown events into focus move operations. */ protected handleKeyboardEvent(event: KeyboardEvent): void { const cell = closest(event.target, EDITABLE_CELL_SELECTOR) as HTMLElement | null; if (!cell) { return; } switch (event.keyCode) { case UP_ARROW: this.moveFocusVertically(cell, -1); break; case DOWN_ARROW: this.moveFocusVertically(cell, 1); break; case LEFT_ARROW: this.moveFocusHorizontally(cell, this.directionality.value === 'ltr' ? -1 : 1); break; case RIGHT_ARROW: this.moveFocusHorizontally(cell, this.directionality.value === 'ltr' ? 1 : -1); break; default: // If the keyboard event is not handled, return now so that we don't `preventDefault`. return; } event.preventDefault(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3244, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/focus-dispatcher.ts" }
components/src/cdk-experimental/popover-edit/index.ts_0_234
/** * @license * Copyright Google LLC 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.dev/license */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/index.ts" }
components/src/cdk-experimental/popover-edit/edit-services.ts_0_1369
/** * @license * Copyright Google LLC 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.dev/license */ import {Injectable, NgZone, inject} from '@angular/core'; import {FocusTrapFactory} from '@angular/cdk/a11y'; import {Directionality} from '@angular/cdk/bidi'; import {Overlay} from '@angular/cdk/overlay'; import {ScrollDispatcher, ViewportRuler} from '@angular/cdk/scrolling'; import {EditEventDispatcher} from './edit-event-dispatcher'; import {FocusDispatcher} from './focus-dispatcher'; import {EditRef} from './edit-ref'; /** * Optimization * Collects multiple Injectables into a singleton shared across the table. By reducing the * number of services injected into each CdkPopoverEdit, this saves about 0.023ms of cpu time * and 56 bytes of memory per instance. */ @Injectable() export class EditServices { readonly directionality = inject(Directionality); readonly editEventDispatcher = inject<EditEventDispatcher<EditRef<unknown>>>(EditEventDispatcher); readonly focusDispatcher = inject(FocusDispatcher); readonly focusTrapFactory = inject(FocusTrapFactory); readonly ngZone = inject(NgZone); readonly overlay = inject(Overlay); readonly scrollDispatcher = inject(ScrollDispatcher); readonly viewportRuler = inject(ViewportRuler); }
{ "commit_id": "ea0d1ba7b", "end_byte": 1369, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/edit-services.ts" }
components/src/cdk-experimental/popover-edit/popover-edit.spec.ts_0_7044
import {BidiModule, Direction} from '@angular/cdk/bidi'; import {DataSource} from '@angular/cdk/collections'; import {DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW, TAB, UP_ARROW} from '@angular/cdk/keycodes'; import {CdkTableModule} from '@angular/cdk/table'; import {dispatchKeyboardEvent} from '@angular/cdk/testing/private'; import { ChangeDetectorRef, Component, Directive, ElementRef, ViewChild, inject, } from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing'; import {FormsModule, NgForm} from '@angular/forms'; import {BehaviorSubject} from 'rxjs'; import { CdkPopoverEditColspan, CdkPopoverEditModule, FormValueContainer, HoverContentState, PopoverEditClickOutBehavior, } from './index'; const NAME_EDIT_TEMPLATE = ` <div style="background-color: white;"> <form #f="ngForm" cdkEditControl (ngSubmit)="onSubmit(element, f)" [(cdkEditControlPreservedFormValue)]="preservedValues.for(element).value" [cdkEditControlIgnoreSubmitUnlessValid]="ignoreSubmitUnlessValid" [cdkEditControlClickOutBehavior]="clickOutBehavior"> <input [ngModel]="element.name" name="name" required> <input [ngModel]="element.weight" name="weight"> <br> <button class="submit" type="submit">Confirm</button> <button class="revert" cdkEditRevert>Revert</button> <button class="close" cdkEditClose>Close</button> </form> </div> `; const WEIGHT_EDIT_TEMPLATE = ` <div> <form #f="ngForm" cdkEditControl> <input> </form> </div> `; const CELL_TEMPLATE = ` {{element.name}} <span *cdkRowHoverContent> <button class="open" cdkEditOpen>Edit</button> </span> `; const POPOVER_EDIT_DIRECTIVE_NAME = ` [cdkPopoverEdit]="nameEdit" [cdkPopoverEditColspan]="colspan" [cdkPopoverEditDisabled]="nameEditDisabled" [cdkPopoverEditAriaLabel]="nameEditAriaLabel" `; const POPOVER_EDIT_DIRECTIVE_WEIGHT = `[cdkPopoverEdit]="weightEdit" cdkPopoverEditTabOut`; interface PeriodicElement { name: string; weight: number; } @Directive() abstract class BaseTestComponent { @ViewChild('table') table: ElementRef; preservedValues = new FormValueContainer<PeriodicElement, {'name': string}>(); nameEditDisabled = false; nameEditAriaLabel: string | undefined = undefined; ignoreSubmitUnlessValid = true; clickOutBehavior: PopoverEditClickOutBehavior = 'close'; colspan: CdkPopoverEditColspan = {}; direction: Direction = 'ltr'; cdr = inject(ChangeDetectorRef); constructor() { this.renderData(); } abstract renderData(): void; onSubmit(element: PeriodicElement, form: NgForm) { if (!form.valid) { return; } element.name = form.value['name']; } triggerHoverState(rowIndex = 0) { const row = getRows(this.table.nativeElement)[rowIndex]; row.dispatchEvent(new Event('mouseover', {bubbles: true})); row.dispatchEvent(new Event('mousemove', {bubbles: true})); // Wait for the mouse hover debounce in edit-event-dispatcher. tick(41); } getRows() { return getRows(this.table.nativeElement); } getEditCell(rowIndex = 0, cellIndex = 1) { const row = this.getRows()[rowIndex]; return getCells(row)[cellIndex]; } focusEditCell(rowIndex = 0, cellIndex = 1) { this.getEditCell(rowIndex, cellIndex).focus(); } hoverContentStateForRow(rowIndex = 0) { const openButton = this.getOpenButton(rowIndex); if (!openButton) { return HoverContentState.OFF; } return parseInt(getComputedStyle(openButton.parentNode as Element).opacity || '', 10) === 0 ? HoverContentState.FOCUSABLE : HoverContentState.ON; } getOpenButton(rowIndex = 0) { return this.getEditCell(rowIndex).querySelector('.open') as HTMLElement | null; } clickOpenButton(rowIndex = 0) { this.getOpenButton(rowIndex)!.click(); } openLens(rowIndex = 0, cellIndex = 1) { this.focusEditCell(rowIndex, cellIndex); this.getEditCell(rowIndex, cellIndex).dispatchEvent( new KeyboardEvent('keydown', {bubbles: true, key: 'Enter'}), ); flush(); } getEditPane() { return document.querySelector('.cdk-edit-pane'); } getEditBoundingBox() { return document.querySelector('.cdk-overlay-connected-position-bounding-box'); } getNameInput() { return document.querySelector('input[name="name"]') as HTMLInputElement | null; } getWeightInput() { return document.querySelector('input[name="weight"]') as HTMLInputElement | null; } lensIsOpen() { return !!this.getNameInput(); } getSubmitButton() { return document.querySelector('.submit') as HTMLElement | null; } clickSubmitButton() { this.getSubmitButton()!.click(); } getRevertButton() { return document.querySelector('.revert') as HTMLElement | null; } clickRevertButton() { this.getRevertButton()!.click(); } getCloseButton() { return document.querySelector('.close') as HTMLElement | null; } clickCloseButton() { this.getCloseButton()!.click(); } } @Component({ template: ` <table #table editable [dir]="direction"> <ng-template #nameEdit let-element> ${NAME_EDIT_TEMPLATE} </ng-template> <ng-template #weightEdit let-element> ${WEIGHT_EDIT_TEMPLATE} </ng-template> @for (element of elements; track element) { <tr> <td> just a cell </td> <td ${POPOVER_EDIT_DIRECTIVE_NAME} [cdkPopoverEditContext]="element"> ${CELL_TEMPLATE} </td> <td ${POPOVER_EDIT_DIRECTIVE_WEIGHT}> {{element.weight}} </td> </tr> } </table> `, standalone: false, }) class VanillaTableOutOfCell extends BaseTestComponent { elements: ChemicalElement[]; renderData() { this.elements = createElementData(); this.cdr.markForCheck(); } } @Component({ template: ` <table #table editable [dir]="direction"> @for (element of elements; track element) { <tr> <td> just a cell </td> <td ${POPOVER_EDIT_DIRECTIVE_NAME}> ${CELL_TEMPLATE} <ng-template #nameEdit> ${NAME_EDIT_TEMPLATE} </ng-template> </td> <td ${POPOVER_EDIT_DIRECTIVE_WEIGHT}> {{element.weight}} <ng-template #weightEdit> ${WEIGHT_EDIT_TEMPLATE} </ng-template> </td> </tr> } </table> `, standalone: false, }) class VanillaTableInCell extends BaseTestComponent { elements: ChemicalElement[]; renderData() { this.elements = createElementData(); this.cdr.markForCheck(); } } class ElementDataSource extends DataSource<PeriodicElement> { /** Stream of data that is provided to the table. */ data = new BehaviorSubject(createElementData()); /** Connect function called by the table to retrieve one stream containing the data to render. */ connect() { return this.data; } disconnect() {} }
{ "commit_id": "ea0d1ba7b", "end_byte": 7044, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/popover-edit.spec.ts" }
components/src/cdk-experimental/popover-edit/popover-edit.spec.ts_7046_10011
@Component({ template: ` <div #table [dir]="direction"> <cdk-table cdk-table editable [dataSource]="dataSource"> <ng-container cdkColumnDef="before"> <cdk-cell *cdkCellDef="let element"> just a cell </cdk-cell> </ng-container> <ng-container cdkColumnDef="name"> <cdk-cell *cdkCellDef="let element" ${POPOVER_EDIT_DIRECTIVE_NAME}> ${CELL_TEMPLATE} <ng-template #nameEdit> ${NAME_EDIT_TEMPLATE} </ng-template> <span *cdkIfRowHovered> <button cdkEditOpen>Edit</button> </span> </cdk-cell> </ng-container> <ng-container cdkColumnDef="weight"> <cdk-cell *cdkCellDef="let element" ${POPOVER_EDIT_DIRECTIVE_WEIGHT}> {{element.weight}} <ng-template #weightEdit> ${WEIGHT_EDIT_TEMPLATE} </ng-template> </cdk-cell> </ng-container> <cdk-row *cdkRowDef="let row; columns: displayedColumns;"></cdk-row> </cdk-table> </div> `, standalone: false, }) class CdkFlexTableInCell extends BaseTestComponent { displayedColumns = ['before', 'name', 'weight']; dataSource: ElementDataSource; renderData() { this.dataSource = new ElementDataSource(); this.cdr.markForCheck(); } } @Component({ template: ` <div #table [dir]="direction"> <table cdk-table editable [dataSource]="dataSource"> <ng-container cdkColumnDef="before"> <td cdk-cell *cdkCellDef="let element"> just a cell </td> </ng-container> <ng-container cdkColumnDef="name"> <td cdk-cell *cdkCellDef="let element" ${POPOVER_EDIT_DIRECTIVE_NAME}> ${CELL_TEMPLATE} <ng-template #nameEdit> ${NAME_EDIT_TEMPLATE} </ng-template> <span *cdkIfRowHovered> <button cdkEditOpen>Edit</button> </span> </td> </ng-container> <ng-container cdkColumnDef="weight"> <td cdk-cell *cdkCellDef="let element" ${POPOVER_EDIT_DIRECTIVE_WEIGHT}> {{element.weight}} <ng-template #weightEdit> ${WEIGHT_EDIT_TEMPLATE} </ng-template> </td> </ng-container> <tr cdk-row *cdkRowDef="let row; columns: displayedColumns;"></tr> </table> <div> `, standalone: false, }) class CdkTableInCell extends BaseTestComponent { displayedColumns = ['before', 'name', 'weight']; dataSource: ElementDataSource; renderData() { this.dataSource = new ElementDataSource(); this.cdr.markForCheck(); } } const testCases = [ [VanillaTableOutOfCell, 'Vanilla HTML table; edit defined outside of cell'], [VanillaTableInCell, 'Vanilla HTML table; edit defined within cell'], [CdkFlexTableInCell, 'Flex cdk-table; edit defined within cell'], [CdkTableInCell, 'Table cdk-table; edit defined within cell'], ] as const;
{ "commit_id": "ea0d1ba7b", "end_byte": 10011, "start_byte": 7046, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/popover-edit.spec.ts" }
components/src/cdk-experimental/popover-edit/popover-edit.spec.ts_10013_17824
describe('CDK Popover Edit', () => { for (const [componentClass, label] of testCases) { describe(label, () => { let component: BaseTestComponent; let fixture: ComponentFixture<BaseTestComponent>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [CdkTableModule, CdkPopoverEditModule, FormsModule, BidiModule], declarations: [componentClass], }); fixture = TestBed.createComponent<BaseTestComponent>(componentClass); component = fixture.componentInstance; fixture.detectChanges(); tick(10); fixture.detectChanges(); })); describe('row hover content', () => { it('makes the first and last rows focusable but invisible', fakeAsync(() => { const rows = component.getRows(); expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.FOCUSABLE); expect(component.hoverContentStateForRow(rows.length - 1)).toBe( HoverContentState.FOCUSABLE, ); })); it('shows and hides on-hover content only after a delay', fakeAsync(() => { const [row0, row1] = component.getRows(); row0.dispatchEvent(new Event('mouseover', {bubbles: true})); row0.dispatchEvent(new Event('mousemove', {bubbles: true})); expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.FOCUSABLE); tick(20); row0.dispatchEvent(new Event('mousemove', {bubbles: true})); tick(20); expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.FOCUSABLE); tick(31); expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.ON); row1.dispatchEvent(new Event('mouseover', {bubbles: true})); row1.dispatchEvent(new Event('mousemove', {bubbles: true})); expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.ON); expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.OFF); tick(41); expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.FOCUSABLE); expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.ON); })); it('shows the hover content if the data changes after initialization', fakeAsync(() => { fixture.componentInstance.renderData(); fixture.detectChanges(); const row = component.getRows()[0]; row.dispatchEvent(new Event('mouseover', {bubbles: true})); row.dispatchEvent(new Event('mousemove', {bubbles: true})); tick(20); row.dispatchEvent(new Event('mousemove', {bubbles: true})); tick(50); expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.ON); })); it('shows hover content for the focused row and makes the rows above and below focusable', fakeAsync(() => { expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.FOCUSABLE); component.focusEditCell(2); tick(1); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.ON); expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.FOCUSABLE); expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.FOCUSABLE); component.focusEditCell(4); tick(1); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.ON); expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.FOCUSABLE); component.getEditCell(4).blur(); tick(1); expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.FOCUSABLE); })); it('should close the focus content when pressing escape', fakeAsync(() => { expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF); component.focusEditCell(2); tick(1); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.ON); const event = new KeyboardEvent('keydown', {bubbles: true, key: 'Escape'}); component.getEditCell(2).dispatchEvent(event); tick(1); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF); })); it( 'shows hover content for the editing row and makes the rows above and below ' + 'focusable unless focus is in a different table row in which case it takes priority', fakeAsync(() => { expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.FOCUSABLE); component.openLens(2); tick(1); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.ON); expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.FOCUSABLE); expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.FOCUSABLE); component.focusEditCell(4); tick(1); expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF); expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.ON); expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.FOCUSABLE); }), ); }); describe('triggering edit', () => { it('opens edit from on-hover button', fakeAsync(() => { component.triggerHoverState(); component.clickOpenButton(); expect(component.lensIsOpen()).toBe(true); clearLeftoverTimers(); })); it('opens edit from Enter on focued cell', fakeAsync(() => { // Uses Enter to open the lens. component.openLens(); fixture.detectChanges(); expect(component.lensIsOpen()).toBe(true); clearLeftoverTimers(); })); it('does not trigger edit when disabled', fakeAsync(() => { component.nameEditDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); // Uses Enter to open the lens. component.openLens(); fixture.detectChanges(); expect(component.lensIsOpen()).toBe(false); clearLeftoverTimers(); })); it('sets aria label and role dialog on the popup', fakeAsync(() => { component.nameEditAriaLabel = 'Label of name!!'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); // Uses Enter to open the lens. component.openLens(); fixture.detectChanges(); expect(component.lensIsOpen()).toBe(true); const dialogElem = component.getEditPane()!; expect(dialogElem.getAttribute('aria-label')).toBe('Label of name!!'); expect(dialogElem.getAttribute('role')).toBe('dialog'); clearLeftoverTimers(); })); });
{ "commit_id": "ea0d1ba7b", "end_byte": 17824, "start_byte": 10013, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/popover-edit.spec.ts" }
components/src/cdk-experimental/popover-edit/popover-edit.spec.ts_17832_23281
describe('focus manipulation', () => { const getRowCells = () => component.getRows().map(getCells); describe('tabindex', () => { it('sets tabindex to 0 on editable cells', () => { expect(component.getEditCell().getAttribute('tabindex')).toBe('0'); }); it('unsets tabindex to 0 on disabled cells', () => { component.nameEditDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(component.getEditCell().hasAttribute('tabindex')).toBe(false); }); }); describe('arrow keys', () => { const dispatchKey = (cell: HTMLElement, keyCode: number) => dispatchKeyboardEvent(cell, 'keydown', keyCode); it('moves focus up/down/left/right and prevents default', () => { const rowCells = getRowCells(); // Focus the upper-left editable cell. rowCells[0][1].focus(); const downEvent = dispatchKey(rowCells[0][1], DOWN_ARROW); expect(document.activeElement).toBe(rowCells[1][1]); expect(downEvent.defaultPrevented).toBe(true); const rightEvent = dispatchKey(rowCells[1][1], RIGHT_ARROW); expect(document.activeElement).toBe(rowCells[1][2]); expect(rightEvent.defaultPrevented).toBe(true); const upEvent = dispatchKey(rowCells[1][2], UP_ARROW); expect(document.activeElement).toBe(rowCells[0][2]); expect(upEvent.defaultPrevented).toBe(true); const leftEvent = dispatchKey(rowCells[0][2], LEFT_ARROW); expect(document.activeElement).toBe(rowCells[0][1]); expect(leftEvent.defaultPrevented).toBe(true); }); it('wraps around when reaching start or end of a row, skipping non-editable cells', () => { const rowCells = getRowCells(); // Focus the upper-right editable cell. rowCells[0][2].focus(); dispatchKey(rowCells[0][2], RIGHT_ARROW); expect(document.activeElement).toBe(rowCells[1][1]); dispatchKey(rowCells[1][1], LEFT_ARROW); expect(document.activeElement).toBe(rowCells[0][2]); }); it('does not fall off top or bottom of the table', () => { const rowCells = getRowCells(); // Focus the upper-left editable cell. rowCells[0][1].focus(); dispatchKey(rowCells[0][1], UP_ARROW); expect(document.activeElement).toBe(rowCells[0][1]); // Focus the bottom-left editable cell. rowCells[4][1].focus(); dispatchKey(rowCells[4][1], DOWN_ARROW); expect(document.activeElement).toBe(rowCells[4][1]); }); it('ignores non arrow key events', () => { component.focusEditCell(); const cell = component.getEditCell(); expect(dispatchKey(cell, TAB).defaultPrevented).toBe(false); }); }); describe('lens focus trapping behavior', () => { const getFocusablePaneElements = () => Array.from( component .getEditBoundingBox()! .querySelectorAll('input, button, .cdk-focus-trap-anchor'), ) as HTMLElement[]; it('keeps focus within the lens by default', fakeAsync(() => { // Open the name lens which has the default behavior. component.openLens(); fixture.detectChanges(); const focusableElements = getFocusablePaneElements(); // Focus the last element (end focus trap anchor). focusableElements[focusableElements.length - 1].focus(); flush(); // Focus should have moved to the top of the lens. expect(document.activeElement).toBe(focusableElements[1]); expect(component.lensIsOpen()).toBe(true); clearLeftoverTimers(); })); it('moves focus to the next cell when focus leaves end of lens with cdkPopoverEditTabOut', fakeAsync(() => { // Open the weight lens which has tab out behavior. component.openLens(0, 2); const focusableElements = getFocusablePaneElements(); // Focus the last element (end focus trap anchor). focusableElements[focusableElements.length - 1].focus(); flush(); // Focus should have moved to the next editable cell. expect(document.activeElement).toBe(component.getEditCell(1, 1)); expect(component.lensIsOpen()).toBe(false); clearLeftoverTimers(); })); it(`moves focus to the previous cell when focus leaves end of lens with cdkPopoverEditTabOut`, fakeAsync(() => { // Open the weight lens which has tab out behavior. component.openLens(0, 2); const focusableElements = getFocusablePaneElements(); // Focus the first (start focus trap anchor). focusableElements[0].focus(); flush(); // Focus should have moved to the next editable cell. expect(document.activeElement).toBe(component.getEditCell(0, 1)); expect(component.lensIsOpen()).toBe(false); clearLeftoverTimers(); })); }); }); describe('edit lens', () =>
{ "commit_id": "ea0d1ba7b", "end_byte": 23281, "start_byte": 17832, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/popover-edit.spec.ts" }
components/src/cdk-experimental/popover-edit/popover-edit.spec.ts_23282_33370
{ function expectPixelsToEqual(actual: number, expected: number) { expect(Math.floor(actual)).toBe(Math.floor(expected)); } it('shows a lens with the value from the table', fakeAsync(() => { component.openLens(); fixture.detectChanges(); expect(component.getNameInput()!.value).toBe('Hydrogen'); clearLeftoverTimers(); })); it('positions the lens at the top left corner and spans the full width of the cell', fakeAsync(() => { component.openLens(); fixture.detectChanges(); const paneRect = component.getEditPane()!.getBoundingClientRect(); const cellRect = component.getEditCell().getBoundingClientRect(); expectPixelsToEqual(paneRect.width, cellRect.width); expectPixelsToEqual(paneRect.left, cellRect.left); expectPixelsToEqual(paneRect.top, cellRect.top); clearLeftoverTimers(); })); it('adjusts the positioning of the lens based on colspan', fakeAsync(() => { const cellRects = getCells(getRows(component.table.nativeElement)[0]).map(cell => cell.getBoundingClientRect(), ); component.colspan = {before: 1}; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); component.openLens(); fixture.detectChanges(); let paneRect = component.getEditPane()!.getBoundingClientRect(); expectPixelsToEqual(paneRect.top, cellRects[0].top); expectPixelsToEqual(paneRect.left, cellRects[0].left); expectPixelsToEqual(paneRect.right, cellRects[1].right); component.colspan = {after: 1}; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); paneRect = component.getEditPane()!.getBoundingClientRect(); expectPixelsToEqual(paneRect.top, cellRects[1].top); expectPixelsToEqual(paneRect.left, cellRects[1].left); expectPixelsToEqual(paneRect.right, cellRects[2].right); component.colspan = {before: 1, after: 1}; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); paneRect = component.getEditPane()!.getBoundingClientRect(); expectPixelsToEqual(paneRect.top, cellRects[0].top); expectPixelsToEqual(paneRect.left, cellRects[0].left); expectPixelsToEqual(paneRect.right, cellRects[2].right); clearLeftoverTimers(); })); it('updates the form and submits, closing the lens', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = 'Hydragon'; component.getNameInput()!.dispatchEvent(new Event('input')); component.clickSubmitButton(); fixture.detectChanges(); expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydragon'); expect(component.lensIsOpen()).toBe(false); clearLeftoverTimers(); })); it('does not close the lens on submit when form is invalid', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = ''; component.getNameInput()!.dispatchEvent(new Event('input')); component.clickSubmitButton(); expect(component.lensIsOpen()).toBe(true); clearLeftoverTimers(); })); it( 'closes lens on submit when form is invalid with ' + 'cdkEditControlIgnoreSubmitUnlessValid = false', fakeAsync(() => { component.ignoreSubmitUnlessValid = false; component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = ''; component.getNameInput()!.dispatchEvent(new Event('input')); component.clickSubmitButton(); expect(component.lensIsOpen()).toBe(false); clearLeftoverTimers(); }), ); it('closes the lens on close', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.clickCloseButton(); expect(component.lensIsOpen()).toBe(false); clearLeftoverTimers(); })); it('closes and reopens a lens with modified value persisted', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = 'Hydragon'; component.getNameInput()!.dispatchEvent(new Event('input')); component.clickCloseButton(); fixture.detectChanges(); expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydrogen'); expect(component.lensIsOpen()).toBe(false); component.openLens(); fixture.detectChanges(); expect(component.getNameInput()!.value).toBe('Hydragon'); clearLeftoverTimers(); })); it('resets the lens to original value', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = 'Hydragon'; component.getNameInput()!.dispatchEvent(new Event('input')); component.clickRevertButton(); expect(component.getNameInput()!.value).toBe('Hydrogen'); clearLeftoverTimers(); })); it('should not reset the values when clicking revert without making changes', fakeAsync(() => { component.openLens(); fixture.detectChanges(); expect(component.getNameInput()!.value).toBe('Hydrogen'); expect(component.getWeightInput()!.value).toBe('1.007'); component.clickRevertButton(); expect(component.getNameInput()!.value).toBe('Hydrogen'); expect(component.getWeightInput()!.value).toBe('1.007'); clearLeftoverTimers(); })); it('resets the lens to previously submitted value', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = 'Hydragon'; component.getNameInput()!.dispatchEvent(new Event('input')); component.clickSubmitButton(); fixture.detectChanges(); component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = 'Hydragon X'; component.getNameInput()!.dispatchEvent(new Event('input')); component.clickRevertButton(); expect(component.getNameInput()!.value).toBe('Hydragon'); clearLeftoverTimers(); })); it('closes the lens on escape', fakeAsync(() => { component.openLens(); fixture.detectChanges(); const event = new KeyboardEvent('keydown', {bubbles: true, key: 'Escape'}); spyOn(event, 'preventDefault').and.callThrough(); component.getNameInput()!.dispatchEvent(event); expect(component.lensIsOpen()).toBe(false); expect(event.preventDefault).toHaveBeenCalled(); clearLeftoverTimers(); })); it('does not close the lens on escape with a modifier key', fakeAsync(() => { component.openLens(); fixture.detectChanges(); const event = new KeyboardEvent('keydown', {bubbles: true, key: 'Escape'}); Object.defineProperty(event, 'altKey', {get: () => true}); spyOn(event, 'preventDefault').and.callThrough(); component.getNameInput()!.dispatchEvent(event); expect(component.lensIsOpen()).toBe(true); expect(event.preventDefault).not.toHaveBeenCalled(); clearLeftoverTimers(); })); it('does not close the lens on click within lens', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.getNameInput()!.dispatchEvent(new Event('click', {bubbles: true})); expect(component.lensIsOpen()).toBe(true); clearLeftoverTimers(); })); it('closes the lens on outside click', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = 'Hydragon'; component.getNameInput()!.dispatchEvent(new Event('input')); document.body.dispatchEvent(new Event('click', {bubbles: true})); fixture.detectChanges(); expect(component.lensIsOpen()).toBe(false); expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydrogen'); clearLeftoverTimers(); })); it( 'submits the lens on outside click with ' + 'cdkEditControlClickOutBehavior = "submit"', fakeAsync(() => { component.clickOutBehavior = 'submit'; component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = 'Hydragon'; component.getNameInput()!.dispatchEvent(new Event('input')); document.body.dispatchEvent(new Event('click', {bubbles: true})); fixture.detectChanges(); expect(component.lensIsOpen()).toBe(false); expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydragon'); clearLeftoverTimers(); }), ); it( 'does nothing on outside click with ' + 'cdkEditControlClickOutBehavior = "noop"', fakeAsync(() => { component.clickOutBehavior = 'noop'; component.openLens(); fixture.detectChanges(); component.getNameInput()!.value = 'Hydragon'; component.getNameInput()!.dispatchEvent(new Event('input')); document.body.dispatchEvent(new Event('click', {bubbles: true})); fixture.detectChanges(); expect(component.lensIsOpen()).toBe(true); expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydrogen'); clearLeftoverTimers(); }), );
{ "commit_id": "ea0d1ba7b", "end_byte": 33370, "start_byte": 23282, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/popover-edit.spec.ts" }
components/src/cdk-experimental/popover-edit/popover-edit.spec.ts_33380_35793
it('sets focus on the first input in the lens', fakeAsync(() => { component.openLens(); fixture.detectChanges(); expect(document.activeElement).toBe(component.getNameInput()); clearLeftoverTimers(); })); it('returns focus to the edited cell after closing', fakeAsync(() => { component.openLens(); fixture.detectChanges(); component.clickCloseButton(); expect(document.activeElement).toBe(component.getEditCell()); clearLeftoverTimers(); })); it( 'does not focus to the edited cell after closing if another element ' + 'outside the lens is already focused', fakeAsync(() => { component.openLens(0); component.getEditCell(1).focus(); component.getEditCell(1).dispatchEvent(new Event('click', {bubbles: true})); expect(document.activeElement).toBe(component.getEditCell(1)); clearLeftoverTimers(); }), ); it('should pass the directionality to the overlay', fakeAsync(() => { component.direction = 'rtl'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); component.openLens(); fixture.detectChanges(); expect(component.getEditBoundingBox()!.getAttribute('dir')).toBe('rtl'); clearLeftoverTimers(); })); }); }); } }); interface ChemicalElement { name: string; weight: number; } function createElementData(): ChemicalElement[] { return [ {name: 'Hydrogen', weight: 1.007}, {name: 'Helium', weight: 4.0026}, {name: 'Lithium', weight: 6.941}, {name: 'Beryllium', weight: 9.0122}, {name: 'Boron', weight: 10.81}, ]; } function getElements(element: Element, query: string): HTMLElement[] { return [].slice.call(element.querySelectorAll(query)); } function getRows(tableElement: Element): HTMLElement[] { return getElements(tableElement, '.cdk-row, tr'); } function getCells(row: Element): HTMLElement[] { if (!row) { return []; } return getElements(row, '.cdk-cell, td'); } // Common actions like mouse events and focus/blur cause timers to be fired off. // When not testing this behavior directly, use this function to clear any timers that were // created in passing. function clearLeftoverTimers() { tick(100); }
{ "commit_id": "ea0d1ba7b", "end_byte": 35793, "start_byte": 33380, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/popover-edit/popover-edit.spec.ts" }
components/src/cdk-experimental/selection/selection-set.ts_0_3855
/** * @license * Copyright Google LLC 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.dev/license */ import {TrackByFunction} from '@angular/core'; import {Subject} from 'rxjs'; /** * Maintains a set of selected values. One or more values can be added to or removed from the * selection. */ interface TrackBySelection<T> { isSelected(value: SelectableWithIndex<T>): boolean; select(...values: SelectableWithIndex<T>[]): void; deselect(...values: SelectableWithIndex<T>[]): void; changed: Subject<SelectionChange<T>>; } /** * A selectable value with an optional index. The index is required when the selection is used with * `trackBy`. */ export interface SelectableWithIndex<T> { value: T; index?: number; } /** * Represents the change in the selection set. */ export interface SelectionChange<T> { before: SelectableWithIndex<T>[]; after: SelectableWithIndex<T>[]; } /** * Maintains a set of selected items. Support selecting and deselecting items, and checking if a * value is selected. * When constructed with a `trackByFn`, all the items will be identified by applying the `trackByFn` * on them. Because `trackByFn` requires the index of the item to be passed in, the `index` field is * expected to be set when calling `isSelected`, `select` and `deselect`. */ export class SelectionSet<T> implements TrackBySelection<T> { private _selectionMap = new Map<T | ReturnType<TrackByFunction<T>>, SelectableWithIndex<T>>(); changed = new Subject<SelectionChange<T>>(); constructor( private _multiple = false, private _trackByFn?: TrackByFunction<T>, ) {} isSelected(value: SelectableWithIndex<T>): boolean { return this._selectionMap.has(this._getTrackedByValue(value)); } select(...selects: SelectableWithIndex<T>[]) { if (!this._multiple && selects.length > 1 && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('SelectionSet: not multiple selection'); } const before = this._getCurrentSelection(); if (!this._multiple) { this._selectionMap.clear(); } const toSelect: SelectableWithIndex<T>[] = []; for (const select of selects) { if (this.isSelected(select)) { continue; } toSelect.push(select); this._markSelected(this._getTrackedByValue(select), select); } const after = this._getCurrentSelection(); this.changed.next({before, after}); } deselect(...selects: SelectableWithIndex<T>[]) { if (!this._multiple && selects.length > 1 && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('SelectionSet: not multiple selection'); } const before = this._getCurrentSelection(); const toDeselect: SelectableWithIndex<T>[] = []; for (const select of selects) { if (!this.isSelected(select)) { continue; } toDeselect.push(select); this._markDeselected(this._getTrackedByValue(select)); } const after = this._getCurrentSelection(); this.changed.next({before, after}); } private _markSelected(key: T | ReturnType<TrackByFunction<T>>, toSelect: SelectableWithIndex<T>) { this._selectionMap.set(key, toSelect); } private _markDeselected(key: T | ReturnType<TrackByFunction<T>>) { this._selectionMap.delete(key); } private _getTrackedByValue(select: SelectableWithIndex<T>) { if (!this._trackByFn) { return select.value; } if (select.index == null && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('SelectionSet: index required when trackByFn is used.'); } return this._trackByFn(select.index!, select.value); } private _getCurrentSelection(): SelectableWithIndex<T>[] { return Array.from(this._selectionMap.values()); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3855, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/selection-set.ts" }
components/src/cdk-experimental/selection/selection.ts_0_6472
/** * @license * Copyright Google LLC 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.dev/license */ import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {CollectionViewer, DataSource, isDataSource, ListRange} from '@angular/cdk/collections'; import { AfterContentChecked, Directive, EventEmitter, Input, OnDestroy, OnInit, Output, TrackByFunction, } from '@angular/core'; import {Observable, of as observableOf, Subject, Subscription} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {SelectableWithIndex, SelectionChange, SelectionSet} from './selection-set'; /** * Manages the selection states of the items and provides methods to check and update the selection * states. * It must be applied to the parent element if `cdkSelectionToggle`, `cdkSelectAll`, * `cdkRowSelection` and `cdkSelectionColumn` are applied. */ @Directive({ selector: '[cdkSelection]', exportAs: 'cdkSelection', }) export class CdkSelection<T> implements OnInit, AfterContentChecked, CollectionViewer, OnDestroy { viewChange: Observable<ListRange>; @Input() get dataSource(): TableDataSource<T> { return this._dataSource; } set dataSource(dataSource: TableDataSource<T>) { if (this._dataSource !== dataSource) { this._switchDataSource(dataSource); } } private _dataSource: TableDataSource<T>; @Input('trackBy') trackByFn: TrackByFunction<T>; /** Whether to support multiple selection */ @Input('cdkSelectionMultiple') get multiple(): boolean { return this._multiple; } set multiple(multiple: BooleanInput) { this._multiple = coerceBooleanProperty(multiple); } protected _multiple: boolean; /** Emits when selection changes. */ @Output('cdkSelectionChange') readonly change = new EventEmitter<SelectionChange<T>>(); /** Latest data provided by the data source. */ private _data: T[] | readonly T[]; /** Subscription that listens for the data provided by the data source. */ private _renderChangeSubscription: Subscription | null; private _destroyed = new Subject<void>(); private _selection: SelectionSet<T>; private _switchDataSource(dataSource: TableDataSource<T>) { this._data = []; // TODO: Move this logic to a shared function in `cdk/collections`. if (isDataSource(this._dataSource)) { this._dataSource.disconnect(this); } if (this._renderChangeSubscription) { this._renderChangeSubscription.unsubscribe(); this._renderChangeSubscription = null; } this._dataSource = dataSource; } private _observeRenderChanges() { if (!this._dataSource) { return; } let dataStream: Observable<readonly T[]> | undefined; if (isDataSource(this._dataSource)) { dataStream = this._dataSource.connect(this); } else if (this._dataSource instanceof Observable) { dataStream = this._dataSource; } else if (Array.isArray(this._dataSource)) { dataStream = observableOf(this._dataSource); } if (dataStream == null && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('Unknown data source'); } this._renderChangeSubscription = dataStream! .pipe(takeUntil(this._destroyed)) .subscribe(data => { this._data = data || []; }); } ngOnInit() { this._selection = new SelectionSet<T>(this._multiple, this.trackByFn); this._selection.changed.pipe(takeUntil(this._destroyed)).subscribe(change => { this._updateSelectAllState(); this.change.emit(change); }); } ngAfterContentChecked() { if (this._dataSource && !this._renderChangeSubscription) { this._observeRenderChanges(); } } ngOnDestroy() { this._destroyed.next(); this._destroyed.complete(); if (isDataSource(this._dataSource)) { this._dataSource.disconnect(this); } } /** Toggles selection for a given value. `index` is required if `trackBy` is used. */ toggleSelection(value: T, index?: number) { if (!!this.trackByFn && index == null && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('CdkSelection: index required when trackBy is used'); } if (this.isSelected(value, index)) { this._selection.deselect({value, index}); } else { this._selection.select({value, index}); } } /** * Toggles select-all. If no value is selected, select all values. If all values or some of the * values are selected, de-select all values. */ toggleSelectAll() { if (!this._multiple && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('CdkSelection: multiple selection not enabled'); } if (this.selectAllState === 'none') { this._selectAll(); } else { this._clearAll(); } } /** Checks whether a value is selected. `index` is required if `trackBy` is used. */ isSelected(value: T, index?: number) { if (!!this.trackByFn && index == null && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('CdkSelection: index required when trackBy is used'); } return this._selection.isSelected({value, index}); } /** Checks whether all values are selected. */ isAllSelected() { return this._data.every((value, index) => this._selection.isSelected({value, index})); } /** Checks whether partially selected. */ isPartialSelected() { return ( !this.isAllSelected() && this._data.some((value, index) => this._selection.isSelected({value, index})) ); } private _selectAll() { const toSelect: SelectableWithIndex<T>[] = []; this._data.forEach((value, index) => { toSelect.push({value, index}); }); this._selection.select(...toSelect); } private _clearAll() { const toDeselect: SelectableWithIndex<T>[] = []; this._data.forEach((value, index) => { toDeselect.push({value, index}); }); this._selection.deselect(...toDeselect); } private _updateSelectAllState() { if (this.isAllSelected()) { this.selectAllState = 'all'; } else if (this.isPartialSelected()) { this.selectAllState = 'partial'; } else { this.selectAllState = 'none'; } } selectAllState: SelectAllState = 'none'; } type SelectAllState = 'all' | 'none' | 'partial'; type TableDataSource<T> = DataSource<T> | Observable<readonly T[]> | readonly T[];
{ "commit_id": "ea0d1ba7b", "end_byte": 6472, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/selection.ts" }
components/src/cdk-experimental/selection/public-api.ts_0_437
/** * @license * Copyright Google LLC 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.dev/license */ export * from './selection'; export * from './select-all'; export * from './selection-toggle'; export * from './selection-column'; export * from './row-selection'; export * from './selection-set'; export * from './selection-module';
{ "commit_id": "ea0d1ba7b", "end_byte": 437, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/public-api.ts" }
components/src/cdk-experimental/selection/selection-toggle.ts_0_3196
/** * @license * Copyright Google LLC 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.dev/license */ import {coerceNumberProperty, NumberInput} from '@angular/cdk/coercion'; import {Directive, Input, OnDestroy, OnInit, inject} from '@angular/core'; import {NG_VALUE_ACCESSOR} from '@angular/forms'; import {Observable, of as observableOf, Subject} from 'rxjs'; import {distinctUntilChanged, switchMap, takeUntil} from 'rxjs/operators'; import {CdkSelection} from './selection'; /** * Makes the element a selection toggle. * * Must be used within a parent `CdkSelection` directive. * Must be provided with the value. If `trackBy` is used on `CdkSelection`, the index of the value * is required. If the element implements `ControlValueAccessor`, e.g. `MatCheckbox`, the directive * automatically connects it with the selection state provided by the `CdkSelection` directive. If * not, use `checked$` to get the checked state of the value, and `toggle()` to change the selection * state. */ @Directive({ selector: '[cdkSelectionToggle]', exportAs: 'cdkSelectionToggle', }) export class CdkSelectionToggle<T> implements OnDestroy, OnInit { private _selection = inject<CdkSelection<T>>(CdkSelection, {optional: true})!; private _controlValueAccessors = inject(NG_VALUE_ACCESSOR, {optional: true, self: true}); /** The value that is associated with the toggle */ @Input('cdkSelectionToggleValue') value: T; /** The index of the value in the list. Required when used with `trackBy` */ @Input('cdkSelectionToggleIndex') get index(): number | undefined { return this._index; } set index(index: NumberInput) { this._index = coerceNumberProperty(index); } protected _index?: number; /** The checked state of the selection toggle */ readonly checked: Observable<boolean>; /** Toggles the selection */ toggle() { this._selection.toggleSelection(this.value, this.index); } private _destroyed = new Subject<void>(); constructor() { const _selection = this._selection; this.checked = _selection.change.pipe( switchMap(() => observableOf(this._isSelected())), distinctUntilChanged(), ); } ngOnInit() { this._assertValidParentSelection(); this._configureControlValueAccessor(); } ngOnDestroy() { this._destroyed.next(); this._destroyed.complete(); } private _assertValidParentSelection() { if (!this._selection && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('CdkSelectAll: missing CdkSelection in the parent'); } } private _configureControlValueAccessor() { if (this._controlValueAccessors && this._controlValueAccessors.length) { this._controlValueAccessors[0].registerOnChange((e: unknown) => { if (typeof e === 'boolean') { this.toggle(); } }); this.checked.pipe(takeUntil(this._destroyed)).subscribe(state => { this._controlValueAccessors![0].writeValue(state); }); } } private _isSelected(): boolean { return this._selection.isSelected(this.value, this.index); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3196, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/selection-toggle.ts" }
components/src/cdk-experimental/selection/row-selection.ts_0_1268
/** * @license * Copyright Google LLC 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.dev/license */ import {coerceNumberProperty, NumberInput} from '@angular/cdk/coercion'; import {Directive, Input, inject} from '@angular/core'; import {CdkSelection} from './selection'; /** * Applies `cdk-selected` class and `aria-selected` to an element. * * Must be used within a parent `CdkSelection` directive. * Must be provided with the value. The index is required if `trackBy` is used on the `CdkSelection` * directive. */ @Directive({ selector: '[cdkRowSelection]', host: { '[class.cdk-selected]': '_selection.isSelected(this.value, this.index)', '[attr.aria-selected]': '_selection.isSelected(this.value, this.index)', }, }) export class CdkRowSelection<T> { readonly _selection = inject<CdkSelection<T>>(CdkSelection); // We need an initializer here to avoid a TS error. @Input('cdkRowSelectionValue') value: T = undefined!; @Input('cdkRowSelectionIndex') get index(): number | undefined { return this._index; } set index(index: NumberInput) { this._index = coerceNumberProperty(index); } protected _index?: number; }
{ "commit_id": "ea0d1ba7b", "end_byte": 1268, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/row-selection.ts" }
components/src/cdk-experimental/selection/selection-column.ts_0_3351
/** * @license * Copyright Google LLC 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.dev/license */ import {CdkCellDef, CdkColumnDef, CdkHeaderCellDef, CdkTable} from '@angular/cdk/table'; import { Component, Input, OnDestroy, OnInit, ViewChild, ChangeDetectionStrategy, ViewEncapsulation, inject, } from '@angular/core'; import {CdkSelection} from './selection'; import {AsyncPipe} from '@angular/common'; import {CdkSelectionToggle} from './selection-toggle'; import {CdkSelectAll} from './select-all'; /** * Column that adds row selecting checkboxes and a select-all checkbox if `cdkSelectionMultiple` is * `true`. * * Must be used within a parent `CdkSelection` directive. */ @Component({ selector: 'cdk-selection-column', template: ` <ng-container cdkColumnDef> <th cdkHeaderCell *cdkHeaderCellDef> @if (selection && selection.multiple) { <input type="checkbox" cdkSelectAll #allToggler="cdkSelectAll" [checked]="allToggler.checked | async" [indeterminate]="allToggler.indeterminate | async" (click)="allToggler.toggle($event)"> } </th> <td cdkCell *cdkCellDef="let row; let i = $index"> <input type="checkbox" #toggler="cdkSelectionToggle" cdkSelectionToggle [cdkSelectionToggleValue]="row" [cdkSelectionToggleIndex]="i" (click)="toggler.toggle()" [checked]="toggler.checked | async"> </td> </ng-container> `, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, imports: [ CdkColumnDef, CdkHeaderCellDef, CdkSelectAll, CdkCellDef, CdkSelectionToggle, AsyncPipe, ], }) export class CdkSelectionColumn<T> implements OnInit, OnDestroy { private _table = inject<CdkTable<T>>(CdkTable, {optional: true}); readonly selection = inject<CdkSelection<T>>(CdkSelection, {optional: true}); /** Column name that should be used to reference this column. */ @Input('cdkSelectionColumnName') get name(): string { return this._name; } set name(name: string) { this._name = name; this._syncColumnDefName(); } private _name: string; @ViewChild(CdkColumnDef, {static: true}) private readonly _columnDef: CdkColumnDef; @ViewChild(CdkCellDef, {static: true}) private readonly _cell: CdkCellDef; @ViewChild(CdkHeaderCellDef, {static: true}) private readonly _headerCell: CdkHeaderCellDef; ngOnInit() { if (!this.selection && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('CdkSelectionColumn: missing CdkSelection in the parent'); } this._syncColumnDefName(); if (this._table) { this._columnDef.cell = this._cell; this._columnDef.headerCell = this._headerCell; this._table.addColumnDef(this._columnDef); } else if (typeof ngDevMode === 'undefined' || ngDevMode) { throw Error('CdkSelectionColumn: missing parent table'); } } ngOnDestroy() { if (this._table) { this._table.removeColumnDef(this._columnDef); } } private _syncColumnDefName() { if (this._columnDef) { this._columnDef.name = this._name; } } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3351, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/selection-column.ts" }
components/src/cdk-experimental/selection/selection.spec.ts_0_9312
import {AsyncPipe} from '@angular/common'; import {CdkTableModule} from '@angular/cdk/table'; import {ChangeDetectorRef, Component, ElementRef, ViewChild, inject} from '@angular/core'; import {waitForAsync, ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing'; import {CdkSelection} from './selection'; import {CdkSelectionModule} from './selection-module'; import {SelectionChange} from './selection-set'; describe('CdkSelection', () => { let fixture: ComponentFixture<ListWithMultiSelection>; let component: ListWithMultiSelection; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [CdkSelectionModule, ListWithMultiSelection], }); })); beforeEach(() => { fixture = TestBed.createComponent(ListWithMultiSelection); component = fixture.componentInstance; fixture.detectChanges(); }); describe('cdkSelection', () => { it('should allow toggling selection', () => { expect(component.cdkSelection.isSelected('apple', 0)).toBeFalsy(); component.cdkSelection.toggleSelection('apple', 0); expect(component.cdkSelection.isSelected('apple', 0)).toBeTruthy(); }); it('should allow selecting all', () => { expect(component.cdkSelection.isAllSelected()).toBeFalsy(); component.cdkSelection.toggleSelectAll(); expect(component.cdkSelection.isAllSelected()).toBeTruthy(); }); it('should detect partial selection', () => { expect(component.cdkSelection.isPartialSelected()).toBeFalsy(); component.cdkSelection.toggleSelectAll(); expect(component.cdkSelection.isPartialSelected()).toBeFalsy(); component.cdkSelection.toggleSelectAll(); component.cdkSelection.toggleSelection('apple', 0); expect(component.cdkSelection.isPartialSelected()).toBeTruthy(); }); it('should clear selection when partial selected and toggling select-all', () => { component.cdkSelection.toggleSelection('apple', 0); component.cdkSelection.toggleSelectAll(); expect(component.cdkSelection.isPartialSelected()).toBeFalsy(); expect(component.cdkSelection.isAllSelected()).toBeFalsy(); }); }); describe('cdkSelectAll', () => { it('should select all items when not all selected', fakeAsync(() => { expect(component.cdkSelection.isAllSelected()).toBeFalsy(); expect(component.getSelectAll().textContent.trim()).toBe('unchecked'); component.clickSelectAll(); expect(component.cdkSelection.isAllSelected()).toBeTruthy(); expect(component.getSelectAll().textContent.trim()).toBe('checked'); })); it('should de-select all items when all selected', fakeAsync(() => { // Select all items. component.clickSelectAll(); expect(component.cdkSelection.isAllSelected()).toBeTruthy(); expect(component.getSelectAll().textContent.trim()).toBe('checked'); component.clickSelectAll(); expect(component.cdkSelection.isAllSelected()).toBeFalsy(); expect(component.getSelectAll().textContent.trim()).toBe('unchecked'); })); it('should de-select all items when partially selected', fakeAsync(() => { // make the 1st item selected. component.clickSelectionToggle(0); expect(component.cdkSelection.isPartialSelected()).toBeTruthy(); expect(component.getSelectAll().textContent.trim()).toBe('indeterminate'); component.clickSelectAll(); expect(component.cdkSelection.isAllSelected()).toBeFalsy(); expect(component.cdkSelection.isPartialSelected()).toBeFalsy(); expect(component.getSelectAll().textContent.trim()).toBe('unchecked'); })); it('should respond to selection toggle clicks', fakeAsync(() => { // Start with no selection. expect(component.cdkSelection.isAllSelected()).toBeFalsy(); expect(component.getSelectAll().textContent.trim()).toBe('unchecked'); // Select the 1st item. component.clickSelectionToggle(0); // Partially selected. expect(component.cdkSelection.isAllSelected()).toBeFalsy(); expect(component.cdkSelection.isPartialSelected()).toBeTruthy(); expect(component.getSelectAll().textContent.trim()).toBe('indeterminate'); // Select the all the other items. component.clickSelectionToggle(1); component.clickSelectionToggle(2); component.clickSelectionToggle(3); // Select-all shows all selected. expect(component.cdkSelection.isAllSelected()).toBeTruthy(); expect(component.cdkSelection.isPartialSelected()).toBeFalsy(); expect(component.getSelectAll().textContent.trim()).toBe('checked'); })); it('should emit the correct selection change events', fakeAsync(() => { component.clickSelectAll(); expect(component.selectionChange!.before).toEqual([]); expect(component.selectionChange!.after).toEqual([ {value: 'apple', index: 0}, {value: 'banana', index: 1}, {value: 'cherry', index: 2}, {value: 'durian', index: 3}, ]); component.clickSelectAll(); expect(component.selectionChange!.before).toEqual([ {value: 'apple', index: 0}, {value: 'banana', index: 1}, {value: 'cherry', index: 2}, {value: 'durian', index: 3}, ]); expect(component.selectionChange!.after).toEqual([]); })); }); describe('cdkSelectionToggle', () => { it('should respond to select-all toggle click', fakeAsync(() => { // All items not unchecked. expect(component.getSelectionToggle(0).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(1).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('unchecked'); component.clickSelectAll(); // Everything selected. expect(component.getSelectionToggle(0).textContent.trim()).toBe('checked'); expect(component.getSelectionToggle(1).textContent.trim()).toBe('checked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('checked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('checked'); component.clickSelectAll(); // Everything unselected. expect(component.getSelectionToggle(0).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(1).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('unchecked'); })); it('should select unselected item when clicked', fakeAsync(() => { expect(component.cdkSelection.isSelected('apple', 0)).toBeFalsy(); expect(component.getSelectionToggle(0).textContent.trim()).toBe('unchecked'); component.clickSelectionToggle(0); expect(component.cdkSelection.isSelected('apple', 0)).toBeTruthy(); expect(component.getSelectionToggle(0).textContent.trim()).toBe('checked'); // And all the others are not affected. expect(component.cdkSelection.isSelected('banana', 1)).toBeFalsy(); expect(component.cdkSelection.isSelected('cherry', 2)).toBeFalsy(); expect(component.cdkSelection.isSelected('durian', 3)).toBeFalsy(); expect(component.getSelectionToggle(1).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('unchecked'); })); it('should de-selected selected item when clicked', fakeAsync(() => { // Make all items selected. component.clickSelectAll(); component.clickSelectionToggle(1); expect(component.cdkSelection.isSelected('banana', 1)).toBeFalsy(); expect(component.getSelectionToggle(1).textContent.trim()).toBe('unchecked'); // And all the others are not affected. expect(component.cdkSelection.isSelected('apple', 0)).toBeTruthy(); expect(component.cdkSelection.isSelected('cherry', 2)).toBeTruthy(); expect(component.cdkSelection.isSelected('durian', 3)).toBeTruthy(); expect(component.getSelectionToggle(0).textContent.trim()).toBe('checked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('checked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('checked'); })); it('should emit the correct selection change events', fakeAsync(() => { component.clickSelectionToggle(1); expect(component.selectionChange!.before).toEqual([]); expect(component.selectionChange!.after).toEqual([{value: 'banana', index: 1}]); component.clickSelectionToggle(2); expect(component.selectionChange!.before).toEqual([{value: 'banana', index: 1}]); expect(component.selectionChange!.after).toEqual([ {value: 'banana', index: 1}, {value: 'cherry', index: 2}, ]); component.clickSelectionToggle(2); expect(component.selectionChange!.before).toEqual([ {value: 'banana', index: 1}, {value: 'cherry', index: 2}, ]); expect(component.selectionChange!.after).toEqual([{value: 'banana', index: 1}]); })); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 9312, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/selection.spec.ts" }
components/src/cdk-experimental/selection/selection.spec.ts_9314_17309
describe('CdkSelection with multiple = false', () => { let fixture: ComponentFixture<ListWithSingleSelection>; let component: ListWithSingleSelection; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [CdkSelectionModule, ListWithSingleSelection], }); })); beforeEach(() => { fixture = TestBed.createComponent(ListWithSingleSelection); component = fixture.componentInstance; fixture.detectChanges(); }); it('should uncheck the previous selection when selecting new item', fakeAsync(() => { // Everything start as unchecked. expect(component.getSelectionToggle(0).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(1).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('unchecked'); component.clickSelectionToggle(0); expect(component.getSelectionToggle(0).textContent.trim()).toBe('checked'); expect(component.getSelectionToggle(1).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('unchecked'); component.clickSelectionToggle(1); // Should uncheck the previous selection while selecting the new value. expect(component.getSelectionToggle(0).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(1).textContent.trim()).toBe('checked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('unchecked'); component.clickSelectionToggle(1); // Selecting a selected value should still uncheck it. expect(component.getSelectionToggle(0).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(1).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(2).textContent.trim()).toBe('unchecked'); expect(component.getSelectionToggle(3).textContent.trim()).toBe('unchecked'); })); it('should emit the correct selection change events', fakeAsync(() => { component.clickSelectionToggle(1); expect(component.selectionChange!.before).toEqual([]); expect(component.selectionChange!.after).toEqual([{value: 'banana', index: 1}]); component.clickSelectionToggle(2); expect(component.selectionChange!.before).toEqual([{value: 'banana', index: 1}]); expect(component.selectionChange!.after).toEqual([{value: 'cherry', index: 2}]); component.clickSelectionToggle(2); expect(component.selectionChange!.before).toEqual([{value: 'cherry', index: 2}]); expect(component.selectionChange!.after).toEqual([]); })); }); describe('cdkSelectionColumn', () => { let fixture: ComponentFixture<MultiSelectTableWithSelectionColumn>; let component: MultiSelectTableWithSelectionColumn; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [CdkSelectionModule, CdkTableModule, MultiSelectTableWithSelectionColumn], }); })); beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(MultiSelectTableWithSelectionColumn); component = fixture.componentInstance; fixture.detectChanges(); flush(); })); it('should show check boxes', () => { const checkboxes = component.elementRef.nativeElement.querySelectorAll('input[type="checkbox"]'); // Select-all toggle + each toggle per row. expect(checkboxes.length).toBe(5); }); it('should allow select all', fakeAsync(() => { expect(component.getSelectAll().checked).toBe(false); expect(component.getSelectionToggle(0).checked).toBe(false); expect(component.getSelectionToggle(1).checked).toBe(false); expect(component.getSelectionToggle(2).checked).toBe(false); expect(component.getSelectionToggle(3).checked).toBe(false); component.clickSelectAll(); expect(component.getSelectAll().checked).toBe(true); expect(component.getSelectionToggle(0).checked).toBe(true); expect(component.getSelectionToggle(1).checked).toBe(true); expect(component.getSelectionToggle(2).checked).toBe(true); expect(component.getSelectionToggle(3).checked).toBe(true); })); it('should allow toggle rows', fakeAsync(() => { expect(component.getSelectAll().checked).toBe(false); expect(component.getSelectAll().indeterminate).toBe(false); expect(component.getSelectionToggle(0).checked).toBe(false); component.clickSelectionToggle(0); expect(component.getSelectAll().checked).toBe(false); expect(component.getSelectAll().indeterminate).toBe(true); expect(component.getSelectionToggle(0).checked).toBe(true); component.clickSelectionToggle(1); component.clickSelectionToggle(2); component.clickSelectionToggle(3); expect(component.getSelectAll().checked).toBe(true); expect(component.getSelectAll().indeterminate).toBe(false); expect(component.getSelectionToggle(1).checked).toBe(true); expect(component.getSelectionToggle(2).checked).toBe(true); expect(component.getSelectionToggle(3).checked).toBe(true); })); describe('cdkRowSelection', () => { it('should set .cdk-selected on selected rows', fakeAsync(() => { expect(component.getRow(0).classList.contains('cdk-selected')).toBeFalsy(); expect(component.getRow(1).classList.contains('cdk-selected')).toBeFalsy(); expect(component.getRow(2).classList.contains('cdk-selected')).toBeFalsy(); expect(component.getRow(3).classList.contains('cdk-selected')).toBeFalsy(); component.clickSelectionToggle(0); expect(component.getRow(0).classList.contains('cdk-selected')).toBeTruthy(); component.clickSelectionToggle(0); expect(component.getRow(0).classList.contains('cdk-selected')).toBeFalsy(); })); it('should set aria-selected on selected rows', fakeAsync(() => { expect(component.getRow(0).getAttribute('aria-selected')).toBe('false'); expect(component.getRow(1).getAttribute('aria-selected')).toBe('false'); expect(component.getRow(2).getAttribute('aria-selected')).toBe('false'); expect(component.getRow(3).getAttribute('aria-selected')).toBe('false'); component.clickSelectionToggle(0); expect(component.getRow(0).getAttribute('aria-selected')).toBe('true'); component.clickSelectionToggle(0); expect(component.getRow(0).getAttribute('aria-selected')).toBe('false'); })); }); }); describe('cdkSelectionColumn with multiple = false', () => { let fixture: ComponentFixture<SingleSelectTableWithSelectionColumn>; let component: SingleSelectTableWithSelectionColumn; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [CdkSelectionModule, CdkTableModule, SingleSelectTableWithSelectionColumn], }); })); beforeEach(() => { fixture = TestBed.createComponent(SingleSelectTableWithSelectionColumn); component = fixture.componentInstance; fixture.detectChanges(); }); it('should not show select all', () => { expect(component.elementRef.nativeElement.querySelector('input[cdkselectall]')).toBe(null); }); it('should allow selecting one single row', fakeAsync(() => { expect(component.getSelectionToggle(0).checked).toBe(false); expect(component.getSelectionToggle(1).checked).toBe(false); expect(component.getSelectionToggle(2).checked).toBe(false); expect(component.getSelectionToggle(3).checked).toBe(false); component.clickSelectionToggle(0); expect(component.getSelectionToggle(0).checked).toBe(true); component.clickSelectionToggle(1); expect(component.getSelectionToggle(0).checked).toBe(false); expect(component.getSelectionToggle(1).checked).toBe(true); component.clickSelectionToggle(1); expect(component.getSelectionToggle(1).checked).toBe(false); })); });
{ "commit_id": "ea0d1ba7b", "end_byte": 17309, "start_byte": 9314, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/selection.spec.ts" }
components/src/cdk-experimental/selection/selection.spec.ts_17311_23872
@Component({ template: ` <ul cdkSelection [dataSource]="data" [cdkSelectionMultiple]="true" (cdkSelectionChange)="selectionChange = $event"> <button cdkSelectAll #toggleAll="cdkSelectAll" (click)="toggleAll.toggle($event)"> {{selectAllState(toggleAll.indeterminate | async, toggleAll.checked | async)}} </button> @for (item of data; track item; let i = $index) { <li> <button cdkSelectionToggle #toggle="cdkSelectionToggle" [cdkSelectionToggleValue]="item" [cdkSelectionToggleIndex]="i" (click)="toggle.toggle()"> {{(toggle.checked | async) ? 'checked' : 'unchecked'}} </button> {{item}} </li> } </ul>`, standalone: true, imports: [CdkSelectionModule, AsyncPipe], }) class ListWithMultiSelection { private readonly _elementRef = inject(ElementRef); private readonly _cdr = inject(ChangeDetectorRef); @ViewChild(CdkSelection) cdkSelection: CdkSelection<string>; data = ['apple', 'banana', 'cherry', 'durian']; selectionChange?: SelectionChange<string>; selectAllState(indeterminateState: boolean | null, checkedState: boolean | null): string { if (indeterminateState) { return 'indeterminate'; } else if (checkedState) { return 'checked'; } else { return 'unchecked'; } } clickSelectAll() { this.getSelectAll().click(); flush(); this._cdr.detectChanges(); } clickSelectionToggle(index: number) { const toggle = this.getSelectionToggle(index); if (!toggle) { return; } toggle.click(); flush(); this._cdr.detectChanges(); } getSelectAll() { return this._elementRef.nativeElement.querySelector('[cdkselectall]'); } getSelectionToggle(index: number) { return this._elementRef.nativeElement.querySelectorAll('[cdkselectiontoggle]')[index]; } } @Component({ template: ` <ul cdkSelection [dataSource]="data" [cdkSelectionMultiple]="false" (cdkSelectionChange)="selectionChange = $event" > @for (item of data; track item; let i = $index) { <li> <button cdkSelectionToggle #toggle="cdkSelectionToggle" [cdkSelectionToggleValue]="item" [cdkSelectionToggleIndex]="i" (click)="toggle.toggle()"> {{(toggle.checked | async) ? 'checked' : 'unchecked'}} </button> {{item}} </li> } </ul>`, standalone: true, imports: [CdkSelectionModule, AsyncPipe], }) class ListWithSingleSelection { private readonly _elementRef = inject(ElementRef); private readonly _cdr = inject(ChangeDetectorRef); @ViewChild(CdkSelection) cdkSelection: CdkSelection<string>; data = ['apple', 'banana', 'cherry', 'durian']; selectionChange?: SelectionChange<string>; clickSelectionToggle(index: number) { const toggle = this.getSelectionToggle(index); if (!toggle) { return; } toggle.click(); flush(); this._cdr.detectChanges(); } getSelectionToggle(index: number) { return this._elementRef.nativeElement.querySelectorAll('[cdkselectiontoggle]')[index]; } } @Component({ template: ` <table cdk-table cdkSelection [dataSource]="data" [cdkSelectionMultiple]="true"> <cdk-selection-column cdkSelectionColumnName="select"></cdk-selection-column> <ng-container cdkColumnDef="name"> <th cdk-header-cell *cdkHeaderCellDef>Name</th> <td cdk-cell *cdkCellDef="let element">{{element}}</td> </ng-container> <tr cdk-header-row *cdkHeaderRowDef="columns"></tr> <tr cdk-row *cdkRowDef="let row; columns: columns;" cdkRowSelection [cdkRowSelectionValue]="row"></tr> </table> `, standalone: true, imports: [CdkSelectionModule, CdkTableModule], }) class MultiSelectTableWithSelectionColumn { readonly elementRef = inject(ElementRef); private readonly _cdr = inject(ChangeDetectorRef); @ViewChild(CdkSelection) cdkSelection: CdkSelection<string>; columns = ['select', 'name']; data = ['apple', 'banana', 'cherry', 'durian']; selectAllState(indeterminateState: boolean | null, checkedState: boolean | null): string { if (indeterminateState) { return 'indeterminate'; } else if (checkedState) { return 'checked'; } else { return 'unchecked'; } } clickSelectAll() { this.getSelectAll().click(); flush(); this._cdr.detectChanges(); flush(); } clickSelectionToggle(index: number) { const toggle = this.getSelectionToggle(index); if (!toggle) { return; } toggle.click(); flush(); this._cdr.detectChanges(); flush(); } getSelectAll(): HTMLInputElement { return this.elementRef.nativeElement.querySelector('input[cdkselectall]'); } getSelectionToggle(index: number): HTMLInputElement { return this.elementRef.nativeElement.querySelectorAll('input[cdkselectiontoggle]')[index]; } getRow(index: number): HTMLElement { return this.elementRef.nativeElement.querySelectorAll('tr[cdkrowselection]')[index]; } } @Component({ template: ` <table cdk-table cdkSelection [dataSource]="data" [cdkSelectionMultiple]="false"> <cdk-selection-column cdkSelectionColumnName="select"></cdk-selection-column> <ng-container cdkColumnDef="name"> <th cdk-header-cell *cdkHeaderCellDef>Name</th> <td cdk-cell *cdkCellDef="let element">{{element}}</td> </ng-container> <tr cdk-header-row *cdkHeaderRowDef="columns"></tr> <tr cdk-row *cdkRowDef="let row; columns: columns;" cdkRowSelection [cdkRowSelectionValue]="row"></tr> </table> `, standalone: true, imports: [CdkSelectionModule, CdkTableModule], }) class SingleSelectTableWithSelectionColumn { readonly elementRef = inject(ElementRef); private readonly _cdr = inject(ChangeDetectorRef); @ViewChild(CdkSelection) cdkSelection: CdkSelection<string>; columns = ['select', 'name']; data = ['apple', 'banana', 'cherry', 'durian']; clickSelectionToggle(index: number) { const toggle = this.getSelectionToggle(index); if (!toggle) { return; } toggle.click(); flush(); this._cdr.detectChanges(); flush(); } getSelectionToggle(index: number): HTMLInputElement { return this.elementRef.nativeElement.querySelectorAll('input[cdkselectiontoggle]')[index]; } getRow(index: number): HTMLElement { return this.elementRef.nativeElement.querySelectorAll('tr[cdkrowselection]')[index]; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 23872, "start_byte": 17311, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/selection.spec.ts" }
components/src/cdk-experimental/selection/selection-module.ts_0_832
/** * @license * Copyright Google LLC 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.dev/license */ import {CdkTableModule} from '@angular/cdk/table'; import {NgModule} from '@angular/core'; import {CdkRowSelection} from './row-selection'; import {CdkSelectAll} from './select-all'; import {CdkSelection} from './selection'; import {CdkSelectionColumn} from './selection-column'; import {CdkSelectionToggle} from './selection-toggle'; @NgModule({ imports: [ CdkTableModule, CdkSelection, CdkSelectionToggle, CdkSelectAll, CdkSelectionColumn, CdkRowSelection, ], exports: [CdkSelection, CdkSelectionToggle, CdkSelectAll, CdkSelectionColumn, CdkRowSelection], }) export class CdkSelectionModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 832, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/selection-module.ts" }
components/src/cdk-experimental/selection/select-all.ts_0_3850
/** * @license * Copyright Google LLC 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.dev/license */ import {Directive, OnDestroy, OnInit, inject} from '@angular/core'; import {NG_VALUE_ACCESSOR} from '@angular/forms'; import {Observable, of as observableOf, Subject} from 'rxjs'; import {switchMap, takeUntil} from 'rxjs/operators'; import {CdkSelection} from './selection'; /** * Makes the element a select-all toggle. * * Must be used within a parent `CdkSelection` directive. It toggles the selection states * of all the selection toggles connected with the `CdkSelection` directive. * If the element implements `ControlValueAccessor`, e.g. `MatCheckbox`, the directive * automatically connects it with the select-all state provided by the `CdkSelection` directive. If * not, use `checked$` to get the checked state, `indeterminate$` to get the indeterminate state, * and `toggle()` to change the selection state. */ @Directive({ selector: '[cdkSelectAll]', exportAs: 'cdkSelectAll', }) export class CdkSelectAll<T> implements OnDestroy, OnInit { private readonly _selection = inject<CdkSelection<T>>(CdkSelection, {optional: true})!; private readonly _controlValueAccessor = inject(NG_VALUE_ACCESSOR, {optional: true, self: true}); /** * The checked state of the toggle. * Resolves to `true` if all the values are selected, `false` if no value is selected. */ readonly checked: Observable<boolean>; /** * The indeterminate state of the toggle. * Resolves to `true` if part (not all) of the values are selected, `false` if all values or no * value at all are selected. */ readonly indeterminate: Observable<boolean>; /** * Toggles the select-all state. * @param event The click event if the toggle is triggered by a (mouse or keyboard) click. If * using with a native `<input type="checkbox">`, the parameter is required for the * indeterminate state to work properly. */ toggle(event?: MouseEvent) { // This is needed when applying the directive on a native <input type="checkbox"> // checkbox. The default behavior needs to be prevented in order to support the indeterminate // state. The timeout is also needed so the checkbox can show the latest state. if (event) { event.preventDefault(); } setTimeout(() => { this._selection.toggleSelectAll(); }); } private readonly _destroyed = new Subject<void>(); constructor() { const _selection = this._selection; this.checked = _selection.change.pipe( switchMap(() => observableOf(_selection.isAllSelected())), ); this.indeterminate = _selection.change.pipe( switchMap(() => observableOf(_selection.isPartialSelected())), ); } ngOnInit() { this._assertValidParentSelection(); this._configureControlValueAccessor(); } private _configureControlValueAccessor() { if (this._controlValueAccessor && this._controlValueAccessor.length) { this._controlValueAccessor[0].registerOnChange((e: unknown) => { if (e === true || e === false) { this.toggle(); } }); this.checked.pipe(takeUntil(this._destroyed)).subscribe(state => { this._controlValueAccessor![0].writeValue(state); }); } } private _assertValidParentSelection() { if (!this._selection && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('CdkSelectAll: missing CdkSelection in the parent'); } if (!this._selection.multiple && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('CdkSelectAll: CdkSelection must have cdkSelectionMultiple set to true'); } } ngOnDestroy() { this._destroyed.next(); this._destroyed.complete(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3850, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/select-all.ts" }
components/src/cdk-experimental/selection/BUILD.bazel_0_846
load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite") package(default_visibility = ["//visibility:public"]) ng_module( name = "selection", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src:dev_mode_types", "//src/cdk/coercion", "//src/cdk/collections", "//src/cdk/table", "@npm//@angular/core", "@npm//@angular/forms", "@npm//rxjs", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":selection", "//src/cdk/table", "//src/cdk/testing/private", "@npm//@angular/common", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], )
{ "commit_id": "ea0d1ba7b", "end_byte": 846, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/BUILD.bazel" }
components/src/cdk-experimental/selection/index.ts_0_234
/** * @license * Copyright Google LLC 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.dev/license */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/cdk-experimental/selection/index.ts" }
components/src/material-luxon-adapter/require-config.js_0_265
// Require.js is being used by the karma bazel rules and needs to be configured to properly // load AMD modules which are not explicitly named in their output bundle. require.config({ paths: { 'luxon': '/base/npm/node_modules/luxon/build/amd/luxon', }, });
{ "commit_id": "ea0d1ba7b", "end_byte": 265, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/require-config.js" }
components/src/material-luxon-adapter/public-api.ts_0_237
/** * @license * Copyright Google LLC 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.dev/license */ export * from './adapter/index';
{ "commit_id": "ea0d1ba7b", "end_byte": 237, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/public-api.ts" }
components/src/material-luxon-adapter/BUILD.bazel_0_1049
load("//tools:defaults.bzl", "ng_module", "ng_package", "ng_test_library", "ng_web_test_suite") package(default_visibility = ["//visibility:public"]) ng_module( name = "material-luxon-adapter", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src:dev_mode_types", "//src/material/core", "@npm//@angular/core", "@npm//@types/luxon", "@npm//luxon", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":material-luxon-adapter", "//src/material/core", "@npm//@types/luxon", "@npm//luxon", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_test_sources", ], ) ng_package( name = "npm_package", srcs = ["package.json"], nested_packages = ["//src/material-luxon-adapter/schematics:npm_package"], tags = ["release-package"], deps = [":material-luxon-adapter"], )
{ "commit_id": "ea0d1ba7b", "end_byte": 1049, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/BUILD.bazel" }
components/src/material-luxon-adapter/index.ts_0_234
/** * @license * Copyright Google LLC 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.dev/license */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/index.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts_0_625
/** * @license * Copyright Google LLC 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.dev/license */ import {LOCALE_ID} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core'; import {CalendarSystem, DateTime, FixedOffsetZone, Settings} from 'luxon'; import {LuxonDateModule} from './index'; import {MAT_LUXON_DATE_ADAPTER_OPTIONS} from './luxon-date-adapter'; const JAN = 1, FEB = 2, MAR = 3, DEC = 12; describe('LuxonDateAdapter',
{ "commit_id": "ea0d1ba7b", "end_byte": 625, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts_626_7391
() => { let adapter: DateAdapter<DateTime>; beforeEach(() => { TestBed.configureTestingModule({imports: [LuxonDateModule]}); adapter = TestBed.inject(DateAdapter); adapter.setLocale('en-US'); }); it('should get year', () => { expect(adapter.getYear(DateTime.local(2017, JAN, 1))).toBe(2017); }); it('should get month', () => { expect(adapter.getMonth(DateTime.local(2017, JAN, 1))).toBe(0); }); it('should get date', () => { expect(adapter.getDate(DateTime.local(2017, JAN, 1))).toBe(1); }); it('should get day of week', () => { expect(adapter.getDayOfWeek(DateTime.local(2017, JAN, 1))).toBe(7); }); it('should get long month names', () => { expect(adapter.getMonthNames('long')).toEqual([ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]); }); it('should get short month names', () => { expect(adapter.getMonthNames('short')).toEqual([ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]); }); it('should get narrow month names', () => { expect(adapter.getMonthNames('narrow')).toEqual([ 'J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', ]); }); it('should get month names in a czech locale', () => { adapter.setLocale('cs-CZ'); expect(adapter.getMonthNames('long')).toEqual([ 'leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec', ]); }); it('should get month names in a different locale', () => { adapter.setLocale('da-DK'); expect(adapter.getMonthNames('long')).toEqual([ 'januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december', ]); }); it('should get date names', () => { expect(adapter.getDateNames()).toEqual([ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', ]); }); it('should get date names in a different locale', () => { adapter.setLocale('ja-JP'); expect(adapter.getDateNames()).toEqual([ '1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日', ]); }); it('should get long day of week names', () => { expect(adapter.getDayOfWeekNames('long')).toEqual([ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]); }); it('should get short day of week names', () => { expect(adapter.getDayOfWeekNames('short')).toEqual([ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', ]); }); it('should get narrow day of week names', () => { expect(adapter.getDayOfWeekNames('narrow')).toEqual(['S', 'M', 'T', 'W', 'T', 'F', 'S']); }); it('should get day of week names in a different locale', () => { adapter.setLocale('ja-JP'); expect(adapter.getDayOfWeekNames('long')).toEqual([ '日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日', ]); }); it('should get year name', () => { expect(adapter.getYearName(DateTime.local(2017, JAN, 1))).toBe('2017'); }); it('should get year name in a different locale', () => { adapter.setLocale('ja-JP'); expect(adapter.getYearName(DateTime.local(2017, JAN, 1))).toBe('2017'); }); it('should get first day of week', () => { expect(adapter.getFirstDayOfWeek()).toBe(0); }); it('should create Luxon date', () => { expect(adapter.createDate(2017, JAN, 1) instanceof DateTime).toBe(true); }); it('should not create Luxon date with month over/under-flow', () => { expect(() => adapter.createDate(2017, 12, 1)).toThrow(); expect(() => adapter.createDate(2017, -1, 1)).toThrow(); }); it('should not create Luxon date with date over/under-flow', () => { expect(() => adapter.createDate(2017, JAN, 32)).toThrow(); expect(() => adapter.createDate(2017, JAN, 0)).toThrow(); }); it("should get today's date", () => { expect(adapter.sameDate(adapter.today(), DateTime.local())) .withContext("should be equal to today's date") .toBe(true); }); it('should parse string according to given format', () => { expect(adapter.parse('1/2/2017', 'L/d/yyyy')!.toISO()).toEqual( DateTime.local(2017, JAN, 2).toISO(), ); expect(adapter.parse('1/2/2017', 'd/L/yyyy')!.toISO()).toEqual( DateTime.local(2017, FEB, 1).toISO(), ); }); it('should parse string according to first matching format', () => { expect(adapter.parse('1/2/2017', ['L/d/yyyy', 'yyyy/d/L'])!.toISO()).toEqual( DateTime.local(2017, JAN, 2).toISO(), ); expect(adapter.parse('1/2/2017', ['yyyy/d/L', 'L/d/yyyy'])!.toISO()).toEqual( DateTime.local(2017, JAN, 2).toISO(), ); }); it('should throw if parse formats are an empty array', () => { expect(() => adapter.parse('1/2/2017', [])).toThrowError('Formats array must not be empty.'); }); it('should parse number', () => { let timestamp = new Date().getTime(); expect(adapter.parse(timestamp, 'LL/dd/yyyy')!.toISO()).toEqual( DateTime.fromMillis(timestamp).toISO(), ); }); it('should parse Date', () => { let date = new Date(2017, JAN, 1); expect(adapter.parse(date, 'LL/dd/yyyy')!.toISO()).toEqual(DateTime.fromJSDate(date).toISO()); }); it('should parse DateTime', () => { let date = DateTime.local(2017, JAN, 1); expect(adapter.parse(date, 'LL/dd/yyyy')!.toISO()).toEqual(date.toISO()); }); it('should parse empty string as null', () => { expect(adapter.parse('', 'LL/dd/yyyy')).toBeNull(); }); it('should parse invalid value as invalid', () => { let d = adapter.parse('hello', 'LL/dd/yyyy'); expe
{ "commit_id": "ea0d1ba7b", "end_byte": 7391, "start_byte": 626, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts_7395_14436
).not.toBeNull(); expect(adapter.isDateInstance(d)).toBe(true); expect(adapter.isValid(d as DateTime)) .withContext('Expected to parse as "invalid date" object') .toBe(false); }); it('should format date according to given format', () => { expect(adapter.format(DateTime.local(2017, JAN, 2), 'LL/dd/yyyy')).toEqual('01/02/2017'); }); it('should format with a different locale', () => { let date = adapter.format(DateTime.local(2017, JAN, 2), 'DD'); expect(date).toEqual('Jan 2, 2017'); adapter.setLocale('da-DK'); date = adapter.format(DateTime.local(2017, JAN, 2), 'DD'); expect(date).toEqual('2. jan. 2017'); }); it('should format with a different timezone', () => { Settings.defaultZone = FixedOffsetZone.parseSpecifier('UTC-12'); let date = adapter.format(DateTime.local(2017, JAN, 2, {zone: 'UTC-12'}), 'DD'); expect(date).toEqual('Jan 2, 2017'); date = adapter.format(DateTime.local(2017, JAN, 2, {zone: 'UTC+12'}), 'DD'); expect(date).toEqual('Jan 2, 2017'); }); it('should throw when attempting to format invalid date', () => { expect(() => adapter.format(DateTime.fromMillis(NaN), 'LL/dd/yyyy')).toThrowError( /LuxonDateAdapter: Cannot format invalid date\./, ); }); it('should add years', () => { expect(adapter.addCalendarYears(DateTime.local(2017, JAN, 1), 1).toISO()).toEqual( DateTime.local(2018, JAN, 1).toISO(), ); expect(adapter.addCalendarYears(DateTime.local(2017, JAN, 1), -1).toISO()).toEqual( DateTime.local(2016, JAN, 1).toISO(), ); }); it('should respect leap years when adding years', () => { expect(adapter.addCalendarYears(DateTime.local(2016, FEB, 29), 1).toISO()).toEqual( DateTime.local(2017, FEB, 28).toISO(), ); expect(adapter.addCalendarYears(DateTime.local(2016, FEB, 29), -1).toISO()).toEqual( DateTime.local(2015, FEB, 28).toISO(), ); }); it('should add months', () => { expect(adapter.addCalendarMonths(DateTime.local(2017, JAN, 1), 1).toISO()).toEqual( DateTime.local(2017, FEB, 1).toISO(), ); expect(adapter.addCalendarMonths(DateTime.local(2017, JAN, 1), -1).toISO()).toEqual( DateTime.local(2016, DEC, 1).toISO(), ); }); it('should respect month length differences when adding months', () => { expect(adapter.addCalendarMonths(DateTime.local(2017, JAN, 31), 1).toISO()).toEqual( DateTime.local(2017, FEB, 28).toISO(), ); expect(adapter.addCalendarMonths(DateTime.local(2017, MAR, 31), -1).toISO()).toEqual( DateTime.local(2017, FEB, 28).toISO(), ); }); it('should add days', () => { expect(adapter.addCalendarDays(DateTime.local(2017, JAN, 1), 1).toISO()).toEqual( DateTime.local(2017, JAN, 2).toISO(), ); expect(adapter.addCalendarDays(DateTime.local(2017, JAN, 1), -1).toISO()).toEqual( DateTime.local(2016, DEC, 31).toISO(), ); }); it('should clone', () => { let date = DateTime.local(2017, JAN, 1); let clone = adapter.clone(date); expect(clone).not.toBe(date); expect(clone.toISO()).toEqual(date.toISO()); }); it('should compare dates', () => { expect( adapter.compareDate(DateTime.local(2017, JAN, 1), DateTime.local(2017, JAN, 2)), ).toBeLessThan(0); expect( adapter.compareDate(DateTime.local(2017, JAN, 1), DateTime.local(2017, FEB, 1)), ).toBeLessThan(0); expect( adapter.compareDate(DateTime.local(2017, JAN, 1), DateTime.local(2018, JAN, 1)), ).toBeLessThan(0); expect(adapter.compareDate(DateTime.local(2017, JAN, 1), DateTime.local(2017, JAN, 1))).toBe(0); expect( adapter.compareDate(DateTime.local(2018, JAN, 1), DateTime.local(2017, JAN, 1)), ).toBeGreaterThan(0); expect( adapter.compareDate(DateTime.local(2017, FEB, 1), DateTime.local(2017, JAN, 1)), ).toBeGreaterThan(0); expect( adapter.compareDate(DateTime.local(2017, JAN, 2), DateTime.local(2017, JAN, 1)), ).toBeGreaterThan(0); }); it('should clamp date at lower bound', () => { expect( adapter.clampDate( DateTime.local(2017, JAN, 1), DateTime.local(2018, JAN, 1), DateTime.local(2019, JAN, 1), ), ).toEqual(DateTime.local(2018, JAN, 1)); }); it('should clamp date at upper bound', () => { expect( adapter.clampDate( DateTime.local(2020, JAN, 1), DateTime.local(2018, JAN, 1), DateTime.local(2019, JAN, 1), ), ).toEqual(DateTime.local(2019, JAN, 1)); }); it('should clamp date already within bounds', () => { expect( adapter.clampDate( DateTime.local(2018, FEB, 1), DateTime.local(2018, JAN, 1), DateTime.local(2019, JAN, 1), ), ).toEqual(DateTime.local(2018, FEB, 1)); }); it('should count today as a valid date instance', () => { let d = DateTime.local(); expect(adapter.isValid(d)).toBe(true); expect(adapter.isDateInstance(d)).toBe(true); }); it('should count an invalid date as an invalid date instance', () => { let d = DateTime.fromMillis(NaN); expect(adapter.isValid(d)).toBe(false); expect(adapter.isDateInstance(d)).toBe(true); }); it('should count a string as not a date instance', () => { let d = '1/1/2017'; expect(adapter.isDateInstance(d)).toBe(false); }); it('should count a Date as not a date instance', () => { let d = new Date(); expect(adapter.isDateInstance(d)).toBe(false); }); it('should create valid dates from valid ISO strings', () => { assertValidDate(adapter, adapter.deserialize('1985-04-12T23:20:50.52Z'), true); assertValidDate(adapter, adapter.deserialize('1996-12-19T16:39:57-08:00'), true); assertValidDate(adapter, adapter.deserialize('1937-01-01T12:00:27.87+00:20'), true); assertValidDate(adapter, adapter.deserialize('1990-13-31T23:59:00Z'), false); assertValidDate(adapter, adapter.deserialize('1/1/2017'), false); expect(adapter.deserialize('')).toBeNull(); expect(adapter.deserialize(null)).toBeNull(); assertValidDate(adapter, adapter.deserialize(new Date()), true); assertValidDate(adapter, adapter.deserialize(new Date(NaN)), false); assertValidDate(adapter, adapter.deserialize(DateTime.local()), true); assertValidDate(adapter, adapter.deserialize(DateTime.invalid('Not valid')), false); }); it('returned dates should have correct locale', () => { adapter.setLocale('ja-JP'); expect(adapter.createDate(2017, JAN, 1).locale).toBe('ja-JP'); expect(adapter.today().locale).toBe('ja-JP'); expect(adapter.parse('1/1/2017', 'L/d/yyyy')!.locale).toBe('ja-JP'); expect(adapter.addCalendarDays(DateTime.local(), 1).locale).toBe('ja-JP'); expect(adapter.addCalendarMonths(DateTime.local(), 1).locale).toBe('ja-JP'); expect(adapter.addCalendarYears(DateTime.local(), 1).locale).toBe('ja-JP'); }); it('should not change locale of DateTime passed as param', () => { const date = DateTime.local(); cons
{ "commit_id": "ea0d1ba7b", "end_byte": 14436, "start_byte": 7395, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts_14440_21590
itialLocale = date.locale; expect(initialLocale).toBeTruthy(); adapter.setLocale('ja-JP'); adapter.getYear(date); adapter.getMonth(date); adapter.getDate(date); adapter.getDayOfWeek(date); adapter.getYearName(date); adapter.getNumDaysInMonth(date); adapter.clone(date); adapter.parse(date, 'LL/dd/yyyy'); adapter.format(date, 'LL/dd/yyyy'); adapter.addCalendarDays(date, 1); adapter.addCalendarMonths(date, 1); adapter.addCalendarYears(date, 1); adapter.toIso8601(date); adapter.isDateInstance(date); adapter.isValid(date); expect(date.locale).toBe(initialLocale); }); it('should create invalid date', () => { assertValidDate(adapter, adapter.invalid(), false); }); it('should get hours', () => { expect(adapter.getHours(DateTime.local(2024, JAN, 1, 14))).toBe(14); }); it('should get minutes', () => { expect(adapter.getMinutes(DateTime.local(2024, JAN, 1, 14, 53))).toBe(53); }); it('should get seconds', () => { expect(adapter.getSeconds(DateTime.local(2024, JAN, 1, 14, 53, 42))).toBe(42); }); it('should set the time of a date', () => { const target = DateTime.local(2024, JAN, 1, 0, 0, 0); const result = adapter.setTime(target, 14, 53, 42); expect(adapter.getHours(result)).toBe(14); expect(adapter.getMinutes(result)).toBe(53); expect(adapter.getSeconds(result)).toBe(42); }); it('should throw when passing in invalid hours to setTime', () => { expect(() => adapter.setTime(adapter.today(), -1, 0, 0)).toThrowError( 'Invalid hours "-1". Hours value must be between 0 and 23.', ); expect(() => adapter.setTime(adapter.today(), 51, 0, 0)).toThrowError( 'Invalid hours "51". Hours value must be between 0 and 23.', ); }); it('should throw when passing in invalid minutes to setTime', () => { expect(() => adapter.setTime(adapter.today(), 0, -1, 0)).toThrowError( 'Invalid minutes "-1". Minutes value must be between 0 and 59.', ); expect(() => adapter.setTime(adapter.today(), 0, 65, 0)).toThrowError( 'Invalid minutes "65". Minutes value must be between 0 and 59.', ); }); it('should throw when passing in invalid seconds to setTime', () => { expect(() => adapter.setTime(adapter.today(), 0, 0, -1)).toThrowError( 'Invalid seconds "-1". Seconds value must be between 0 and 59.', ); expect(() => adapter.setTime(adapter.today(), 0, 0, 65)).toThrowError( 'Invalid seconds "65". Seconds value must be between 0 and 59.', ); }); it('should parse a 24-hour time string', () => { const result = adapter.parseTime('14:52', 't')!; expect(result).toBeTruthy(); expect(adapter.isValid(result)).toBe(true); expect(adapter.getHours(result)).toBe(14); expect(adapter.getMinutes(result)).toBe(52); expect(adapter.getSeconds(result)).toBe(0); }); it('should parse a 12-hour time string', () => { const result = adapter.parseTime('2:52 PM', 't')!; expect(result).toBeTruthy(); expect(adapter.isValid(result)).toBe(true); expect(adapter.getHours(result)).toBe(14); expect(adapter.getMinutes(result)).toBe(52); expect(adapter.getSeconds(result)).toBe(0); }); it('should parse a padded time string', () => { const result = adapter.parseTime('03:04:05', 'tt')!; expect(result).toBeTruthy(); expect(adapter.isValid(result)).toBe(true); expect(adapter.getHours(result)).toBe(3); expect(adapter.getMinutes(result)).toBe(4); expect(adapter.getSeconds(result)).toBe(5); }); it('should parse a time string that uses dot as a separator', () => { adapter.setLocale('fi-FI'); const result = adapter.parseTime('14.52', 't')!; expect(result).toBeTruthy(); expect(adapter.isValid(result)).toBe(true); expect(adapter.getHours(result)).toBe(14); expect(adapter.getMinutes(result)).toBe(52); expect(adapter.getSeconds(result)).toBe(0); }); it('should parse a time string with characters around the time', () => { adapter.setLocale('bg-BG'); const result = adapter.parseTime('14:52 ч.', 't')!; expect(result).toBeTruthy(); expect(adapter.isValid(result)).toBe(true); expect(adapter.getHours(result)).toBe(14); expect(adapter.getMinutes(result)).toBe(52); expect(adapter.getSeconds(result)).toBe(0); }); it('should return an invalid date when parsing invalid time string', () => { expect(adapter.isValid(adapter.parseTime('abc', 't')!)).toBeFalse(); expect(adapter.isValid(adapter.parseTime(' ', 't')!)).toBeFalse(); expect(adapter.isValid(adapter.parseTime('24:05', 't')!)).toBeFalse(); expect(adapter.isValid(adapter.parseTime('00:61:05', 'tt')!)).toBeFalse(); expect(adapter.isValid(adapter.parseTime('14:52:78', 'tt')!)).toBeFalse(); expect(adapter.isValid(adapter.parseTime('12:10 PM11:10 PM', 'tt')!)).toBeFalse(); }); it('should return null when parsing unsupported time values', () => { expect(adapter.parseTime(true, 't')).toBeNull(); expect(adapter.parseTime(undefined, 't')).toBeNull(); expect(adapter.parseTime('', 't')).toBeNull(); }); it('should compare times', () => { // Use different dates to guarantee that we only compare the times. const aDate = [2024, JAN, 1] as const; const bDate = [2024, FEB, 7] as const; expect( adapter.compareTime(DateTime.local(...aDate, 12, 0, 0), DateTime.local(...bDate, 13, 0, 0)), ).toBeLessThan(0); expect( adapter.compareTime(DateTime.local(...aDate, 12, 50, 0), DateTime.local(...bDate, 12, 51, 0)), ).toBeLessThan(0); expect( adapter.compareTime(DateTime.local(...aDate, 1, 2, 3), DateTime.local(...bDate, 1, 2, 3)), ).toBe(0); expect( adapter.compareTime(DateTime.local(...aDate, 13, 0, 0), DateTime.local(...bDate, 12, 0, 0)), ).toBeGreaterThan(0); expect( adapter.compareTime( DateTime.local(...aDate, 12, 50, 11), DateTime.local(...bDate, 12, 50, 10), ), ).toBeGreaterThan(0); expect( adapter.compareTime(DateTime.local(...aDate, 13, 0, 0), DateTime.local(...bDate, 10, 59, 59)), ).toBeGreaterThan(0); }); it('should add seconds to a date', () => { const amount = 20; const initial = DateTime.local(2024, JAN, 1, 12, 34, 56); const result = adapter.addSeconds(initial, amount); expect(result).not.toBe(initial); expect(result.toMillis() - initial.toMillis()).toBe(amount * 1000); }); }); describe('LuxonDateAdapter with MAT_DATE_LOCALE override', () => { let adapter: DateAdapter<DateTime>; beforeEach(() => { TestBed.configureTestingModule({ imports: [LuxonDateModule], providers: [{provide: MAT_DATE_LOCALE, useValue: 'da-DK'}], }); adapter = TestBed.inject(DateAdapter); }); it('should take the default locale id from the MAT_DATE_LOCALE injection token', () => { const date = adapter.format(DateTime.local(2017, JAN, 2), 'DD'); expect(date).toEqual('2. jan. 2017'); }); }); describe('LuxonDateAdapter with LOCALE_ID override', () => { let adapter: DateAdapter<DateTime>; beforeEach(
{ "commit_id": "ea0d1ba7b", "end_byte": 21590, "start_byte": 14440, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts_21592_24904
=> { TestBed.configureTestingModule({ imports: [LuxonDateModule], providers: [{provide: LOCALE_ID, useValue: 'fr-FR'}], }); adapter = TestBed.inject(DateAdapter); }); it('should take the default locale id from the LOCALE_ID injection token', () => { const date = adapter.format(DateTime.local(2017, JAN, 2), 'DD'); expect(date).toEqual('2 janv. 2017'); }); }); describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS override', () => { let adapter: DateAdapter<DateTime>; beforeEach(() => { TestBed.configureTestingModule({ imports: [LuxonDateModule], providers: [ { provide: MAT_LUXON_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true, firstDayOfWeek: 1}, }, ], }); adapter = TestBed.inject(DateAdapter); }); describe('use UTC', () => { it('should create Luxon date in UTC', () => { // Use 0 since createDate takes 0-indexed months. expect(adapter.createDate(2017, 0, 5).toISO()).toBe(DateTime.utc(2017, JAN, 5).toISO()); }); it('should get first day of week', () => { expect(adapter.getFirstDayOfWeek()).toBe(1); }); it('should create today in UTC', () => { const today = adapter.today(); expect(today.toISO()).toBe(today.toUTC().toISO()); }); it('should parse dates to UTC', () => { const date = adapter.parse('1/2/2017', 'LL/dd/yyyy')!; expect(date.toISO()).toBe(date.toUTC().toISO()); }); it('should return UTC date when deserializing', () => { const date = adapter.deserialize('1985-04-12T23:20:50.52Z')!; expect(date.toISO()).toBe(date.toUTC().toISO()); }); }); }); describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS override for defaultOutputCalendar option', () => { let adapter: DateAdapter<DateTime>; const calendarExample: CalendarSystem = 'islamic'; beforeEach(() => { TestBed.configureTestingModule({ imports: [LuxonDateModule], providers: [ { provide: MAT_LUXON_DATE_ADAPTER_OPTIONS, useValue: {defaultOutputCalendar: calendarExample}, }, ], }); adapter = TestBed.inject(DateAdapter); }); describe(`use ${calendarExample} calendar`, () => { it(`should create Luxon date in ${calendarExample} calendar`, () => { // Use 0 since createDate takes 0-indexed months. expect(adapter.createDate(2017, 0, 2).toLocaleString()).toBe( DateTime.local(2017, JAN, 2, {outputCalendar: calendarExample}).toLocaleString(), ); }); it(`should create today in ${calendarExample} calendar`, () => { expect(adapter.today().toLocaleString()).toBe( DateTime.local({outputCalendar: calendarExample}).toLocaleString(), ); }); }); }); function assertValidDate(adapter: DateAdapter<DateTime>, d: DateTime | null, valid: boolean) { expect(adapter.isDateInstance(d)) .not.withContext(`Expected ${d} to be a date instance`) .toBeNull(); expect(adapter.isValid(d!)) .withContext( `Expected ${d} to be ${valid ? 'valid' : 'invalid'},` + ` but was ${valid ? 'invalid' : 'valid'}`, ) .toBe(valid); }
{ "commit_id": "ea0d1ba7b", "end_byte": 24904, "start_byte": 21592, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-adapter.spec.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-formats.ts_0_553
/** * @license * Copyright Google LLC 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.dev/license */ import {MatDateFormats} from '@angular/material/core'; export const MAT_LUXON_DATE_FORMATS: MatDateFormats = { parse: { dateInput: 'D', timeInput: 't', }, display: { dateInput: 'D', timeInput: 't', monthYearLabel: 'LLL yyyy', dateA11yLabel: 'DD', monthYearA11yLabel: 'LLLL yyyy', timeOptionLabel: 't', }, };
{ "commit_id": "ea0d1ba7b", "end_byte": 553, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-formats.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-adapter.ts_0_1944
/** * @license * Copyright Google LLC 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.dev/license */ import {Injectable, InjectionToken, inject} from '@angular/core'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core'; import { DateTime as LuxonDateTime, Info as LuxonInfo, DateTimeOptions as LuxonDateTimeOptions, CalendarSystem as LuxonCalendarSystem, } from 'luxon'; /** Configurable options for the `LuxonDateAdapter`. */ export interface MatLuxonDateAdapterOptions { /** * Turns the use of utc dates on or off. * Changing this will change how Angular Material components like DatePicker output dates. */ useUtc: boolean; /** * Sets the first day of week. * Changing this will change how Angular Material components like DatePicker shows start of week. */ firstDayOfWeek: number; /** * Sets the output Calendar. * Changing this will change how Angular Material components like DatePicker output dates. */ defaultOutputCalendar: LuxonCalendarSystem; } /** InjectionToken for LuxonDateAdapter to configure options. */ export const MAT_LUXON_DATE_ADAPTER_OPTIONS = new InjectionToken<MatLuxonDateAdapterOptions>( 'MAT_LUXON_DATE_ADAPTER_OPTIONS', { providedIn: 'root', factory: MAT_LUXON_DATE_ADAPTER_OPTIONS_FACTORY, }, ); /** @docs-private */ export function MAT_LUXON_DATE_ADAPTER_OPTIONS_FACTORY(): MatLuxonDateAdapterOptions { return { useUtc: false, firstDayOfWeek: 0, defaultOutputCalendar: 'gregory', }; } /** Creates an array and fills it with values. */ function range<T>(length: number, valueFunction: (index: number) => T): T[] { const valuesArray = Array(length); for (let i = 0; i < length; i++) { valuesArray[i] = valueFunction(i); } return valuesArray; } /** Adapts Luxon Dates for use with Angular Material. */
{ "commit_id": "ea0d1ba7b", "end_byte": 1944, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-adapter.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-adapter.ts_1945_9809
@Injectable() export class LuxonDateAdapter extends DateAdapter<LuxonDateTime> { private _useUTC: boolean; private _firstDayOfWeek: number; private _defaultOutputCalendar: LuxonCalendarSystem; constructor(...args: unknown[]); constructor() { super(); const dateLocale = inject(MAT_DATE_LOCALE, {optional: true}); const options = inject<MatLuxonDateAdapterOptions>(MAT_LUXON_DATE_ADAPTER_OPTIONS, { optional: true, }); this._useUTC = !!options?.useUtc; this._firstDayOfWeek = options?.firstDayOfWeek || 0; this._defaultOutputCalendar = options?.defaultOutputCalendar || 'gregory'; this.setLocale(dateLocale || LuxonDateTime.local().locale); } getYear(date: LuxonDateTime): number { return date.year; } getMonth(date: LuxonDateTime): number { // Luxon works with 1-indexed months whereas our code expects 0-indexed. return date.month - 1; } getDate(date: LuxonDateTime): number { return date.day; } getDayOfWeek(date: LuxonDateTime): number { return date.weekday; } getMonthNames(style: 'long' | 'short' | 'narrow'): string[] { // Adding outputCalendar option, because LuxonInfo doesn't get effected by LuxonSettings return LuxonInfo.months(style, { locale: this.locale, outputCalendar: this._defaultOutputCalendar, }); } getDateNames(): string[] { // At the time of writing, Luxon doesn't offer similar // functionality so we have to fall back to the Intl API. const dtf = new Intl.DateTimeFormat(this.locale, {day: 'numeric', timeZone: 'utc'}); // Format a UTC date in order to avoid DST issues. return range(31, i => dtf.format(LuxonDateTime.utc(2017, 1, i + 1).toJSDate())); } getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] { // Note that we shift the array once, because Luxon returns Monday as the // first day of the week, whereas our logic assumes that it's Sunday. See: // https://moment.github.io/luxon/api-docs/index.html#infoweekdays const days = LuxonInfo.weekdays(style, {locale: this.locale}); days.unshift(days.pop()!); return days; } getYearName(date: LuxonDateTime): string { return date.toFormat('yyyy', this._getOptions()); } getFirstDayOfWeek(): number { return this._firstDayOfWeek; } getNumDaysInMonth(date: LuxonDateTime): number { return date.daysInMonth!; } clone(date: LuxonDateTime): LuxonDateTime { return LuxonDateTime.fromObject(date.toObject(), this._getOptions()); } createDate(year: number, month: number, date: number): LuxonDateTime { const options = this._getOptions(); if (month < 0 || month > 11) { throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`); } if (date < 1) { throw Error(`Invalid date "${date}". Date has to be greater than 0.`); } // Luxon uses 1-indexed months so we need to add one to the month. const result = this._useUTC ? LuxonDateTime.utc(year, month + 1, date, options) : LuxonDateTime.local(year, month + 1, date, options); if (!this.isValid(result)) { throw Error(`Invalid date "${date}". Reason: "${result.invalidReason}".`); } return result; } today(): LuxonDateTime { const options = this._getOptions(); return this._useUTC ? LuxonDateTime.utc(options) : LuxonDateTime.local(options); } parse(value: any, parseFormat: string | string[]): LuxonDateTime | null { const options: LuxonDateTimeOptions = this._getOptions(); if (typeof value == 'string' && value.length > 0) { const iso8601Date = LuxonDateTime.fromISO(value, options); if (this.isValid(iso8601Date)) { return iso8601Date; } const formats = Array.isArray(parseFormat) ? parseFormat : [parseFormat]; if (!parseFormat.length) { throw Error('Formats array must not be empty.'); } for (const format of formats) { const fromFormat = LuxonDateTime.fromFormat(value, format, options); if (this.isValid(fromFormat)) { return fromFormat; } } return this.invalid(); } else if (typeof value === 'number') { return LuxonDateTime.fromMillis(value, options); } else if (value instanceof Date) { return LuxonDateTime.fromJSDate(value, options); } else if (value instanceof LuxonDateTime) { return LuxonDateTime.fromMillis(value.toMillis(), options); } return null; } format(date: LuxonDateTime, displayFormat: string): string { if (!this.isValid(date)) { throw Error('LuxonDateAdapter: Cannot format invalid date.'); } if (this._useUTC) { return date.setLocale(this.locale).setZone('utc').toFormat(displayFormat); } else { return date.setLocale(this.locale).toFormat(displayFormat); } } addCalendarYears(date: LuxonDateTime, years: number): LuxonDateTime { return date.reconfigure(this._getOptions()).plus({years}); } addCalendarMonths(date: LuxonDateTime, months: number): LuxonDateTime { return date.reconfigure(this._getOptions()).plus({months}); } addCalendarDays(date: LuxonDateTime, days: number): LuxonDateTime { return date.reconfigure(this._getOptions()).plus({days}); } toIso8601(date: LuxonDateTime): string { return date.toISO()!; } /** * Returns the given value if given a valid Luxon or null. Deserializes valid ISO 8601 strings * (https://www.ietf.org/rfc/rfc3339.txt) and valid Date objects into valid DateTime and empty * string into null. Returns an invalid date for all other values. */ override deserialize(value: any): LuxonDateTime | null { const options = this._getOptions(); let date: LuxonDateTime | undefined; if (value instanceof Date) { date = LuxonDateTime.fromJSDate(value, options); } if (typeof value === 'string') { if (!value) { return null; } date = LuxonDateTime.fromISO(value, options); } if (date && this.isValid(date)) { return date; } return super.deserialize(value); } isDateInstance(obj: any): boolean { return obj instanceof LuxonDateTime; } isValid(date: LuxonDateTime): boolean { return date.isValid; } invalid(): LuxonDateTime { return LuxonDateTime.invalid('Invalid Luxon DateTime object.'); } override setTime( target: LuxonDateTime, hours: number, minutes: number, seconds: number, ): LuxonDateTime { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (hours < 0 || hours > 23) { throw Error(`Invalid hours "${hours}". Hours value must be between 0 and 23.`); } if (minutes < 0 || minutes > 59) { throw Error(`Invalid minutes "${minutes}". Minutes value must be between 0 and 59.`); } if (seconds < 0 || seconds > 59) { throw Error(`Invalid seconds "${seconds}". Seconds value must be between 0 and 59.`); } } return this.clone(target).set({ hour: hours, minute: minutes, second: seconds, millisecond: 0, }); } override getHours(date: LuxonDateTime): number { return date.hour; } override getMinutes(date: LuxonDateTime): number { return date.minute; } override getSeconds(date: LuxonDateTime): number { return date.second; } override parseTime(value: any, parseFormat: string | string[]): LuxonDateTime | null { const result = this.parse(value, parseFormat); if ((!result || !this.isValid(result)) && typeof value === 'string') { // It seems like Luxon doesn't work well cross-browser for strings that have // additional characters around the time. Try parsing without those characters. return this.parse(value.replace(/[^0-9:(AM|PM)]/gi, ''), parseFormat) || result; } return result; }
{ "commit_id": "ea0d1ba7b", "end_byte": 9809, "start_byte": 1945, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-adapter.ts" }
components/src/material-luxon-adapter/adapter/luxon-date-adapter.ts_9813_10251
override addSeconds(date: LuxonDateTime, amount: number): LuxonDateTime { return date.reconfigure(this._getOptions()).plus({seconds: amount}); } /** Gets the options that should be used when constructing a new `DateTime` object. */ private _getOptions(): LuxonDateTimeOptions { return { zone: this._useUTC ? 'utc' : undefined, locale: this.locale, outputCalendar: this._defaultOutputCalendar, }; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 10251, "start_byte": 9813, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/luxon-date-adapter.ts" }
components/src/material-luxon-adapter/adapter/index.ts_0_1210
/** * @license * Copyright Google LLC 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.dev/license */ import {NgModule, Provider} from '@angular/core'; import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE, MatDateFormats, } from '@angular/material/core'; import {MAT_LUXON_DATE_ADAPTER_OPTIONS, LuxonDateAdapter} from './luxon-date-adapter'; import {MAT_LUXON_DATE_FORMATS} from './luxon-date-formats'; export * from './luxon-date-adapter'; export * from './luxon-date-formats'; @NgModule({ providers: [ { provide: DateAdapter, useClass: LuxonDateAdapter, deps: [MAT_DATE_LOCALE, MAT_LUXON_DATE_ADAPTER_OPTIONS], }, ], }) export class LuxonDateModule {} @NgModule({ providers: [provideLuxonDateAdapter()], }) export class MatLuxonDateModule {} export function provideLuxonDateAdapter( formats: MatDateFormats = MAT_LUXON_DATE_FORMATS, ): Provider[] { return [ { provide: DateAdapter, useClass: LuxonDateAdapter, deps: [MAT_DATE_LOCALE, MAT_LUXON_DATE_ADAPTER_OPTIONS], }, {provide: MAT_DATE_FORMATS, useValue: formats}, ]; }
{ "commit_id": "ea0d1ba7b", "end_byte": 1210, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/adapter/index.ts" }
components/src/material-luxon-adapter/schematics/BUILD.bazel_0_908
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") load("//tools:defaults.bzl", "pkg_npm", "ts_library") package(default_visibility = ["//visibility:public"]) copy_to_bin( name = "schematics_assets", srcs = glob(["**/*.json"]), ) ts_library( name = "schematics", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), # Schematics can not yet run in ESM module. For now we continue to use CommonJS. # TODO(ESM): remove this once the Angular CLI supports ESM schematics. devmode_module = "commonjs", prodmode_module = "commonjs", deps = [ "@npm//@angular-devkit/schematics", "@npm//@types/node", ], ) # This package is intended to be combined into the main @angular/material-luxon-adapter package as a dep. pkg_npm( name = "npm_package", deps = [ ":schematics", ":schematics_assets", ], )
{ "commit_id": "ea0d1ba7b", "end_byte": 908, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/schematics/BUILD.bazel" }
components/src/material-luxon-adapter/schematics/ng-add/index.ts_0_455
/** * @license * Copyright Google LLC 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.dev/license */ import {Rule} from '@angular-devkit/schematics'; export default function (): Rule { // Noop schematic so the CLI doesn't throw if users try to `ng add` this package. // Also allows us to add more functionality in the future. return () => {}; }
{ "commit_id": "ea0d1ba7b", "end_byte": 455, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-luxon-adapter/schematics/ng-add/index.ts" }
components/src/e2e-app/index.html_0_807
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Angular Material</title> <base href="/"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <link href="theme.css" rel="stylesheet"> </head> <body class="mat-typography"> <e2e-app>Loading...</e2e-app> <span class="sibling">I am a sibling!</span> <script src="zone.js/bundles/zone.umd.min.js"></script> <script src="kagekiri/dist/kagekiri.umd.min.js"></script> <script src="bundles/e2e-app/main.js" type="module"></script> </body> </html>
{ "commit_id": "ea0d1ba7b", "end_byte": 807, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/index.html" }
components/src/e2e-app/main.ts_0_1119
import {enableProdMode} from '@angular/core'; import {bootstrapApplication, provideProtractorTestingSupport} from '@angular/platform-browser'; import {provideNoopAnimations} from '@angular/platform-browser/animations'; import {provideRouter} from '@angular/router'; import {E2eApp} from './components/e2e-app/e2e-app'; import {Home} from './components/home'; import {BlockScrollStrategyE2E} from './components/block-scroll-strategy/block-scroll-strategy-e2e'; import {ComponentHarnessE2e} from './components/component-harness-e2e'; import {SliderE2e} from './components/slider-e2e'; import {VirtualScrollE2E} from './components/virtual-scroll/virtual-scroll-e2e'; enableProdMode(); bootstrapApplication(E2eApp, { providers: [ provideNoopAnimations(), provideProtractorTestingSupport(), provideRouter([ {path: '', component: Home}, {path: 'block-scroll-strategy', component: BlockScrollStrategyE2E}, {path: 'component-harness', component: ComponentHarnessE2e}, {path: 'slider', component: SliderE2e}, {path: 'virtual-scroll', component: VirtualScrollE2E}, ]), ], });
{ "commit_id": "ea0d1ba7b", "end_byte": 1119, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/main.ts" }
components/src/e2e-app/test_suite.bzl_0_402
load("//tools:defaults.bzl", "protractor_web_test_suite") def e2e_test_suite(name, data = [], tags = ["e2e"], deps = []): protractor_web_test_suite( name = name, configuration = "//src/e2e-app:protractor.conf.js", data = data, on_prepare = "//src/e2e-app:start-devserver.js", server = "//src/e2e-app:server", tags = tags, deps = deps, )
{ "commit_id": "ea0d1ba7b", "end_byte": 402, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/test_suite.bzl" }
components/src/e2e-app/start-devserver.js_0_1016
const protractor = require('protractor'); // Note: We need to specify an explicit file extension here because otherwise // the Bazel-patched NodeJS module resolution would resolve to the `.mjs` file // in non-sandbox environments (as usually with Bazel and Windows). const utils = require('@bazel/protractor/protractor-utils.js'); /** * Called by Protractor before starting any tests. This is script is responsible for * starting up the devserver and updating the Protractor base URL to the proper port. */ module.exports = async function (config) { const {port} = await utils.runServer(config.workspace, config.server, '--port', []); const baseUrl = `http://localhost:${port}`; const processedConfig = await protractor.browser.getProcessedConfig(); // Update the protractor "baseUrl" to match the new random TCP port. We need random TCP ports // because otherwise Bazel could not execute protractor tests concurrently. protractor.browser.baseUrl = baseUrl; processedConfig.baseUrl = baseUrl; };
{ "commit_id": "ea0d1ba7b", "end_byte": 1016, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/start-devserver.js" }
components/src/e2e-app/protractor.conf.js_0_365
exports.config = { useAllAngular2AppRoots: true, allScriptsTimeout: 120000, getPageTimeout: 120000, jasmineNodeOpts: { defaultTimeoutInterval: 120000, }, // Since we want to use async/await we don't want to mix up with selenium's promise // manager. In order to enforce this, we disable the promise manager. SELENIUM_PROMISE_MANAGER: false, };
{ "commit_id": "ea0d1ba7b", "end_byte": 365, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/protractor.conf.js" }
components/src/e2e-app/BUILD.bazel_0_2567
load("//tools:defaults.bzl", "devmode_esbuild", "esbuild_config", "http_server", "ng_module", "sass_binary") load("//src/components-examples:config.bzl", "ALL_EXAMPLES") load("//tools/angular:index.bzl", "LINKER_PROCESSED_FW_PACKAGES") package(default_visibility = ["//visibility:public"]) # List of dependencies that are referenced in the `index.html` file. devserverIndexHtmlDependencies = [ "@npm//zone.js", "@npm//kagekiri", "//src/material/prebuilt-themes:azure-blue", ":index.html", ":theme", ] exports_files([ "protractor.conf.js", "start-devserver.js", "devserver-configure.js", ]) ng_module( name = "e2e-app", testonly = True, srcs = glob( ["**/*.ts"], ), assets = glob( [ "**/*.html", "**/*.css", ], exclude = ["index.html"], ), deps = [ "//src/cdk-experimental/scrolling", "//src/cdk/overlay", "//src/cdk/scrolling", "//src/cdk/testing/tests:test_components", "//src/components-examples/private", "//src/material/core", "//src/material/slider", "@npm//@angular/animations", "@npm//@angular/core", "@npm//@angular/forms", "@npm//@angular/platform-browser", "@npm//@angular/router", ], ) sass_binary( name = "theme", src = "theme.scss", deps = [ "//src/material:sass_lib", "//src/material-experimental:sass_lib", "//src/material/core:theming_scss_lib", ], ) esbuild_config( name = "esbuild_config", testonly = True, config_file = "esbuild.config.mjs", ) devmode_esbuild( name = "bundles", testonly = True, config = ":esbuild_config", entry_points = [":main.ts"] + ["%s:index.ts" % e for e in ALL_EXAMPLES], platform = "browser", splitting = True, # We cannot use `ES2017` or higher as that would result in `async/await` not being downleveled. # ZoneJS needs to be able to intercept these as otherwise change detection would not work properly. target = "es2016", # Note: We add all linker-processed FW packages as dependencies here so that ESBuild will # map all framework packages to their linker-processed bundles from `tools/angular`. deps = LINKER_PROCESSED_FW_PACKAGES + [ ":e2e-app", ], ) http_server( name = "server", testonly = True, srcs = devserverIndexHtmlDependencies, additional_root_paths = [ "npm/node_modules", ], tags = ["manual"], deps = [ ":bundles", ], )
{ "commit_id": "ea0d1ba7b", "end_byte": 2567, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/BUILD.bazel" }
components/src/e2e-app/esbuild.config.mjs_0_271
/** * @license * Copyright Google LLC 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.dev/license */ export default { resolveExtensions: ['.js'], format: 'esm', };
{ "commit_id": "ea0d1ba7b", "end_byte": 271, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/esbuild.config.mjs" }
components/src/e2e-app/theme.scss_0_300
@use '@angular/material' as mat; $theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$azure-palette, tertiary: mat.$blue-palette, ), density: ( scale: 0, ) )); html { @include mat.all-component-themes($theme); } @include mat.typography-hierarchy($theme);
{ "commit_id": "ea0d1ba7b", "end_byte": 300, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/theme.scss" }
components/src/e2e-app/components/component-harness-e2e.ts_0_636
import {Component} from '@angular/core'; import {TestMainComponent} from '@angular/cdk/testing/tests'; @Component({ selector: 'component-harness-e2e', template: ` <button id="reset-state" (click)="reset()">Reset state</button> @if (isShown) { <test-main></test-main> } `, imports: [TestMainComponent], }) export class ComponentHarnessE2e { protected isShown = true; /** * Resets the test component state without the need to refresh the page. * Used by Webdriver integration tests. */ protected reset(): void { this.isShown = false; setTimeout(() => (this.isShown = true), 100); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 636, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/component-harness-e2e.ts" }
components/src/e2e-app/components/home.ts_0_150
import {Component} from '@angular/core'; @Component({ selector: 'home', template: `<p>Welcome to the e2e tests app</p>`, }) export class Home {}
{ "commit_id": "ea0d1ba7b", "end_byte": 150, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/home.ts" }
components/src/e2e-app/components/slider-e2e.ts_0_911
/** * @license * Copyright Google LLC 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.dev/license */ import {Component} from '@angular/core'; import {MatSliderModule} from '@angular/material/slider'; @Component({ selector: 'slider-e2e', template: ` <mat-slider id="standard-slider" discrete> <input aria-label="Standard slider" matSliderThumb> </mat-slider> <mat-slider id="disabled-slider" disabled> <input aria-label="Disabled slider" matSliderThumb> </mat-slider> <mat-slider id="range-slider"> <input aria-label="Range slider start thumb" matSliderStartThumb> <input aria-label="Range slider end thumb" matSliderEndThumb> </mat-slider> `, styles: '.mat-mdc-slider { width: 148px; }', imports: [MatSliderModule], }) export class SliderE2e {}
{ "commit_id": "ea0d1ba7b", "end_byte": 911, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/slider-e2e.ts" }
components/src/e2e-app/components/virtual-scroll/virtual-scroll-e2e.ts_0_625
import {Component} from '@angular/core'; import {ScrollingModule} from '@angular/cdk/scrolling'; import {ScrollingModule as ExperimentalScrollingModule} from '@angular/cdk-experimental/scrolling'; const itemSizeSample = [100, 25, 50, 50, 100, 200, 75, 100, 50, 250]; @Component({ selector: 'virtual-scroll-e2e', templateUrl: 'virtual-scroll-e2e.html', styleUrl: 'virtual-scroll-e2e.css', imports: [ScrollingModule, ExperimentalScrollingModule], }) export class VirtualScrollE2E { uniformItems = Array(1000).fill(50); variableItems = Array(100) .fill(0) .reduce(acc => acc.concat(itemSizeSample), []); }
{ "commit_id": "ea0d1ba7b", "end_byte": 625, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/virtual-scroll/virtual-scroll-e2e.ts" }
components/src/e2e-app/components/virtual-scroll/virtual-scroll-e2e.html_0_855
<section class="demo-virtual-scroll-uniform-size"> <h3>Uniform size</h3> <cdk-virtual-scroll-viewport class="demo-viewport" autosize tabindex="0"> <div *cdkVirtualFor="let size of uniformItems; let i = index; let odd = odd" class="demo-item" [style.height.px]="size" [class.demo-odd]="odd" [attr.data-index]="i"> Uniform Item #{{i}} - ({{size}}px) </div> </cdk-virtual-scroll-viewport> </section> <section class="demo-virtual-scroll-variable-size"> <h3>Random size</h3> <cdk-virtual-scroll-viewport class="demo-viewport" autosize tabindex="0"> <div *cdkVirtualFor="let size of variableItems; let i = index; let odd = odd" class="demo-item" [style.height.px]="size" [class.demo-odd]="odd" [attr.data-index]="i"> Variable Item #{{i}} - ({{size}}px) </div> </cdk-virtual-scroll-viewport> </section>
{ "commit_id": "ea0d1ba7b", "end_byte": 855, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/virtual-scroll/virtual-scroll-e2e.html" }
components/src/e2e-app/components/virtual-scroll/virtual-scroll-e2e.css_0_157
.demo-viewport { height: 300px; width: 300px; box-shadow: 0 0 0 1px black; } .demo-item { background: magenta; } .demo-odd { background: cyan; }
{ "commit_id": "ea0d1ba7b", "end_byte": 157, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/virtual-scroll/virtual-scroll-e2e.css" }
components/src/e2e-app/components/block-scroll-strategy/block-scroll-strategy-e2e.ts_0_581
import {Component, inject} from '@angular/core'; import {Overlay, OverlayContainer} from '@angular/cdk/overlay'; import {ScrollingModule} from '@angular/cdk/scrolling'; @Component({ selector: 'block-scroll-strategy-e2e', templateUrl: 'block-scroll-strategy-e2e.html', styleUrl: 'block-scroll-strategy-e2e.css', imports: [ScrollingModule], }) export class BlockScrollStrategyE2E { scrollStrategy = inject(Overlay).scrollStrategies.block(); constructor() { // This loads the structural styles for the test. inject(OverlayContainer).getContainerElement(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 581, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/block-scroll-strategy/block-scroll-strategy-e2e.ts" }
components/src/e2e-app/components/block-scroll-strategy/block-scroll-strategy-e2e.css_0_392
.demo-spacer { background: #3f51b5; margin-bottom: 10px; } .demo-spacer-vertical { width: 100px; height: 3000px; } .demo-spacer-horizontal { width: 3000px; height: 100px; } .demo-scroller { width: 100px; height: 100px; overflow: auto; position: absolute; top: 100px; left: 200px; } .demo-scroller-spacer { width: 200px; height: 200px; background: #ff4081; }
{ "commit_id": "ea0d1ba7b", "end_byte": 392, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/block-scroll-strategy/block-scroll-strategy-e2e.css" }
components/src/e2e-app/components/block-scroll-strategy/block-scroll-strategy-e2e.html_0_485
<p> <button id="enable" (click)="scrollStrategy.enable()">Enable scroll blocking</button> <button id="disable" (click)="scrollStrategy.disable()">Disable scroll blocking</button> </p> <div class="demo-spacer demo-spacer-vertical"></div> <!-- this one needs a tabindex so protractor can trigger key presses inside it --> <div class="demo-scroller" id="scroller" tabindex="-1"> <div class="demo-scroller-spacer"></div> </div> <div class="demo-spacer demo-spacer-horizontal"></div>
{ "commit_id": "ea0d1ba7b", "end_byte": 485, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/block-scroll-strategy/block-scroll-strategy-e2e.html" }
components/src/e2e-app/components/e2e-app/e2e-app.ts_0_628
import {Component, ViewEncapsulation} from '@angular/core'; import {MatListModule} from '@angular/material/list'; import {RouterLink, RouterOutlet} from '@angular/router'; @Component({ selector: 'e2e-app', templateUrl: 'e2e-app.html', encapsulation: ViewEncapsulation.None, imports: [MatListModule, RouterLink, RouterOutlet], }) export class E2eApp { showLinks = false; navLinks = [ {path: 'block-scroll-strategy', title: 'Block Scroll Strategy'}, {path: 'component-harness', title: 'Component Harness'}, {path: 'slider', title: 'Slider'}, {path: 'virtual-scroll', title: 'Virtual Scroll'}, ]; }
{ "commit_id": "ea0d1ba7b", "end_byte": 628, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/e2e-app/e2e-app.ts" }
components/src/e2e-app/components/e2e-app/e2e-app.html_0_339
<button (click)="showLinks = !showLinks">Toggle Navigation Links</button> <main> @if (showLinks) { <mat-nav-list (click)="showLinks = false"> @for (link of navLinks; track link) { <a mat-list-item [routerLink]="[link.path]">{{link.title}}</a> } </mat-nav-list> } <router-outlet></router-outlet> </main>
{ "commit_id": "ea0d1ba7b", "end_byte": 339, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/e2e-app/components/e2e-app/e2e-app.html" }
components/src/material-moment-adapter/public-api.ts_0_237
/** * @license * Copyright Google LLC 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.dev/license */ export * from './adapter/index';
{ "commit_id": "ea0d1ba7b", "end_byte": 237, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/public-api.ts" }
components/src/material-moment-adapter/BUILD.bazel_0_1029
load("//tools:defaults.bzl", "ng_module", "ng_package", "ng_test_library", "ng_web_test_suite") package(default_visibility = ["//visibility:public"]) ng_module( name = "material-moment-adapter", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src:dev_mode_types", "//src/material/core", "@npm//@angular/core", "@npm//moment", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":material-moment-adapter", "//src/material/core", "//src/material/testing", "@npm//moment", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_test_sources", ], ) ng_package( name = "npm_package", srcs = ["package.json"], nested_packages = ["//src/material-moment-adapter/schematics:npm_package"], tags = ["release-package"], deps = [":material-moment-adapter"], )
{ "commit_id": "ea0d1ba7b", "end_byte": 1029, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/BUILD.bazel" }