content
stringlengths
28
1.34M
import { Injectable } from '@angular/core'; import { Type } from '@vendure/common/lib/shared-types'; import { from, Observable } from 'rxjs'; import { mergeMap } from 'rxjs/operators'; import { ModalDialogComponent } from '../../shared/components/modal-dialog/modal-dialog.component'; import { SimpleDialogComponent } from '../../shared/components/simple-dialog/simple-dialog.component'; import { OverlayHostService } from '../overlay-host/overlay-host.service'; import { Dialog, DialogConfig, ModalOptions } from './modal.types'; /** * @description * This service is responsible for instantiating a ModalDialog component and * embedding the specified component within. * * @docsCategory services * @docsPage ModalService * @docsWeight 0 */ @Injectable({ providedIn: 'root', }) export class ModalService { constructor(private overlayHostService: OverlayHostService) {} /** * @description * Create a modal from a component. The component must implement the {@link Dialog} interface. * Additionally, the component should include templates for the title and the buttons to be * displayed in the modal dialog. See example: * * @example * ```ts * class MyDialog implements Dialog { * resolveWith: (result?: any) => void; * * okay() { * doSomeWork().subscribe(result => { * this.resolveWith(result); * }) * } * * cancel() { * this.resolveWith(false); * } * } * ``` * * @example * ```html * <ng-template vdrDialogTitle>Title of the modal</ng-template> * * <p> * My Content * </p> * * <ng-template vdrDialogButtons> * <button type="button" * class="btn" * (click)="cancel()">Cancel</button> * <button type="button" * class="btn btn-primary" * (click)="okay()">Okay</button> * </ng-template> * ``` */ fromComponent<T extends Dialog<any>, R>( component: Type<T> & Type<Dialog<R>>, options?: ModalOptions<T>, ): Observable<R | undefined> { return from(this.overlayHostService.getHostView()).pipe( mergeMap(hostView => { const modalComponentRef = hostView.createComponent(ModalDialogComponent); const modalInstance: ModalDialogComponent<any> = modalComponentRef.instance; modalInstance.childComponentType = component; modalInstance.options = options; return new Observable<R>(subscriber => { modalInstance.closeModal = (result: R) => { modalComponentRef.destroy(); subscriber.next(result); subscriber.complete(); }; }); }), ); } /** * @description * Displays a modal dialog with the provided title, body and buttons. */ dialog<T>(config: DialogConfig<T>): Observable<T | undefined> { return this.fromComponent(SimpleDialogComponent, { locals: config, size: config.size, }); } }
/** * @description * Any component intended to be used with the ModalService.fromComponent() method must implement * this interface. * * @docsCategory services * @docsPage ModalService */ export interface Dialog<R = any> { /** * @description * Function to be invoked in order to close the dialog when the action is complete. * The Observable returned from the .fromComponent() method will emit the value passed * to this method and then complete. */ resolveWith: (result?: R) => void; } export interface DialogButtonConfig<T> { label: string; type: 'secondary' | 'primary' | 'danger'; translationVars?: Record<string, string | number>; returnValue?: T; } /** * @description * Configures a generic modal dialog. * * @docsCategory services * @docsPage ModalService */ export interface DialogConfig<T> { title: string; body?: string; translationVars?: { [key: string]: string | number }; buttons: Array<DialogButtonConfig<T>>; size?: 'sm' | 'md' | 'lg' | 'xl'; } /** * @description * Options to configure the behaviour of the modal. * * @docsCategory services * @docsPage ModalService */ export interface ModalOptions<T> { /** * @description * Sets the width of the dialog */ size?: 'sm' | 'md' | 'lg' | 'xl'; /** * @description * Sets the vertical alignment of the dialog */ verticalAlign?: 'top' | 'center' | 'bottom'; /** * @description * When true, the "x" icon is shown * and clicking it or the mask will close the dialog */ closable?: boolean; /** * @description * Values to be passed directly to the component being instantiated inside the dialog. */ locals?: Partial<T>; }
import { Injector } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { ActionBarLocationId } from '../../common/component-registry-types'; import { DataService } from '../../data/providers/data.service'; import { NotificationService } from '../notification/notification.service'; export type NavMenuBadgeType = 'none' | 'info' | 'success' | 'warning' | 'error'; /** * @description * A color-coded notification badge which will be displayed by the * NavMenuItem's icon. * * @docsCategory nav-menu * @docsPage navigation-types */ export interface NavMenuBadge { type: NavMenuBadgeType; /** * @description * If true, the badge will propagate to the NavMenuItem's * parent section, displaying a notification badge next * to the section name. */ propagateToSection?: boolean; } /** * @description * A NavMenuItem is a menu item in the main (left-hand side) nav * bar. * * @docsCategory nav-menu */ export interface NavMenuItem { id: string; label: string; routerLink: RouterLinkDefinition; onClick?: (event: MouseEvent) => void; icon?: string; /** * Control the display of this item based on the user permissions. */ requiresPermission?: string | ((userPermissions: string[]) => boolean); statusBadge?: Observable<NavMenuBadge>; } /** * @description * A NavMenuSection is a grouping of links in the main * (left-hand side) nav bar. * * @docsCategory nav-menu */ export interface NavMenuSection { id: string; label: string; items: NavMenuItem[]; icon?: string; displayMode?: 'regular' | 'settings'; /** * @description * Control the display of this item based on the user permissions. Note: if you attempt to pass a * {@link PermissionDefinition} object, you will get a compilation error. Instead, pass the plain * string version. For example, if the permission is defined as: * ```ts * export const MyPermission = new PermissionDefinition('ProductReview'); * ``` * then the generated permission strings will be: * * - `CreateProductReview` * - `ReadProductReview` * - `UpdateProductReview` * - `DeleteProductReview` */ requiresPermission?: string | ((userPermissions: string[]) => boolean); collapsible?: boolean; collapsedByDefault?: boolean; } /** * @description * Providers & data available to the `onClick` & `buttonState` functions of an {@link ActionBarItem}, * {@link ActionBarDropdownMenuItem} or {@link NavMenuItem}. * * @docsCategory action-bar */ export interface ActionBarContext { /** * @description * The router's [ActivatedRoute](https://angular.dev/guide/routing/router-reference#activated-route) object for * the current route. This object contains information about the route, its parameters, and additional data * associated with the route. */ route: ActivatedRoute; /** * @description * The Angular [Injector](https://angular.dev/api/core/Injector) which can be used to get instances * of services and other providers available in the application. */ injector: Injector; /** * @description * The [DataService](/reference/admin-ui-api/services/data-service), which provides methods for querying the * server-side data. */ dataService: DataService; /** * @description * The [NotificationService](/reference/admin-ui-api/services/notification-service), which provides methods for * displaying notifications to the user. */ notificationService: NotificationService; /** * @description * An observable of the current entity in a detail view. In a list view the observable will not emit any values. * * @example * ```ts * addActionBarDropdownMenuItem({ * id: 'print-invoice', * locationId: 'order-detail', * label: 'Print Invoice', * icon: 'printer', * buttonState: context => { * // highlight-start * return context.entity$.pipe( * map((order) => { * return order?.state === 'PaymentSettled' * ? { disabled: false, visible: true } * : { disabled: true, visible: true }; * }), * ); * // highlight-end * }, * requiresPermission: ['UpdateOrder'], * }), * ``` * * @since 2.2.0 */ entity$: Observable<Record<string, any> | undefined>; } export interface ActionBarButtonState { disabled: boolean; visible: boolean; } /** * @description * A button in the ActionBar area at the top of one of the list or detail views. * * @docsCategory action-bar */ export interface ActionBarItem { /** * @description * A unique identifier for the item. */ id: string; /** * @description * The label to display for the item. This can also be a translation token, * e.g. `invoice-plugin.print-invoice`. */ label: string; /** * @description * The location in the UI where this button should be displayed. */ locationId: ActionBarLocationId; /** * @description * Deprecated since v2.1.0 - use `buttonState` instead. * @deprecated - use `buttonState` instead. */ disabled?: Observable<boolean>; /** * @description * A function which returns an observable of the button state, allowing you to * dynamically enable/disable or show/hide the button. * * @since 2.1.0 */ buttonState?: (context: ActionBarContext) => Observable<ActionBarButtonState>; onClick?: (event: MouseEvent, context: ActionBarContext) => void; routerLink?: RouterLinkDefinition; buttonColor?: 'primary' | 'success' | 'warning'; buttonStyle?: 'solid' | 'outline' | 'link'; /** * @description * An optional icon to display in the button. The icon * should be a valid shape name from the [Clarity Icons](https://core.clarity.design/foundation/icons/shapes/) * set. */ icon?: string; /** * @description * Control the display of this item based on the user permissions. Note: if you attempt to pass a * {@link PermissionDefinition} object, you will get a compilation error. Instead, pass the plain * string version. For example, if the permission is defined as: * * ```ts * export const MyPermission = new PermissionDefinition('ProductReview'); * ``` * * then the generated permission strings will be: * * - `CreateProductReview` * - `ReadProductReview` * - `UpdateProductReview` * - `DeleteProductReview` */ requiresPermission?: string | string[]; } /** * @description * A dropdown menu item in the ActionBar area at the top of one of the list or detail views. * * @docsCategory action-bar * @since 2.2.0 */ export interface ActionBarDropdownMenuItem { /** * @description * A unique identifier for the item. */ id: string; /** * @description * The label to display for the item. This can also be a translation token, * e.g. `invoice-plugin.print-invoice`. */ label: string; /** * @description * The location in the UI where this menu item should be displayed. */ locationId: ActionBarLocationId; /** * @description * Whether to render a divider above this item. */ hasDivider?: boolean; /** * @description * A function which returns an observable of the button state, allowing you to * dynamically enable/disable or show/hide the button. */ buttonState?: (context: ActionBarContext) => Observable<ActionBarButtonState | undefined>; onClick?: (event: MouseEvent, context: ActionBarContext) => void; routerLink?: RouterLinkDefinition; /** * @description * An optional icon to display with the item. The icon * should be a valid shape name from the [Clarity Icons](https://core.clarity.design/foundation/icons/shapes/) * set. */ icon?: string; /** * @description * Control the display of this item based on the user permissions. Note: if you attempt to pass a * {@link PermissionDefinition} object, you will get a compilation error. Instead, pass the plain * string version. For example, if the permission is defined as: * * ```ts * export const MyPermission = new PermissionDefinition('ProductReview'); * ``` * then the generated permission strings will be: * * - `CreateProductReview` * - `ReadProductReview` * - `UpdateProductReview` * - `DeleteProductReview` */ requiresPermission?: string | string[]; } /** * @description * A function which returns the router link for an {@link ActionBarItem} or {@link NavMenuItem}. * * @docsCategory action-bar */ export type RouterLinkDefinition = ((route: ActivatedRoute, context: ActionBarContext) => any[]) | any[];
/* eslint-disable @typescript-eslint/no-non-null-assertion, no-console */ import { TestBed } from '@angular/core/testing'; import { take } from 'rxjs/operators'; import { NavMenuSection } from './nav-builder-types'; import { NavBuilderService } from './nav-builder.service'; describe('NavBuilderService', () => { let service: NavBuilderService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(NavBuilderService); }); it('defineNavMenuSections', done => { service.defineNavMenuSections(getBaseNav()); service.menuConfig$.pipe(take(1)).subscribe(result => { expect(result).toEqual(getBaseNav()); done(); }); }); describe('addNavMenuSection', () => { it('adding new section to end', done => { service.defineNavMenuSections(getBaseNav()); service.addNavMenuSection({ id: 'reports', label: 'Reports', items: [], }); service.menuConfig$.pipe(take(1)).subscribe(result => { expect(result.map(section => section.id)).toEqual(['catalog', 'sales', 'reports']); done(); }); }); it('adding new section before', done => { service.defineNavMenuSections(getBaseNav()); service.addNavMenuSection( { id: 'reports', label: 'Reports', items: [], }, 'sales', ); service.menuConfig$.pipe(take(1)).subscribe(result => { expect(result.map(section => section.id)).toEqual(['catalog', 'reports', 'sales']); done(); }); }); it('replacing an existing section', done => { service.defineNavMenuSections(getBaseNav()); service.addNavMenuSection({ id: 'sales', label: 'Custom Sales', items: [], }); service.menuConfig$.pipe(take(1)).subscribe(result => { expect(result.map(section => section.id)).toEqual(['catalog', 'sales']); expect(result[1].label).toBe('Custom Sales'); done(); }); }); it('replacing and moving', done => { service.defineNavMenuSections(getBaseNav()); service.addNavMenuSection( { id: 'sales', label: 'Custom Sales', items: [], }, 'catalog', ); service.menuConfig$.pipe(take(1)).subscribe(result => { expect(result.map(section => section.id)).toEqual(['sales', 'catalog']); expect(result[0].label).toBe('Custom Sales'); done(); }); }); }); describe('addNavMenuItem()', () => { it('adding to non-existent section', done => { spyOn(console, 'error'); service.defineNavMenuSections(getBaseNav()); service.addNavMenuItem( { id: 'fulfillments', label: 'Fulfillments', routerLink: ['/extensions', 'fulfillments'], }, 'farm-tools', ); service.menuConfig$.pipe(take(1)).subscribe(result => { expect(console.error).toHaveBeenCalledWith( 'Could not add menu item "fulfillments", section "farm-tools" does not exist', ); done(); }); }); it('adding to end of section', done => { service.defineNavMenuSections(getBaseNav()); service.addNavMenuItem( { id: 'fulfillments', label: 'Fulfillments', routerLink: ['/extensions', 'fulfillments'], }, 'sales', ); service.menuConfig$.pipe(take(1)).subscribe(result => { const salesSection = result.find(r => r.id === 'sales')!; expect(salesSection.items.map(item => item.id)).toEqual(['orders', 'fulfillments']); done(); }); }); it('adding before existing item', done => { service.defineNavMenuSections(getBaseNav()); service.addNavMenuItem( { id: 'fulfillments', label: 'Fulfillments', routerLink: ['/extensions', 'fulfillments'], }, 'sales', 'orders', ); service.menuConfig$.pipe(take(1)).subscribe(result => { const salesSection = result.find(r => r.id === 'sales')!; expect(salesSection.items.map(item => item.id)).toEqual(['fulfillments', 'orders']); done(); }); }); it('replacing existing item', done => { service.defineNavMenuSections(getBaseNav()); service.addNavMenuItem( { id: 'facets', label: 'Custom Facets', routerLink: ['/custom-facets'], }, 'catalog', ); service.menuConfig$.pipe(take(1)).subscribe(result => { const catalogSection = result.find(r => r.id === 'catalog')!; expect(catalogSection.items.map(item => item.id)).toEqual(['products', 'facets']); expect(catalogSection.items[1].label).toBe('Custom Facets'); done(); }); }); it('replacing existing item and moving', done => { service.defineNavMenuSections(getBaseNav()); service.addNavMenuItem( { id: 'facets', label: 'Custom Facets', routerLink: ['/custom-facets'], }, 'catalog', 'products', ); service.menuConfig$.pipe(take(1)).subscribe(result => { const catalogSection = result.find(r => r.id === 'catalog')!; expect(catalogSection.items.map(item => item.id)).toEqual(['facets', 'products']); expect(catalogSection.items[0].label).toBe('Custom Facets'); done(); }); }); }); function getBaseNav(): NavMenuSection[] { return [ { id: 'catalog', label: 'Catalog', items: [ { id: 'products', label: 'Products', icon: 'library', routerLink: ['/catalog', 'products'], }, { id: 'facets', label: 'Facets', icon: 'tag', routerLink: ['/catalog', 'facets'], }, ], }, { id: 'sales', label: 'Sales', requiresPermission: 'ReadOrder', items: [ { id: 'orders', label: 'Orders', routerLink: ['/orders'], icon: 'shopping-cart', }, ], }, ]; } });
import { Injectable } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { BehaviorSubject, combineLatest, Observable, of } from 'rxjs'; import { map, shareReplay } from 'rxjs/operators'; import { Permission } from '../../common/generated-types'; import { ActionBarContext, ActionBarDropdownMenuItem, ActionBarItem, NavMenuBadgeType, NavMenuItem, NavMenuSection, RouterLinkDefinition, } from './nav-builder-types'; /** * This service is used to define the contents of configurable menus in the application. */ @Injectable({ providedIn: 'root', }) export class NavBuilderService { menuConfig$: Observable<NavMenuSection[]>; actionBarConfig$: Observable<ActionBarItem[]>; actionBarDropdownConfig$: Observable<ActionBarDropdownMenuItem[]>; sectionBadges: { [sectionId: string]: Observable<NavMenuBadgeType> } = {}; private initialNavMenuConfig$ = new BehaviorSubject<NavMenuSection[]>([]); private addedNavMenuSections: Array<{ config: NavMenuSection; before?: string }> = []; private addedNavMenuItems: Array<{ config: NavMenuItem; sectionId: string; before?: string; }> = []; private addedActionBarItems: ActionBarItem[] = []; private addedActionBarDropdownMenuItems: ActionBarDropdownMenuItem[] = []; constructor() { this.setupStreams(); } /** * Used to define the initial sections and items of the main nav menu. */ defineNavMenuSections(config: NavMenuSection[]) { this.initialNavMenuConfig$.next(config); } /** * Add a section to the main nav menu. Providing the `before` argument will * move the section before any existing section with the specified id. If * omitted (or if the id is not found) the section will be appended to the * existing set of sections. * * Providing the `id` of an existing section will replace that section. */ addNavMenuSection(config: NavMenuSection, before?: string) { this.addedNavMenuSections.push({ config, before }); } /** * Add a menu item to an existing section specified by `sectionId`. The id of the section * can be found by inspecting the DOM and finding the `data-section-id` attribute. * Providing the `before` argument will move the item before any existing item with the specified id. * If omitted (or if the name is not found) the item will be appended to the * end of the section. * * Providing the `id` of an existing item in that section will replace * that item. */ addNavMenuItem(config: NavMenuItem, sectionId: string, before?: string) { this.addedNavMenuItems.push({ config, sectionId, before }); } /** * Adds a button to the ActionBar at the top right of each list or detail view. The locationId can * be determined by inspecting the DOM and finding the `<vdr-action-bar>` element and its * `data-location-id` attribute. */ addActionBarItem(config: ActionBarItem) { if (!this.addedActionBarItems.find(item => item.id === config.id)) { this.addedActionBarItems.push({ requiresPermission: Permission.Authenticated, ...config, }); } } /** * Adds a dropdown menu to the ActionBar at the top right of each list or detail view. The locationId can * be determined by inspecting the DOM and finding the `<vdr-action-bar>` element and its * `data-location-id` attribute. */ addActionBarDropdownMenuItem(config: ActionBarDropdownMenuItem) { if (!this.addedActionBarDropdownMenuItems.find(item => item.id === config.id)) { this.addedActionBarDropdownMenuItems.push({ requiresPermission: Permission.Authenticated, ...config, }); } } getRouterLink( config: { routerLink?: RouterLinkDefinition; context: ActionBarContext }, route: ActivatedRoute, ): string[] | null { if (typeof config.routerLink === 'function') { return config.routerLink(route, config.context); } if (Array.isArray(config.routerLink)) { return config.routerLink; } return null; } private setupStreams() { const sectionAdditions$ = of(this.addedNavMenuSections); const itemAdditions$ = of(this.addedNavMenuItems); const combinedConfig$ = combineLatest(this.initialNavMenuConfig$, sectionAdditions$).pipe( map(([initialConfig, additions]) => { for (const { config, before } of additions) { if (!config.requiresPermission) { config.requiresPermission = Permission.Authenticated; } const existingIndex = initialConfig.findIndex(c => c.id === config.id); if (-1 < existingIndex) { initialConfig[existingIndex] = config; } const beforeIndex = initialConfig.findIndex(c => c.id === before); if (-1 < beforeIndex) { if (-1 < existingIndex) { initialConfig.splice(existingIndex, 1); } initialConfig.splice(beforeIndex, 0, config); } else if (existingIndex === -1) { initialConfig.push(config); } } return initialConfig; }), shareReplay(1), ); this.menuConfig$ = combineLatest(combinedConfig$, itemAdditions$).pipe( map(([sections, additionalItems]) => { for (const item of additionalItems) { const section = sections.find(s => s.id === item.sectionId); if (!section) { // eslint-disable-next-line no-console console.error( `Could not add menu item "${item.config.id}", section "${item.sectionId}" does not exist`, ); } else { const { config, sectionId, before } = item; const existingIndex = section.items.findIndex(i => i.id === config.id); if (-1 < existingIndex) { section.items[existingIndex] = config; } const beforeIndex = section.items.findIndex(i => i.id === before); if (-1 < beforeIndex) { if (-1 < existingIndex) { section.items.splice(existingIndex, 1); } section.items.splice(beforeIndex, 0, config); } else if (existingIndex === -1) { section.items.push(config); } } } // Aggregate any badges defined for the nav items in each section for (const section of sections) { const itemBadgeStatuses = section.items .map(i => i.statusBadge) .filter(notNullOrUndefined); this.sectionBadges[section.id] = combineLatest(itemBadgeStatuses).pipe( map(badges => { const propagatingBadges = badges.filter(b => b.propagateToSection); if (propagatingBadges.length === 0) { return 'none'; } const statuses = propagatingBadges.map(b => b.type); if (statuses.includes('error')) { return 'error'; } else if (statuses.includes('warning')) { return 'warning'; } else if (statuses.includes('info')) { return 'info'; } else { return 'none'; } }), ); } return sections; }), ); this.actionBarConfig$ = of(this.addedActionBarItems); this.actionBarDropdownConfig$ = of(this.addedActionBarDropdownMenuItems); } }
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { TestingCommonModule } from '../../../../../testing/testing-common.module'; import { NotificationComponent } from '../../components/notification/notification.component'; import { OverlayHostComponent } from '../../components/overlay-host/overlay-host.component'; import { I18nService } from '../i18n/i18n.service'; import { MockI18nService } from '../i18n/i18n.service.mock'; import { OverlayHostService } from '../overlay-host/overlay-host.service'; import { NotificationService } from './notification.service'; describe('NotificationService:', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [TestingCommonModule], declarations: [NotificationComponent, OverlayHostComponent, TestComponent], providers: [ NotificationService, OverlayHostService, { provide: I18nService, useClass: MockI18nService }, ], schemas: [CUSTOM_ELEMENTS_SCHEMA], }); }); describe('notification():', () => { // The ToastComponent relies heavily on async calls to schedule the dismissal of a notify. function runDismissTimers(): void { tick(5000); // duration timeout tick(2000); // fadeOut timeout tick(); // promise tick(); } let fixture: ComponentFixture<TestComponent>; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(TestComponent); tick(); fixture.detectChanges(); })); it('should insert notify next to OverlayHost', fakeAsync(() => { const instance: TestComponent = fixture.componentInstance; instance.notificationService.notify({ message: 'test' }); fixture.detectChanges(); tick(); expect(fixture.nativeElement.querySelector('vdr-notification')).not.toBeNull(); runDismissTimers(); })); it('should bind the message', fakeAsync(() => { const instance: TestComponent = fixture.componentInstance; instance.notificationService.notify({ message: 'test' }); tick(); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.notification-wrapper').innerHTML).toContain('test'); runDismissTimers(); })); it('should dismiss after duration elapses', fakeAsync(() => { const instance: TestComponent = fixture.componentInstance; instance.notificationService.notify({ message: 'test', duration: 1000, }); tick(); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('vdr-notification')).not.toBeNull(); runDismissTimers(); expect(fixture.nativeElement.querySelector('vdr-notification')).toBeNull(); })); }); }); @Component({ template: ` <vdr-overlay-host></vdr-overlay-host> `, }) class TestComponent { constructor(public notificationService: NotificationService) {} }
import { ComponentFactoryResolver, ComponentRef, Injectable, ViewContainerRef } from '@angular/core'; import { NotificationComponent } from '../../components/notification/notification.component'; import { I18nService } from '../i18n/i18n.service'; import { OverlayHostService } from '../overlay-host/overlay-host.service'; /** * @description * The types of notification available. * * @docsCategory services * @docsPage NotificationService */ export type NotificationType = 'info' | 'success' | 'error' | 'warning'; /** * @description * Configuration for a toast notification. * * @docsCategory services * @docsPage NotificationService */ export interface ToastConfig { message: string; translationVars?: { [key: string]: string | number }; type?: NotificationType; duration?: number; } // How many ms before the toast is dismissed. const TOAST_DURATION = 3000; /** * @description * Provides toast notification functionality. * * @example * ```ts * class MyComponent { * constructor(private notificationService: NotificationService) {} * * save() { * this.notificationService * .success(_('asset.notify-create-assets-success'), { * count: successCount, * }); * } * } * * @docsCategory services * @docsPage NotificationService * @docsWeight 0 */ @Injectable({ providedIn: 'root', }) export class NotificationService { private get hostView(): Promise<ViewContainerRef> { return this.overlayHostService.getHostView(); } private openToastRefs: Array<{ ref: ComponentRef<NotificationComponent>; timerId: any }> = []; constructor( private i18nService: I18nService, private resolver: ComponentFactoryResolver, private overlayHostService: OverlayHostService, ) {} /** * @description * Display a success toast notification */ success(message: string, translationVars?: { [key: string]: string | number }): void { this.notify({ message, translationVars, type: 'success', }); } /** * @description * Display an info toast notification */ info(message: string, translationVars?: { [key: string]: string | number }): void { this.notify({ message, translationVars, type: 'info', }); } /** * @description * Display a warning toast notification */ warning(message: string, translationVars?: { [key: string]: string | number }): void { this.notify({ message, translationVars, type: 'warning', }); } /** * @description * Display an error toast notification */ error(message: string, translationVars?: { [key: string]: string | number }): void { this.notify({ message, translationVars, type: 'error', duration: 20000, }); } /** * @description * Display a toast notification. */ notify(config: ToastConfig): void { this.createToast(config); } /** * Load a ToastComponent into the DOM host location. */ private async createToast(config: ToastConfig): Promise<void> { const toastFactory = this.resolver.resolveComponentFactory(NotificationComponent); const hostView = await this.hostView; const ref = hostView.createComponent<NotificationComponent>(toastFactory); const toast: NotificationComponent = ref.instance; const dismissFn = this.createDismissFunction(ref); toast.type = config.type || 'info'; toast.message = config.message; toast.translationVars = this.translateTranslationVars(config.translationVars || {}); toast.registerOnClickFn(dismissFn); let timerId; if (!config.duration || 0 < config.duration) { timerId = setTimeout(dismissFn, config.duration || TOAST_DURATION); } this.openToastRefs.unshift({ ref, timerId }); setTimeout(() => this.calculatePositions()); } /** * Returns a function which will destroy the toast component and * remove it from the openToastRefs array. */ private createDismissFunction(ref: ComponentRef<NotificationComponent>): () => void { return () => { const toast: NotificationComponent = ref.instance; const index = this.openToastRefs.map(o => o.ref).indexOf(ref); if (this.openToastRefs[index]) { clearTimeout(this.openToastRefs[index].timerId); } toast.fadeOut().then(() => { ref.destroy(); this.openToastRefs.splice(index, 1); this.calculatePositions(); }); }; } /** * Calculate and set the top offsets for each of the open toasts. */ private calculatePositions(): void { let cumulativeHeight = 10; this.openToastRefs.forEach(obj => { const toast: NotificationComponent = obj.ref.instance; toast.offsetTop = cumulativeHeight; cumulativeHeight += toast.getHeight() + 6; }); } private translateTranslationVars(translationVars: { [key: string]: string | number }): { [key: string]: string | number; } { for (const [key, val] of Object.entries(translationVars)) { if (typeof val === 'string') { translationVars[key] = this.i18nService.translate(val); } } return translationVars; } }
import { Injectable, ViewContainerRef } from '@angular/core'; /** * The OverlayHostService is used to get a reference to the ViewConainerRef of the * OverlayHost component, so that other components may insert components & elements * into the DOM at that point. */ @Injectable({ providedIn: 'root', }) export class OverlayHostService { private hostView: ViewContainerRef; private promiseResolveFns: Array<(result: any) => void> = []; /** * Used to pass in the ViewContainerRed from the OverlayHost component. * Should not be used by any other component. */ registerHostView(viewContainerRef: ViewContainerRef): void { this.hostView = viewContainerRef; if (0 < this.promiseResolveFns.length) { this.resolveHostView(); } } /** * Returns a promise which resolves to the ViewContainerRef of the OverlayHost * component. This can then be used to insert components and elements into the * DOM at that point. */ getHostView(): Promise<ViewContainerRef> { return new Promise((resolve: (result: any) => void) => { this.promiseResolveFns.push(resolve); if (this.hostView !== undefined) { this.resolveHostView(); } }); } private resolveHostView(): void { this.promiseResolveFns.forEach(resolve => resolve(this.hostView)); this.promiseResolveFns = []; } }
import { Injectable, Type } from '@angular/core'; import { Route } from '@angular/router'; import { map } from 'rxjs/operators'; import { detailComponentWithResolver } from '../../common/base-detail.component'; import { PageLocationId } from '../../common/component-registry-types'; import { CanDeactivateDetailGuard } from '../../shared/providers/routing/can-deactivate-detail-guard'; /** * @description * The object used to configure a new page tab. * * @docsCategory tabs */ export interface PageTabConfig { /** * @description * A valid location representing a list or detail page. */ location: PageLocationId; /** * @description * An optional icon to display in the tab. The icon * should be a valid shape name from the [Clarity Icons](https://core.clarity.design/foundation/icons/shapes/) * set. */ tabIcon?: string; /** * @description * The route path to the tab. This will be appended to the * route of the parent page. */ route: string; /** * @description * The name of the tab to display in the UI. */ tab: string; /** * @description * The priority of the tab. Tabs with a lower priority will be displayed first. */ priority?: number; /** * @description * The component to render at the route of the tab. */ component: Type<any> | ReturnType<typeof detailComponentWithResolver>; /** * @description * You can optionally provide any native Angular route configuration options here. * Any values provided here will take precedence over the values generated * by the `route` and `component` properties. */ routeConfig?: Route; } @Injectable({ providedIn: 'root', }) export class PageService { private registry = new Map<PageLocationId, PageTabConfig[]>(); registerPageTab(config: PageTabConfig) { if (!this.registry.has(config.location)) { this.registry.set(config.location, []); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const pages = this.registry.get(config.location)!; if (pages.find(p => p.tab === config.tab)) { throw new Error(`A page with the tab "${config.tab}" has already been registered`); } pages.push(config); } getPageTabRoutes(location: PageLocationId): Route[] { const configs = this.registry.get(location) || []; return configs.map(config => { const route: Route = { path: config.route || '', pathMatch: config.route ? 'prefix' : 'full', }; let component: Type<any>; if (isComponentWithResolver(config.component)) { const { component: cmp, breadcrumbFn, resolveFn } = config.component; component = cmp; route.resolve = { detail: resolveFn }; route.data = { breadcrumb: data => data.detail.entity.pipe(map(entity => breadcrumbFn(entity))), }; } else { component = config.component; } const guards = typeof component.prototype.canDeactivate === 'function' ? [CanDeactivateDetailGuard] : []; route.component = component; route.canDeactivate = guards; if (config.routeConfig) { Object.assign(route, config.routeConfig); } return route; }); } getPageTabs(location: PageLocationId): PageTabConfig[] { return this.registry.get(location)?.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0)) || []; } } function isComponentWithResolver(input: any): input is ReturnType<typeof detailComponentWithResolver> { return input && input.hasOwnProperty('resolveFn'); }
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { Permission } from '../../common/generated-types'; /** * @description * This service is used internally to power components & logic that are dependent on knowing the * current user's permissions in the currently-active channel. */ @Injectable({ providedIn: 'root', }) export class PermissionsService { private currentUserPermissions: string[] = []; private _currentUserPermissions$ = new BehaviorSubject<string[]>([]); currentUserPermissions$ = this._currentUserPermissions$.asObservable(); /** * @description * This is called whenever: * - the user logs in * - the active channel changes * * Since active user validation occurs as part of the main auth guard, we can be assured * that if the user is logged in, then this method will be called with the user's permissions * before any other components are rendered lower down in the component tree. */ setCurrentUserPermissions(permissions: string[]) { this.currentUserPermissions = permissions; this._currentUserPermissions$.next(permissions); } userHasPermissions(requiredPermissions: Array<string | Permission>): boolean { for (const perm of requiredPermissions) { if (this.currentUserPermissions.includes(perm)) { return true; } } return false; } }
import { DragDropModule } from '@angular/cdk/drag-drop'; import { OverlayModule } from '@angular/cdk/overlay'; import { A11yModule } from '@angular/cdk/a11y'; import { CommonModule } from '@angular/common'; import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { ClarityModule } from '@clr/angular'; import '@clr/icons'; import '@clr/icons/shapes/all-shapes'; import { NgSelectModule } from '@ng-select/ng-select'; import { TranslateModule } from '@ngx-translate/core'; import '@webcomponents/custom-elements/custom-elements.min.js'; import { NgxPaginationModule } from 'ngx-pagination'; import { ModalService } from '../providers/modal/modal.service'; import { ActionBarItemsComponent } from './components/action-bar-items/action-bar-items.component'; import { ActionBarComponent, ActionBarLeftComponent, ActionBarRightComponent, } from './components/action-bar/action-bar.component'; import { AddressFormComponent } from './components/address-form/address-form.component'; import { AffixedInputComponent } from './components/affixed-input/affixed-input.component'; import { PercentageSuffixInputComponent } from './components/affixed-input/percentage-suffix-input.component'; import { AssetFileInputComponent } from './components/asset-file-input/asset-file-input.component'; import { AssetGalleryComponent } from './components/asset-gallery/asset-gallery.component'; import { AssetPickerDialogComponent } from './components/asset-picker-dialog/asset-picker-dialog.component'; import { AssetPreviewDialogComponent } from './components/asset-preview-dialog/asset-preview-dialog.component'; import { AssetPreviewLinksComponent } from './components/asset-preview-links/asset-preview-links.component'; import { AssetPreviewComponent } from './components/asset-preview/asset-preview.component'; import { AssetsComponent } from './components/assets/assets.component'; import { AssetSearchInputComponent } from './components/asset-search-input/asset-search-input.component'; import { AssignToChannelDialogComponent } from './components/assign-to-channel-dialog/assign-to-channel-dialog.component'; import { BulkActionMenuComponent } from './components/bulk-action-menu/bulk-action-menu.component'; import { ChannelAssignmentControlComponent } from './components/channel-assignment-control/channel-assignment-control.component'; import { ChannelBadgeComponent } from './components/channel-badge/channel-badge.component'; import { ChipComponent } from './components/chip/chip.component'; import { ConfigurableInputComponent } from './components/configurable-input/configurable-input.component'; import { CurrencyInputComponent } from './components/currency-input/currency-input.component'; import { CustomDetailComponentHostComponent } from './components/custom-detail-component-host/custom-detail-component-host.component'; import { CustomFieldControlComponent } from './components/custom-field-control/custom-field-control.component'; import { CustomerLabelComponent } from './components/customer-label/customer-label.component'; import { DataTable2ColumnComponent } from './components/data-table-2/data-table-column.component'; import { DataTableCustomFieldColumnComponent } from './components/data-table-2/data-table-custom-field-column.component'; import { DataTable2SearchComponent } from './components/data-table-2/data-table-search.component'; import { DataTable2Component } from './components/data-table-2/data-table2.component'; import { DataTableColumnPickerComponent } from './components/data-table-column-picker/data-table-column-picker.component'; import { DataTableFilterLabelComponent } from './components/data-table-filter-label/data-table-filter-label.component'; import { CustomFilterComponentDirective } from './components/data-table-filters/custom-filter-component.directive'; import { DataTableFiltersComponent } from './components/data-table-filters/data-table-filters.component'; import { DataTableColumnComponent } from './components/data-table/data-table-column.component'; import { DataTableComponent } from './components/data-table/data-table.component'; import { DatetimePickerComponent } from './components/datetime-picker/datetime-picker.component'; import { DropdownItemDirective } from './components/dropdown/dropdown-item.directive'; import { DropdownMenuComponent } from './components/dropdown/dropdown-menu.component'; import { DropdownTriggerDirective } from './components/dropdown/dropdown-trigger.directive'; import { DropdownComponent } from './components/dropdown/dropdown.component'; import { EditNoteDialogComponent } from './components/edit-note-dialog/edit-note-dialog.component'; import { EmptyPlaceholderComponent } from './components/empty-placeholder/empty-placeholder.component'; import { EntityInfoComponent } from './components/entity-info/entity-info.component'; import { FacetValueChipComponent } from './components/facet-value-chip/facet-value-chip.component'; import { FacetValueSelectorComponent } from './components/facet-value-selector/facet-value-selector.component'; import { FocalPointControlComponent } from './components/focal-point-control/focal-point-control.component'; import { FormFieldControlDirective } from './components/form-field/form-field-control.directive'; import { FormFieldComponent } from './components/form-field/form-field.component'; import { FormItemComponent } from './components/form-item/form-item.component'; import { FormattedAddressComponent } from './components/formatted-address/formatted-address.component'; import { HelpTooltipComponent } from './components/help-tooltip/help-tooltip.component'; import { HistoryEntryDetailComponent } from './components/history-entry-detail/history-entry-detail.component'; import { ItemsPerPageControlsComponent } from './components/items-per-page-controls/items-per-page-controls.component'; import { LabeledDataComponent } from './components/labeled-data/labeled-data.component'; import { LanguageSelectorComponent } from './components/language-selector/language-selector.component'; import { LocalizedTextComponent } from './components/localized-text/localized-text.component'; import { ManageTagsDialogComponent } from './components/manage-tags-dialog/manage-tags-dialog.component'; import { DialogButtonsDirective } from './components/modal-dialog/dialog-buttons.directive'; import { DialogComponentOutletComponent } from './components/modal-dialog/dialog-component-outlet.component'; import { DialogTitleDirective } from './components/modal-dialog/dialog-title.directive'; import { ModalDialogComponent } from './components/modal-dialog/modal-dialog.component'; import { ObjectTreeComponent } from './components/object-tree/object-tree.component'; import { OrderStateLabelComponent } from './components/order-state-label/order-state-label.component'; import { PageBlockComponent } from './components/page-block/page-block.component'; import { PageBodyComponent } from './components/page-body/page-body.component'; import { PageDetailLayoutComponent } from './components/page-detail-layout/page-detail-layout.component'; import { PageDetailSidebarComponent } from './components/page-detail-layout/page-detail-sidebar.component'; import { PageEntityInfoComponent } from './components/page-entity-info/page-entity-info.component'; import { PageHeaderDescriptionComponent } from './components/page-header-description/page-header-description.component'; import { PageHeaderTabsComponent } from './components/page-header-tabs/page-header-tabs.component'; import { PageHeaderComponent } from './components/page-header/page-header.component'; import { PageTitleComponent } from './components/page-title/page-title.component'; import { PageComponent } from './components/page/page.component'; import { PaginationControlsComponent } from './components/pagination-controls/pagination-controls.component'; import { ProductMultiSelectorDialogComponent } from './components/product-multi-selector-dialog/product-multi-selector-dialog.component'; import { ProductSearchInputComponent } from './components/product-search-input/product-search-input.component'; import { ProductVariantSelectorComponent } from './components/product-variant-selector/product-variant-selector.component'; import { RadioCardFieldsetComponent } from './components/radio-card/radio-card-fieldset.component'; import { RadioCardComponent } from './components/radio-card/radio-card.component'; import { ExternalImageDialogComponent } from './components/rich-text-editor/external-image-dialog/external-image-dialog.component'; import { LinkDialogComponent } from './components/rich-text-editor/link-dialog/link-dialog.component'; import { ContextMenuComponent } from './components/rich-text-editor/prosemirror/context-menu/context-menu.component'; import { RawHtmlDialogComponent } from './components/rich-text-editor/raw-html-dialog/raw-html-dialog.component'; import { RichTextEditorComponent } from './components/rich-text-editor/rich-text-editor.component'; import { SelectToggleComponent } from './components/select-toggle/select-toggle.component'; import { SimpleDialogComponent } from './components/simple-dialog/simple-dialog.component'; import { SplitViewComponent } from './components/split-view/split-view.component'; import { SplitViewLeftDirective, SplitViewRightDirective, } from './components/split-view/split-view.directive'; import { StatusBadgeComponent } from './components/status-badge/status-badge.component'; import { TabbedCustomFieldsComponent } from './components/tabbed-custom-fields/tabbed-custom-fields.component'; import { TableRowActionComponent } from './components/table-row-action/table-row-action.component'; import { TagSelectorComponent } from './components/tag-selector/tag-selector.component'; import { TimelineEntryComponent } from './components/timeline-entry/timeline-entry.component'; import { TitleInputComponent } from './components/title-input/title-input.component'; import { UiExtensionPointComponent } from './components/ui-extension-point/ui-extension-point.component'; import { DisabledDirective } from './directives/disabled.directive'; import { IfDefaultChannelActiveDirective } from './directives/if-default-channel-active.directive'; import { IfMultichannelDirective } from './directives/if-multichannel.directive'; import { IfPermissionsDirective } from './directives/if-permissions.directive'; import { BooleanFormInputComponent } from './dynamic-form-inputs/boolean-form-input/boolean-form-input.component'; import { HtmlEditorFormInputComponent } from './dynamic-form-inputs/code-editor-form-input/html-editor-form-input.component'; import { JsonEditorFormInputComponent } from './dynamic-form-inputs/code-editor-form-input/json-editor-form-input.component'; import { CombinationModeFormInputComponent } from './dynamic-form-inputs/combination-mode-form-input/combination-mode-form-input.component'; import { CurrencyFormInputComponent } from './dynamic-form-inputs/currency-form-input/currency-form-input.component'; import { CustomerGroupFormInputComponent } from './dynamic-form-inputs/customer-group-form-input/customer-group-form-input.component'; import { DateFormInputComponent } from './dynamic-form-inputs/date-form-input/date-form-input.component'; import { DynamicFormInputComponent } from './dynamic-form-inputs/dynamic-form-input/dynamic-form-input.component'; import { FacetValueFormInputComponent } from './dynamic-form-inputs/facet-value-form-input/facet-value-form-input.component'; import { NumberFormInputComponent } from './dynamic-form-inputs/number-form-input/number-form-input.component'; import { PasswordFormInputComponent } from './dynamic-form-inputs/password-form-input/password-form-input.component'; import { ProductMultiSelectorFormInputComponent } from './dynamic-form-inputs/product-multi-selector-form-input/product-multi-selector-form-input.component'; import { ProductSelectorFormInputComponent } from './dynamic-form-inputs/product-selector-form-input/product-selector-form-input.component'; import { RelationAssetInputComponent } from './dynamic-form-inputs/relation-form-input/asset/relation-asset-input.component'; import { RelationCustomerInputComponent } from './dynamic-form-inputs/relation-form-input/customer/relation-customer-input.component'; import { RelationGenericInputComponent } from './dynamic-form-inputs/relation-form-input/generic/relation-generic-input.component'; import { RelationProductVariantInputComponent } from './dynamic-form-inputs/relation-form-input/product-variant/relation-product-variant-input.component'; import { RelationProductInputComponent } from './dynamic-form-inputs/relation-form-input/product/relation-product-input.component'; import { RelationCardComponent, RelationCardDetailDirective, RelationCardPreviewDirective, } from './dynamic-form-inputs/relation-form-input/relation-card/relation-card.component'; import { RelationFormInputComponent } from './dynamic-form-inputs/relation-form-input/relation-form-input.component'; import { RelationSelectorDialogComponent } from './dynamic-form-inputs/relation-form-input/relation-selector-dialog/relation-selector-dialog.component'; import { RichTextFormInputComponent } from './dynamic-form-inputs/rich-text-form-input/rich-text-form-input.component'; import { SelectFormInputComponent } from './dynamic-form-inputs/select-form-input/select-form-input.component'; import { TextFormInputComponent } from './dynamic-form-inputs/text-form-input/text-form-input.component'; import { TextareaFormInputComponent } from './dynamic-form-inputs/textarea-form-input/textarea-form-input.component'; import { AssetPreviewPipe } from './pipes/asset-preview.pipe'; import { ChannelLabelPipe } from './pipes/channel-label.pipe'; import { CustomFieldDescriptionPipe } from './pipes/custom-field-description.pipe'; import { CustomFieldLabelPipe } from './pipes/custom-field-label.pipe'; import { DurationPipe } from './pipes/duration.pipe'; import { FileSizePipe } from './pipes/file-size.pipe'; import { HasPermissionPipe } from './pipes/has-permission.pipe'; import { LocaleCurrencyNamePipe } from './pipes/locale-currency-name.pipe'; import { LocaleCurrencyPipe } from './pipes/locale-currency.pipe'; import { LocaleDatePipe } from './pipes/locale-date.pipe'; import { LocaleLanguageNamePipe } from './pipes/locale-language-name.pipe'; import { LocaleRegionNamePipe } from './pipes/locale-region-name.pipe'; import { SentenceCasePipe } from './pipes/sentence-case.pipe'; import { SortPipe } from './pipes/sort.pipe'; import { StateI18nTokenPipe } from './pipes/state-i18n-token.pipe'; import { StringToColorPipe } from './pipes/string-to-color.pipe'; import { TimeAgoPipe } from './pipes/time-ago.pipe'; import { CanDeactivateDetailGuard } from './providers/routing/can-deactivate-detail-guard'; import { CardComponent, CardControlsDirective } from './components/card/card.component'; import { ZoneSelectorComponent } from './components/zone-selector/zone-selector.component'; import { ChartComponent } from './components/chart/chart.component'; import { CurrencyCodeSelectorComponent } from './components/currency-code-selector/currency-code-selector.component'; import { LanguageCodeSelectorComponent } from './components/language-code-selector/language-code-selector.component'; import { DataTableFilterPresetsComponent } from './components/data-table-filter-presets/data-table-filter-presets.component'; import { AddFilterPresetButtonComponent } from './components/data-table-filter-presets/add-filter-preset-button.component'; import { RenameFilterPresetDialogComponent } from './components/data-table-filter-presets/rename-filter-preset-dialog.component'; import { ActionBarDropdownMenuComponent } from './components/action-bar-dropdown-menu/action-bar-dropdown-menu.component'; import { DuplicateEntityDialogComponent } from './components/duplicate-entity-dialog/duplicate-entity-dialog.component'; const IMPORTS = [ ClarityModule, CommonModule, FormsModule, ReactiveFormsModule, RouterModule, NgSelectModule, NgxPaginationModule, TranslateModule, OverlayModule, DragDropModule, A11yModule, ]; const DECLARATIONS = [ ActionBarComponent, ActionBarLeftComponent, ActionBarRightComponent, ActionBarDropdownMenuComponent, AssetsComponent, AssetPreviewComponent, AssetPreviewDialogComponent, AssetSearchInputComponent, ConfigurableInputComponent, AffixedInputComponent, ChipComponent, CurrencyInputComponent, LocaleCurrencyNamePipe, CustomerLabelComponent, CustomFieldControlComponent, DataTableComponent, DataTableColumnComponent, FacetValueSelectorComponent, ItemsPerPageControlsComponent, PaginationControlsComponent, TableRowActionComponent, FacetValueChipComponent, FileSizePipe, FormFieldComponent, FormFieldControlDirective, FormItemComponent, ModalDialogComponent, PercentageSuffixInputComponent, DialogComponentOutletComponent, DialogButtonsDirective, DialogTitleDirective, SelectToggleComponent, LanguageSelectorComponent, RichTextEditorComponent, SimpleDialogComponent, TitleInputComponent, SentenceCasePipe, DropdownComponent, DropdownMenuComponent, SortPipe, DropdownTriggerDirective, DropdownItemDirective, OrderStateLabelComponent, FormattedAddressComponent, LabeledDataComponent, StringToColorPipe, ObjectTreeComponent, IfPermissionsDirective, IfMultichannelDirective, HasPermissionPipe, ActionBarItemsComponent, DisabledDirective, AssetFileInputComponent, AssetGalleryComponent, AssetPickerDialogComponent, EntityInfoComponent, DatetimePickerComponent, ChannelBadgeComponent, ChannelAssignmentControlComponent, ChannelLabelPipe, IfDefaultChannelActiveDirective, CustomFieldLabelPipe, CustomFieldDescriptionPipe, FocalPointControlComponent, AssetPreviewPipe, LinkDialogComponent, ExternalImageDialogComponent, TimeAgoPipe, DurationPipe, EmptyPlaceholderComponent, TimelineEntryComponent, HistoryEntryDetailComponent, EditNoteDialogComponent, ProductSelectorFormInputComponent, StateI18nTokenPipe, ProductVariantSelectorComponent, HelpTooltipComponent, CustomerGroupFormInputComponent, AddressFormComponent, LocaleDatePipe, LocaleCurrencyPipe, LocaleLanguageNamePipe, LocaleRegionNamePipe, TagSelectorComponent, ManageTagsDialogComponent, RelationSelectorDialogComponent, RelationCardComponent, StatusBadgeComponent, TabbedCustomFieldsComponent, UiExtensionPointComponent, CustomDetailComponentHostComponent, AssetPreviewLinksComponent, ProductMultiSelectorDialogComponent, ProductSearchInputComponent, ContextMenuComponent, RawHtmlDialogComponent, BulkActionMenuComponent, RadioCardComponent, RadioCardFieldsetComponent, DataTable2Component, DataTable2ColumnComponent, DataTableFiltersComponent, DataTableFilterLabelComponent, DataTableColumnPickerComponent, DataTable2SearchComponent, DataTableCustomFieldColumnComponent, SplitViewComponent, SplitViewLeftDirective, SplitViewRightDirective, PageComponent, CustomFilterComponentDirective, PageHeaderComponent, PageTitleComponent, PageHeaderDescriptionComponent, PageHeaderTabsComponent, PageBodyComponent, PageBlockComponent, PageEntityInfoComponent, LocalizedTextComponent, PageDetailLayoutComponent, PageDetailSidebarComponent, CardComponent, CardControlsDirective, ZoneSelectorComponent, ChartComponent, AssignToChannelDialogComponent, CurrencyCodeSelectorComponent, LanguageCodeSelectorComponent, DataTableFilterPresetsComponent, AddFilterPresetButtonComponent, RenameFilterPresetDialogComponent, DuplicateEntityDialogComponent, ]; const DYNAMIC_FORM_INPUTS = [ TextFormInputComponent, PasswordFormInputComponent, NumberFormInputComponent, DateFormInputComponent, CurrencyFormInputComponent, BooleanFormInputComponent, SelectFormInputComponent, FacetValueFormInputComponent, DynamicFormInputComponent, RelationFormInputComponent, RelationAssetInputComponent, RelationProductInputComponent, RelationProductVariantInputComponent, RelationCustomerInputComponent, RelationCardPreviewDirective, RelationCardDetailDirective, RelationSelectorDialogComponent, RelationGenericInputComponent, TextareaFormInputComponent, RichTextFormInputComponent, JsonEditorFormInputComponent, HtmlEditorFormInputComponent, ProductMultiSelectorFormInputComponent, CombinationModeFormInputComponent, ]; @NgModule({ imports: [IMPORTS], exports: [...IMPORTS, ...DECLARATIONS, ...DYNAMIC_FORM_INPUTS], declarations: [...DECLARATIONS, ...DYNAMIC_FORM_INPUTS], providers: [ // This needs to be shared, since lazy-loaded // modules have their own entryComponents which // are unknown to the CoreModule instance of ModalService. // See https://github.com/angular/angular/issues/14324#issuecomment-305650763 ModalService, CanDeactivateDetailGuard, ], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class SharedModule {}
import { AfterViewInit, ChangeDetectionStrategy, Component, Input, OnInit, Self, ViewChild, } from '@angular/core'; import { combineLatest } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { ActionBarDropdownMenuItem } from '../../../providers/nav-builder/nav-builder-types'; import { ActionBarBaseComponent } from '../action-bar-items/action-bar-base.component'; import { DropdownComponent } from '../dropdown/dropdown.component'; @Component({ selector: 'vdr-action-bar-dropdown-menu', templateUrl: './action-bar-dropdown-menu.component.html', styleUrls: ['./action-bar-dropdown-menu.component.css'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ // This is a rather involved work-around to allow the {@link DropdownItemDirective} to // be able to access the DropdownComponent instance even when it is not a direct parent, // as is the case when this component is used. { provide: DropdownComponent, useFactory: (actionBarDropdownMenuComponent: ActionBarDropdownMenuComponent) => { return new Promise(resolve => actionBarDropdownMenuComponent.onDropdownComponentResolved(cmp => resolve(cmp)), ); }, deps: [[new Self(), ActionBarDropdownMenuComponent]], }, ], }) export class ActionBarDropdownMenuComponent extends ActionBarBaseComponent<ActionBarDropdownMenuItem> implements OnInit, AfterViewInit { @ViewChild('dropdownComponent') dropdownComponent: DropdownComponent; @Input() alwaysShow = false; private onDropdownComponentResolvedFn: (dropdownComponent: DropdownComponent) => void; ngOnInit() { this.items$ = combineLatest(this.navBuilderService.actionBarDropdownConfig$, this.locationId$).pipe( map(([items, locationId]) => items.filter(config => config.locationId === locationId)), tap(items => { this.buildButtonStates(items); }), ); } ngAfterViewInit() { if (this.onDropdownComponentResolvedFn) { this.onDropdownComponentResolvedFn(this.dropdownComponent); } } onDropdownComponentResolved(fn: (dropdownComponent: DropdownComponent) => void) { this.onDropdownComponentResolvedFn = fn; } }
import { Directive, HostBinding, inject, Injector, Input, OnChanges, SimpleChanges } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { BehaviorSubject, Observable, of, switchMap } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { ActionBarLocationId } from '../../../common/component-registry-types'; import { DataService } from '../../../data/providers/data.service'; import { ActionBarButtonState, ActionBarContext, ActionBarDropdownMenuItem, ActionBarItem, } from '../../../providers/nav-builder/nav-builder-types'; import { NavBuilderService } from '../../../providers/nav-builder/nav-builder.service'; import { NotificationService } from '../../../providers/notification/notification.service'; @Directive() export abstract class ActionBarBaseComponent<T extends ActionBarItem | ActionBarDropdownMenuItem> implements OnChanges { @HostBinding('attr.data-location-id') @Input() locationId: ActionBarLocationId; items$: Observable<T[]>; buttonStates: { [id: string]: Observable<ActionBarButtonState> } = {}; protected locationId$ = new BehaviorSubject<string>(''); protected navBuilderService = inject(NavBuilderService); protected route = inject(ActivatedRoute); protected dataService = inject(DataService); protected notificationService = inject(NotificationService); protected injector = inject(Injector); ngOnChanges(changes: SimpleChanges): void { if ('locationId' in changes) { this.locationId$.next(changes['locationId'].currentValue); } } handleClick(event: MouseEvent, item: T) { if (typeof item.onClick === 'function') { item.onClick(event, this.createContext()); } } getRouterLink(item: T): any[] | null { return this.navBuilderService.getRouterLink( { routerLink: item.routerLink, context: this.createContext() }, this.route, ); } protected buildButtonStates(items: T[]) { const context = this.createContext(); const defaultState = { disabled: false, visible: true, }; for (const item of items) { const buttonState$ = typeof item.buttonState === 'function' ? item.buttonState(context).pipe( map(result => result ?? defaultState), catchError(() => of(defaultState)), ) : of(defaultState); this.buttonStates[item.id] = buttonState$; } } protected createContext(): ActionBarContext { return { route: this.route, injector: this.injector, dataService: this.dataService, notificationService: this.notificationService, entity$: this.route.data.pipe( switchMap(data => { if (data.detail?.entity) { return data.detail.entity as Observable<Record<string, any>>; } else { return of(undefined); } }), ), }; } }
import { ChangeDetectionStrategy, Component, OnChanges, OnInit } from '@angular/core'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { combineLatest } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { ActionBarItem } from '../../../providers/nav-builder/nav-builder-types'; import { ActionBarBaseComponent } from './action-bar-base.component'; @Component({ selector: 'vdr-action-bar-items', templateUrl: './action-bar-items.component.html', styleUrls: ['./action-bar-items.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ActionBarItemsComponent extends ActionBarBaseComponent<ActionBarItem> implements OnInit { ngOnInit() { this.items$ = combineLatest([this.navBuilderService.actionBarConfig$, this.locationId$]).pipe( map(([items, locationId]) => items.filter(config => config.locationId === locationId)), tap(items => { this.buildButtonStates(items); }), ); } getButtonStyles(item: ActionBarItem): string[] { const styles = ['button']; if (item.buttonStyle && item.buttonStyle === 'link') { styles.push('btn-link'); return styles; } styles.push(this.getButtonColorClass(item)); return styles; } private getButtonColorClass(item: ActionBarItem): string { switch (item.buttonColor) { case undefined: return ''; case 'primary': return item.buttonStyle === 'outline' ? 'btn-outline' : 'primary'; case 'success': return item.buttonStyle === 'outline' ? 'btn-success-outline' : 'success'; case 'warning': return item.buttonStyle === 'outline' ? 'btn-warning-outline' : 'warning'; default: assertNever(item.buttonColor); return ''; } } }
import { Component, ContentChild, Input, OnInit } from '@angular/core'; @Component({ selector: 'vdr-ab-left', template: ` <ng-content></ng-content> `, }) export class ActionBarLeftComponent { @Input() grow = false; } @Component({ selector: 'vdr-ab-right', template: ` <ng-content></ng-content> `, styles: [ ` :host { display: flex; align-items: center; } `, ], }) export class ActionBarRightComponent { @Input() grow = false; } @Component({ selector: 'vdr-action-bar', templateUrl: './action-bar.component.html', styleUrls: ['./action-bar.component.scss'], }) export class ActionBarComponent { @ContentChild(ActionBarLeftComponent) left: ActionBarLeftComponent; @ContentChild(ActionBarRightComponent) right: ActionBarRightComponent; }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { UntypedFormGroup } from '@angular/forms'; import { CustomFieldConfig, GetAvailableCountriesQuery } from '../../../common/generated-types'; @Component({ selector: 'vdr-address-form', templateUrl: './address-form.component.html', styleUrls: ['./address-form.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AddressFormComponent { @Input() customFields: CustomFieldConfig; @Input() formGroup: UntypedFormGroup; @Input() availableCountries: Array<GetAvailableCountriesQuery['countries']['items']>; }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; /** * A wrapper around an <input> element which adds a prefix and/or a suffix element. */ @Component({ selector: 'vdr-affixed-input', templateUrl: './affixed-input.component.html', styleUrls: ['./affixed-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AffixedInputComponent { @Input() prefix: string; @Input() suffix: string; }
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; /** * A form input control which displays a number input with a percentage sign suffix. */ @Component({ selector: 'vdr-percentage-suffix-input', styles: [ ` :host { padding: 0; } `, ], template: ` <vdr-affixed-input suffix="%"> <input type="number" step="1" [value]="_value" [disabled]="disabled" [readonly]="readonly" (input)="onInput($event.target.value)" (focus)="onTouch()" /> </vdr-affixed-input> `, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: PercentageSuffixInputComponent, multi: true, }, ], }) export class PercentageSuffixInputComponent implements ControlValueAccessor, OnChanges { @Input() disabled = false; @Input() readonly = false; @Input() value: number; onChange: (val: any) => void; onTouch: () => void; _value: number; ngOnChanges(changes: SimpleChanges) { if ('value' in changes) { this.writeValue(changes['value'].currentValue); } } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouch = fn; } setDisabledState(isDisabled: boolean) { this.disabled = isDisabled; } onInput(value: string | number) { this.onChange(value); } writeValue(value: any): void { const numericValue = +value; if (!Number.isNaN(numericValue)) { this._value = numericValue; } } }
import { ChangeDetectionStrategy, Component, EventEmitter, HostListener, Input, OnInit, Output, } from '@angular/core'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { ServerConfigService } from '../../../data/server-config'; /** * A component for selecting files to upload as new Assets. */ @Component({ selector: 'vdr-asset-file-input', templateUrl: './asset-file-input.component.html', styleUrls: ['./asset-file-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AssetFileInputComponent implements OnInit { /** * CSS selector of the DOM element which will be masked by the file * drop zone. Defaults to `body`. */ @Input() dropZoneTarget = 'body'; @Input() uploading = false; @Output() selectFiles = new EventEmitter<File[]>(); dragging = false; overDropZone = false; dropZoneStyle = { 'width.px': 0, 'height.px': 0, 'top.px': 0, 'left.px': 0, }; accept: string; constructor(private serverConfig: ServerConfigService) {} ngOnInit() { this.accept = this.serverConfig.serverConfig.permittedAssetTypes.join(','); this.fitDropZoneToTarget(); } @HostListener('document:dragenter') onDragEnter() { this.dragging = true; this.fitDropZoneToTarget(); } // DragEvent is not supported in Safari, see https://github.com/vendure-ecommerce/vendure/pull/284 @HostListener('document:dragleave', ['$event']) onDragLeave(event: any) { if (!event.clientX && !event.clientY) { this.dragging = false; } } /** * Preventing this event is required to make dropping work. * See https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API#Define_a_drop_zone */ onDragOver(event: any) { event.preventDefault(); } // DragEvent is not supported in Safari, see https://github.com/vendure-ecommerce/vendure/pull/284 onDrop(event: any) { event.preventDefault(); this.dragging = false; this.overDropZone = false; const files = Array.from<DataTransferItem>(event.dataTransfer ? event.dataTransfer.items : []) .map(i => i.getAsFile()) .filter(notNullOrUndefined); this.selectFiles.emit(files); } select(event: Event) { const files = (event.target as HTMLInputElement).files; if (files) { this.selectFiles.emit(Array.from(files)); } } private fitDropZoneToTarget() { const target = document.querySelector(this.dropZoneTarget) as HTMLElement; if (target) { const rect = target.getBoundingClientRect(); this.dropZoneStyle['width.px'] = rect.width; this.dropZoneStyle['height.px'] = rect.height; this.dropZoneStyle['top.px'] = rect.top; this.dropZoneStyle['left.px'] = rect.left; } } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output, SimpleChanges, } from '@angular/core'; import { SelectionManager } from '../../../common/utilities/selection-manager'; import { ModalService } from '../../../providers/modal/modal.service'; import { AssetPreviewDialogComponent } from '../asset-preview-dialog/asset-preview-dialog.component'; import { AssetLike } from './asset-gallery.types'; @Component({ selector: 'vdr-asset-gallery', templateUrl: './asset-gallery.component.html', styleUrls: ['./asset-gallery.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AssetGalleryComponent implements OnChanges { @Input() assets: AssetLike[]; /** * If true, allows multiple assets to be selected by ctrl+clicking. */ @Input() multiSelect = false; @Input() canDelete = false; @Output() selectionChange = new EventEmitter<AssetLike[]>(); @Output() deleteAssets = new EventEmitter<AssetLike[]>(); @Output() editAssetClick = new EventEmitter<void>(); selectionManager = new SelectionManager<AssetLike>({ multiSelect: this.multiSelect, itemsAreEqual: (a, b) => a.id === b.id, additiveMode: false, }); constructor(private modalService: ModalService) {} ngOnChanges(changes: SimpleChanges) { if (this.assets) { for (const asset of this.selectionManager.selection) { // Update any selected assets with any changes const match = this.assets.find(a => a.id === asset.id); if (match) { Object.assign(asset, match); } } } if (changes['assets']) { this.selectionManager.setCurrentItems(this.assets); } if (changes['multiSelect']) { this.selectionManager.setMultiSelect(this.multiSelect); } } toggleSelection(asset: AssetLike, event?: MouseEvent) { this.selectionManager.toggleSelection(asset, event); this.selectionChange.emit(this.selectionManager.selection); } selectMultiple(assets: AssetLike[]) { this.selectionManager.selectMultiple(assets); this.selectionChange.emit(this.selectionManager.selection); } isSelected(asset: AssetLike): boolean { return this.selectionManager.isSelected(asset); } lastSelected(): AssetLike { return this.selectionManager.lastSelected(); } previewAsset(asset: AssetLike) { this.modalService .fromComponent(AssetPreviewDialogComponent, { size: 'xl', closable: true, locals: { asset, assets: this.assets }, }) .subscribe(); } entityInfoClick(event: MouseEvent) { event.preventDefault(); event.stopPropagation(); } }
import { ItemOf } from '../../../common/base-list.component'; import { GetAssetListQuery } from '../../../common/generated-types'; export type AssetLike = ItemOf<GetAssetListQuery, 'assets'>;
import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, OnInit, ViewChild, } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { PaginationInstance } from 'ngx-pagination'; import { BehaviorSubject, Observable, Subject } from 'rxjs'; import { debounceTime, delay, finalize, map, take as rxjsTake, takeUntil, tap } from 'rxjs/operators'; import { Asset, CreateAssetsMutation, GetAssetListQuery, GetAssetListQueryVariables, LogicalOperator, SortOrder, TagFragment, } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; import { QueryResult } from '../../../data/query-result'; import { Dialog } from '../../../providers/modal/modal.types'; import { NotificationService } from '../../../providers/notification/notification.service'; import { AssetGalleryComponent } from '../asset-gallery/asset-gallery.component'; import { AssetLike } from '../asset-gallery/asset-gallery.types'; import { AssetSearchInputComponent } from '../asset-search-input/asset-search-input.component'; /** * @description * A dialog which allows the creation and selection of assets. * * @example * ```ts * selectAssets() { * this.modalService * .fromComponent(AssetPickerDialogComponent, { * size: 'xl', * }) * .subscribe(result => { * if (result && result.length) { * // ... * } * }); * } * ``` * * @docsCategory components */ @Component({ selector: 'vdr-asset-picker-dialog', templateUrl: './asset-picker-dialog.component.html', styleUrls: ['./asset-picker-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AssetPickerDialogComponent implements OnInit, AfterViewInit, OnDestroy, Dialog<Asset[]> { assets$: Observable<AssetLike[]>; allTags$: Observable<TagFragment[]>; paginationConfig: PaginationInstance = { currentPage: 1, itemsPerPage: 25, totalItems: 1, }; @ViewChild('assetSearchInputComponent') private assetSearchInputComponent: AssetSearchInputComponent; @ViewChild('assetGalleryComponent') private assetGalleryComponent: AssetGalleryComponent; multiSelect = true; initialTags: string[] = []; resolveWith: (result?: Asset[]) => void; selection: Asset[] = []; searchTerm$ = new BehaviorSubject<string | undefined>(undefined); filterByTags$ = new BehaviorSubject<TagFragment[] | undefined>(undefined); uploading = false; private listQuery: QueryResult<GetAssetListQuery, GetAssetListQueryVariables>; private destroy$ = new Subject<void>(); constructor(private dataService: DataService, private notificationService: NotificationService) {} ngOnInit() { this.listQuery = this.dataService.product.getAssetList(this.paginationConfig.itemsPerPage, 0); this.allTags$ = this.dataService.product.getTagList().mapSingle(data => data.tags.items); this.assets$ = this.listQuery.stream$.pipe( tap(result => (this.paginationConfig.totalItems = result.assets.totalItems)), map(result => result.assets.items), ); this.searchTerm$.pipe(debounceTime(250), takeUntil(this.destroy$)).subscribe(() => { this.fetchPage(this.paginationConfig.currentPage, this.paginationConfig.itemsPerPage); }); this.filterByTags$.pipe(debounceTime(100), takeUntil(this.destroy$)).subscribe(() => { this.fetchPage(this.paginationConfig.currentPage, this.paginationConfig.itemsPerPage); }); } ngAfterViewInit() { if (0 < this.initialTags.length) { this.allTags$ .pipe( rxjsTake(1), map(allTags => allTags.filter(tag => this.initialTags.includes(tag.value))), tap(tags => this.filterByTags$.next(tags)), delay(1), ) .subscribe(tags => this.assetSearchInputComponent.setTags(tags)); } } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); } pageChange(page: number) { this.paginationConfig.currentPage = page; this.fetchPage(this.paginationConfig.currentPage, this.paginationConfig.itemsPerPage); } itemsPerPageChange(itemsPerPage: number) { this.paginationConfig.itemsPerPage = itemsPerPage; this.fetchPage(this.paginationConfig.currentPage, this.paginationConfig.itemsPerPage); } cancel() { this.resolveWith(); } select() { this.resolveWith(this.selection); } createAssets(files: File[]) { if (files.length) { this.uploading = true; this.dataService.product .createAssets(files) .pipe(finalize(() => (this.uploading = false))) .subscribe(res => { this.fetchPage(this.paginationConfig.currentPage, this.paginationConfig.itemsPerPage); this.notificationService.success(_('asset.notify-create-assets-success'), { count: files.length, }); const assets = res.createAssets.filter(a => a.__typename === 'Asset') as AssetLike[]; this.assetGalleryComponent.selectMultiple(assets); }); } } private fetchPage(currentPage: number, itemsPerPage: number) { const take = +itemsPerPage; const skip = (currentPage - 1) * +itemsPerPage; const searchTerm = this.searchTerm$.value; const tags = this.filterByTags$.value?.map(t => t.value); this.listQuery.ref.refetch({ options: { skip, take, filter: { name: { contains: searchTerm, }, }, sort: { createdAt: SortOrder.DESC, }, tags, tagsOperator: LogicalOperator.AND, }, }); } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { gql } from 'apollo-angular'; import { Observable, of } from 'rxjs'; import { map, mergeMap, tap } from 'rxjs/operators'; import { GetAssetQuery, UpdateAssetInput } from '../../../common/generated-types'; import { ASSET_FRAGMENT, TAG_FRAGMENT } from '../../../data/definitions/product-definitions'; import { DataService } from '../../../data/providers/data.service'; import { Dialog } from '../../../providers/modal/modal.types'; import { AssetLike } from '../asset-gallery/asset-gallery.types'; export const ASSET_PREVIEW_QUERY = gql` query AssetPreviewQuery($id: ID!) { asset(id: $id) { ...Asset tags { ...Tag } } } ${ASSET_FRAGMENT} ${TAG_FRAGMENT} `; @Component({ selector: 'vdr-asset-preview-dialog', templateUrl: './asset-preview-dialog.component.html', styleUrls: ['./asset-preview-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AssetPreviewDialogComponent implements Dialog<void>, OnInit { constructor(private dataService: DataService) { } asset: AssetLike; assets?: AssetLike[]; assetChanges?: UpdateAssetInput; resolveWith: (result?: void) => void; assetWithTags$: Observable<GetAssetQuery['asset']>; assetsWithTags$: Observable<Array<GetAssetQuery['asset']>>; ngOnInit() { this.assetWithTags$ = of(this.asset).pipe( mergeMap(asset => { if (this.hasTags(asset)) { return of(asset); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.dataService.product.getAsset(asset.id).mapSingle(data => data.asset!); } }), ); this.assetsWithTags$ = of(this.assets ?? []); } private hasTags(asset: AssetLike): asset is AssetLike & { tags: string[] } { return asset.hasOwnProperty('tags'); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { AssetLike } from '../asset-gallery/asset-gallery.types'; @Component({ selector: 'vdr-asset-preview-links', templateUrl: './asset-preview-links.component.html', styleUrls: ['./asset-preview-links.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AssetPreviewLinksComponent { @Input() asset: AssetLike; sizes = ['tiny', 'thumb', 'small', 'medium', 'large', 'full']; }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild, } from '@angular/core'; import { FormBuilder, UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { fromEvent, Subscription } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { CustomFieldConfig, UpdateAssetInput } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; import { ModalService } from '../../../providers/modal/modal.service'; import { NotificationService } from '../../../providers/notification/notification.service'; import { AssetLike } from '../asset-gallery/asset-gallery.types'; import { Point } from '../focal-point-control/focal-point-control.component'; import { ManageTagsDialogComponent } from '../manage-tags-dialog/manage-tags-dialog.component'; export type PreviewPreset = 'tiny' | 'thumb' | 'small' | 'medium' | 'large' | ''; @Component({ selector: 'vdr-asset-preview', templateUrl: './asset-preview.component.html', styleUrls: ['./asset-preview.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AssetPreviewComponent implements OnInit, OnDestroy { @Input() asset: AssetLike; @Input() assets?: AssetLike[]; @Input() editable = false; @Input() customFields: CustomFieldConfig[] = []; @Input() customFieldsForm: UntypedFormGroup | undefined; @Output() assetChange = new EventEmitter<Omit<UpdateAssetInput, 'focalPoint'>>(); @Output() editClick = new EventEmitter(); form = this.formBuilder.group({ name: '', tags: [[] as string[]], }); size: PreviewPreset = 'medium'; width = 0; height = 0; centered = true; settingFocalPoint = false; lastFocalPoint?: Point; previewAssetIndex = 0; disableNextButton = false; disablePreviousButton = false; showSlideButtons = false; @ViewChild('imageElement', { static: true }) private imageElementRef: ElementRef<HTMLImageElement>; @ViewChild('previewDiv', { static: true }) private previewDivRef: ElementRef<HTMLDivElement>; private subscription: Subscription; private sizePriorToSettingFocalPoint: PreviewPreset; constructor( private formBuilder: FormBuilder, private dataService: DataService, private notificationService: NotificationService, private changeDetector: ChangeDetectorRef, private modalService: ModalService, ) { } get fpx(): number | null { return this.asset.focalPoint ? this.asset.focalPoint.x : null; } get fpy(): number | null { return this.asset.focalPoint ? this.asset.focalPoint.y : null; } ngOnInit() { const { focalPoint } = this.asset; if (this.assets?.length) { this.showSlideButtons = true; this.previewAssetIndex = this.assets.findIndex(asset => asset.id === this.asset.id) || 0; } else { this.showSlideButtons = false; this.updateButtonAccessibility(); } this.updateButtonAccessibility(); this.form.get('name')?.setValue(this.asset.name); this.form.get('tags')?.setValue(this.asset.tags?.map(t => t.value)); this.subscription = this.form.valueChanges.subscribe(value => { this.assetChange.emit({ id: this.asset.id, name: value.name, tags: value.tags, }); }); this.subscription.add( fromEvent(window, 'resize') .pipe(debounceTime(50)) .subscribe(() => { this.updateDimensions(); this.changeDetector.markForCheck(); }), ); } ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } getSourceFileName(): string { const parts = this.asset.source.split(/[\\\/]/g); return parts[parts.length - 1]; } onImageLoad() { this.updateDimensions(); this.changeDetector.markForCheck(); } updateDimensions() { const img = this.imageElementRef.nativeElement; const container = this.previewDivRef.nativeElement; const imgWidth = img.naturalWidth; const imgHeight = img.naturalHeight; const containerWidth = container.offsetWidth; const containerHeight = container.offsetHeight; const constrainToContainer = this.settingFocalPoint; if (constrainToContainer) { const controlsMarginPx = 48 * 2; const availableHeight = containerHeight - controlsMarginPx; const availableWidth = containerWidth; const hRatio = imgHeight / availableHeight; const wRatio = imgWidth / availableWidth; const imageExceedsAvailableDimensions = 1 < hRatio || 1 < wRatio; if (imageExceedsAvailableDimensions) { const factor = hRatio < wRatio ? wRatio : hRatio; this.width = Math.round(imgWidth / factor); this.height = Math.round(imgHeight / factor); this.centered = true; return; } } this.width = imgWidth; this.height = imgHeight; this.centered = imgWidth <= containerWidth && imgHeight <= containerHeight; } setFocalPointStart() { this.sizePriorToSettingFocalPoint = this.size; this.size = 'medium'; this.settingFocalPoint = true; this.lastFocalPoint = this.asset.focalPoint || { x: 0.5, y: 0.5 }; this.updateDimensions(); } removeFocalPoint() { this.dataService.product .updateAsset({ id: this.asset.id, focalPoint: null, }) .subscribe( () => { this.notificationService.success(_('asset.update-focal-point-success')); this.asset = { ...this.asset, focalPoint: null }; this.changeDetector.markForCheck(); }, () => this.notificationService.error(_('asset.update-focal-point-error')), ); } onFocalPointChange(point: Point) { this.lastFocalPoint = point; } setFocalPointCancel() { this.settingFocalPoint = false; this.lastFocalPoint = undefined; this.size = this.sizePriorToSettingFocalPoint; } setFocalPointEnd() { this.settingFocalPoint = false; this.size = this.sizePriorToSettingFocalPoint; if (this.lastFocalPoint) { const { x, y } = this.lastFocalPoint; this.lastFocalPoint = undefined; this.dataService.product .updateAsset({ id: this.asset.id, focalPoint: { x, y }, }) .subscribe( () => { this.notificationService.success(_('asset.update-focal-point-success')); this.asset = { ...this.asset, focalPoint: { x, y } }; this.changeDetector.markForCheck(); }, () => this.notificationService.error(_('asset.update-focal-point-error')), ); } } manageTags() { this.modalService .fromComponent(ManageTagsDialogComponent, { size: 'sm', }) .subscribe(result => { if (result) { this.notificationService.success(_('common.notify-updated-tags-success')); } }); } nextImage() { this.previewAssetIndex = this.previewAssetIndex + 1; if (Array.isArray(this.assets)) { this.asset = this.assets[this.previewAssetIndex]; this.updateButtonAccessibility(); } } previousImage() { this.previewAssetIndex = this.previewAssetIndex - 1; if (Array.isArray(this.assets)) { this.asset = this.assets[this.previewAssetIndex]; this.updateButtonAccessibility(); } } updateButtonAccessibility() { this.disableNextButton = this.assets?.[this.previewAssetIndex + 1]?.id ? false : true; this.disablePreviousButton = this.assets?.[this.previewAssetIndex - 1]?.id ? false : true; } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core'; import { NgSelectComponent, SELECTION_MODEL_FACTORY } from '@ng-select/ng-select'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { SearchProductsQuery, TagFragment } from '../../../common/generated-types'; import { SingleSearchSelectionModelFactory } from '../../../common/single-search-selection-model'; @Component({ selector: 'vdr-asset-search-input', templateUrl: './asset-search-input.component.html', styleUrls: ['./asset-search-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [{ provide: SELECTION_MODEL_FACTORY, useValue: SingleSearchSelectionModelFactory }], }) export class AssetSearchInputComponent { @Input() tags: TagFragment[]; @Output() searchTermChange = new EventEmitter<string>(); @Output() tagsChange = new EventEmitter<TagFragment[]>(); @ViewChild('selectComponent', { static: true }) private selectComponent: NgSelectComponent; private lastTerm = ''; private lastTagIds: string[] = []; setSearchTerm(term: string | null) { if (term) { this.selectComponent.select({ label: term, value: { label: term } }); } else { const currentTerm = this.selectComponent.selectedItems.find(i => !this.isTag(i.value)); if (currentTerm) { this.selectComponent.unselect(currentTerm); } } } setTags(tags: TagFragment[]) { const items = this.selectComponent.items; this.selectComponent.selectedItems.forEach(item => { if (this.isTag(item.value) && !tags.map(t => t.id).includes(item.id)) { this.selectComponent.unselect(item); } }); tags.map(tag => items?.find(item => this.isTag(item) && item.id === tag.id)) .filter(notNullOrUndefined) .forEach(item => { const isSelected = this.selectComponent.selectedItems.find(i => { const val = i.value; if (this.isTag(val)) { return val.id === item.id; } return false; }); if (!isSelected) { this.selectComponent.select({ label: '', value: item }); } }); } filterTagResults = ( term: string, item: SearchProductsQuery['search']['facetValues'] | { label: string }, ) => { if (!this.isTag(item)) { return false; } return item.value.toLowerCase().startsWith(term.toLowerCase()); }; onSelectChange(selectedItems: Array<TagFragment | { label: string }>) { if (!Array.isArray(selectedItems)) { selectedItems = [selectedItems]; } const searchTermItems = selectedItems.filter(item => !this.isTag(item)); if (1 < searchTermItems.length) { for (let i = 0; i < searchTermItems.length - 1; i++) { // this.selectComponent.unselect(searchTermItems[i] as any); } } const searchTermItem = searchTermItems[searchTermItems.length - 1] as { label: string } | undefined; const searchTerm = searchTermItem ? searchTermItem.label : ''; const tags = selectedItems.filter(this.isTag); if (searchTerm !== this.lastTerm) { this.searchTermChange.emit(searchTerm); this.lastTerm = searchTerm; } if (this.lastTagIds.join(',') !== tags.map(t => t.id).join(',')) { this.tagsChange.emit(tags); this.lastTagIds = tags.map(t => t.id); } } isSearchHeaderSelected(): boolean { return this.selectComponent.itemsList.markedIndex === -1; } addTagFn(item: any) { return { label: item }; } private isTag = (input: unknown): input is TagFragment => typeof input === 'object' && !!input && input.hasOwnProperty('value'); }
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, HostBinding, Input, Output, } from '@angular/core'; import { unique } from '@vendure/common/lib/unique'; import { Asset, Permission } from '../../../common/generated-types'; import { ModalService } from '../../../providers/modal/modal.service'; import { AssetPickerDialogComponent } from '../asset-picker-dialog/asset-picker-dialog.component'; import { AssetPreviewDialogComponent } from '../asset-preview-dialog/asset-preview-dialog.component'; export interface AssetChange { assets: Asset[]; featuredAsset: Asset | undefined; } /** * A component which displays the Assets, and allows assets to be removed and * added, and for the featured asset to be set. * * Note: rather complex code for drag drop is due to a limitation of the default CDK implementation * which is addressed by a work-around from here: https://github.com/angular/components/issues/13372#issuecomment-483998378 */ @Component({ selector: 'vdr-assets', templateUrl: './assets.component.html', styleUrls: ['./assets.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AssetsComponent { @Input('assets') set assetsSetter(val: Asset[]) { // create a new non-readonly array of assets this.assets = (val || []).slice(); } @Input() featuredAsset: Asset | undefined; @HostBinding('class.compact') @Input() compact = false; // eslint-disable-next-line @angular-eslint/no-output-native @Output() change = new EventEmitter<AssetChange>(); public assets: Asset[] = []; @Input() updatePermissions: string | string[] | Permission | Permission[]; constructor( private modalService: ModalService, private changeDetector: ChangeDetectorRef, ) {} selectAssets() { this.modalService .fromComponent(AssetPickerDialogComponent, { size: 'xl', }) .subscribe(result => { if (result && result.length) { this.assets = unique(this.assets.concat(result), 'id'); if (!this.featuredAsset) { this.featuredAsset = result[0]; } this.emitChangeEvent(this.assets, this.featuredAsset); this.changeDetector.markForCheck(); } }); } setAsFeatured(asset: Asset) { this.featuredAsset = asset; this.emitChangeEvent(this.assets, asset); } isFeatured(asset: Asset): boolean { return !!this.featuredAsset && this.featuredAsset.id === asset.id; } previewAsset(asset: Asset) { this.modalService .fromComponent(AssetPreviewDialogComponent, { size: 'xl', closable: true, locals: { asset, assets: this.assets }, }) .subscribe(); } removeAsset(asset: Asset) { this.assets = this.assets.filter(a => a.id !== asset.id); if (this.featuredAsset && this.featuredAsset.id === asset.id) { this.featuredAsset = this.assets.length > 0 ? this.assets[0] : undefined; } this.emitChangeEvent(this.assets, this.featuredAsset); } private emitChangeEvent(assets: Asset[], featuredAsset: Asset | undefined) { this.change.emit({ assets, featuredAsset, }); } dropListDropped(event: CdkDragDrop<number>) { moveItemInArray(this.assets, event.previousContainer.data, event.container.data); this.emitChangeEvent(this.assets, this.featuredAsset); } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { combineLatest } from 'rxjs'; import { ItemOf } from '../../../common/base-list.component'; import { GetChannelsQuery } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; import { Dialog } from '../../../providers/modal/modal.types'; import { NotificationService } from '../../../providers/notification/notification.service'; type Channel = ItemOf<GetChannelsQuery, 'channels'>; @Component({ selector: 'vdr-assign-to-channel-dialog', templateUrl: './assign-to-channel-dialog.component.html', styleUrls: ['./assign-to-channel-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AssignToChannelDialogComponent implements OnInit, Dialog<Channel[]> { selectedChannels: Channel[] = []; currentChannel: Channel; availableChannels: Channel[]; resolveWith: (result?: Channel[]) => void; selectedChannelIdControl = new UntypedFormControl(); itemNames: string; nMore: number; constructor(private dataService: DataService, private notificationService: NotificationService) {} ngOnInit() { const activeChannelId$ = this.dataService.client .userStatus() .mapSingle(({ userStatus }) => userStatus.activeChannelId); const allChannels$ = this.dataService.settings.getChannels().mapSingle(data => data.channels); combineLatest(activeChannelId$, allChannels$).subscribe(([activeChannelId, channels]) => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.currentChannel = channels.items.find(c => c.id === activeChannelId)!; this.availableChannels = channels.items; }); this.selectedChannelIdControl.valueChanges.subscribe(ids => { this.selectChannel(ids); }); } selectChannel(channelIds: string[]) { this.selectedChannels = this.availableChannels.filter(c => channelIds.includes(c.id)); } assign() { const selectedChannels = this.selectedChannels; if (selectedChannels.length > 0) { this.resolveWith(selectedChannels); } } cancel() { this.resolveWith(); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Injector, Input, OnDestroy, OnInit, } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Observable, Subscription } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { SelectionManager } from '../../../common/utilities/selection-manager'; import { DataService } from '../../../data/providers/data.service'; import { BulkActionRegistryService } from '../../../providers/bulk-action-registry/bulk-action-registry.service'; import { BulkAction, BulkActionFunctionContext, BulkActionLocationId, } from '../../../providers/bulk-action-registry/bulk-action-types'; @Component({ selector: 'vdr-bulk-action-menu', templateUrl: './bulk-action-menu.component.html', styleUrls: ['./bulk-action-menu.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class BulkActionMenuComponent<T = any> implements OnInit, OnDestroy { @Input() locationId: BulkActionLocationId; @Input() selectionManager: SelectionManager<T>; @Input() hostComponent: any; actions$: Observable< Array<BulkAction<T> & { display: boolean; translationVars: Record<string, string | number> }> >; userPermissions: string[] = []; private subscription: Subscription; private onClearSelectionFns: Array<() => void> = []; constructor( private bulkActionRegistryService: BulkActionRegistryService, private injector: Injector, private route: ActivatedRoute, private dataService: DataService, private changeDetectorRef: ChangeDetectorRef, ) {} ngOnInit(): void { const actionsForLocation = this.bulkActionRegistryService.getBulkActionsForLocation(this.locationId); this.actions$ = this.selectionManager.selectionChanges$.pipe( switchMap(selection => Promise.all( actionsForLocation.map(async action => { let display = true; let translationVars = {}; const isVisibleFn = action.isVisible; const getTranslationVarsFn = action.getTranslationVars; const functionContext: BulkActionFunctionContext<T, any> = { injector: this.injector, hostComponent: this.hostComponent, route: this.route, selection, }; if (typeof isVisibleFn === 'function') { display = await isVisibleFn(functionContext); } if (typeof getTranslationVarsFn === 'function') { translationVars = await getTranslationVarsFn(functionContext); } return { ...action, display, translationVars }; }), ), ), ); this.subscription = this.dataService.client .userStatus() .mapStream(({ userStatus }) => { this.userPermissions = userStatus.permissions; }) .subscribe(); } ngOnDestroy() { this.subscription?.unsubscribe(); } hasPermissions(bulkAction: Pick<BulkAction, 'requiresPermission'>) { if (!this.userPermissions) { return false; } if (!bulkAction.requiresPermission) { return true; } if (typeof bulkAction.requiresPermission === 'string') { return this.userPermissions.includes(bulkAction.requiresPermission); } if (typeof bulkAction.requiresPermission === 'function') { return bulkAction.requiresPermission(this.userPermissions); } } actionClick(event: MouseEvent, action: BulkAction) { action.onClick({ injector: this.injector, event, route: this.route, selection: this.selectionManager.selection, hostComponent: this.hostComponent, clearSelection: () => this.selectionManager.clearSelection(), }); } clearSelection() { this.selectionManager.clearSelection(); this.changeDetectorRef.markForCheck(); this.onClearSelectionFns.forEach(fn => fn()); } onClearSelection(callback: () => void) { this.onClearSelectionFns.push(callback); } }
import { ChangeDetectionStrategy, Component, ContentChild, Directive, Input, TemplateRef, } from '@angular/core'; @Directive({ selector: '[vdrCardControls]', }) export class CardControlsDirective {} @Component({ selector: 'vdr-card', templateUrl: './card.component.html', styleUrls: ['./card.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CardComponent { @Input() title: string; @Input() paddingX = true; @ContentChild(CardControlsDirective, { read: TemplateRef }) controlsTemplate: TemplateRef<any>; }
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { Observable } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { Channel, CurrentUserChannel } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; @Component({ selector: 'vdr-channel-assignment-control', templateUrl: './channel-assignment-control.component.html', styleUrls: ['./channel-assignment-control.component.scss'], changeDetection: ChangeDetectionStrategy.Default, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: ChannelAssignmentControlComponent, multi: true, }, ], }) export class ChannelAssignmentControlComponent implements OnInit, ControlValueAccessor { @Input() multiple = true; @Input() includeDefaultChannel = true; @Input() disableChannelIds: string[] = []; channels$: Observable<CurrentUserChannel[]>; value: CurrentUserChannel[] = []; disabled = false; private onChange: (value: any) => void; private onTouched: () => void; private channels: CurrentUserChannel[] | undefined; private lastIncomingValue: any; constructor(private dataService: DataService) {} ngOnInit() { this.channels$ = this.dataService.client.userStatus().single$.pipe( map(({ userStatus }) => userStatus.channels.filter(c => this.includeDefaultChannel ? true : c.code !== DEFAULT_CHANNEL_CODE, ), ), tap(channels => { if (!this.channels) { this.channels = channels; this.mapIncomingValueToChannels(this.lastIncomingValue); } else { this.channels = channels; } }), ); } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } writeValue(obj: unknown): void { this.lastIncomingValue = obj; this.mapIncomingValueToChannels(obj); } focussed() { if (this.onTouched) { this.onTouched(); } } channelIsDisabled(id: string) { return this.disableChannelIds.includes(id); } valueChanged(value: CurrentUserChannel[] | CurrentUserChannel | undefined) { if (Array.isArray(value)) { this.onChange(value.map(c => c.id)); } else { this.onChange([value ? value.id : undefined]); } } compareFn(c1: Channel | string, c2: Channel | string): boolean { const c1id = typeof c1 === 'string' ? c1 : c1.id; const c2id = typeof c2 === 'string' ? c2 : c2.id; return c1id === c2id; } private mapIncomingValueToChannels(value: unknown) { if (Array.isArray(value)) { if (typeof value[0] === 'string') { this.value = value .map(id => this.channels?.find(c => c.id === id)) .filter(notNullOrUndefined); } else { this.value = value; } } else { if (typeof value === 'string') { const channel = this.channels?.find(c => c.id === value); if (channel) { this.value = [channel]; } } else if (value && (value as any).id) { this.value = [value as any]; } } } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; @Component({ selector: 'vdr-channel-badge', templateUrl: './channel-badge.component.html', styleUrls: ['./channel-badge.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ChannelBadgeComponent { @Input() channelCode: string; get isDefaultChannel(): boolean { return this.channelCode === DEFAULT_CHANNEL_CODE; } }
import { ChangeDetectionStrategy, Component, ElementRef, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewChild, } from '@angular/core'; import { easings, LineChart, LineChartData, LineChartOptions } from 'chartist'; import { CurrencyService } from '../../../providers/currency/currency.service'; import { tooltipPlugin } from './tooltip-plugin'; export interface ChartFormatOptions { formatValueAs: 'currency' | 'number'; currencyCode?: string; locale?: string; } export interface ChartEntry { label: string; value: number; formatOptions: ChartFormatOptions; } @Component({ selector: 'vdr-chart', templateUrl: './chart.component.html', styleUrls: ['./chart.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ChartComponent implements OnInit, OnChanges, OnDestroy { @Input() entries: ChartEntry[] = []; @Input() options?: LineChartOptions = {}; @ViewChild('chartDiv', { static: true }) private chartDivRef: ElementRef<HTMLDivElement>; private chart: LineChart; constructor(private currencyService: CurrencyService) {} ngOnInit() { this.chart = new LineChart( this.chartDivRef.nativeElement, this.entriesToLineChartData(this.entries ?? []), { low: 0, showArea: true, showLine: true, showPoint: true, fullWidth: true, axisX: { showLabel: false, showGrid: false, offset: 1, }, axisY: { showLabel: false, offset: 1, }, plugins: [ tooltipPlugin({ currencyPrecision: this.currencyService.precision, currencyPrecisionFactor: this.currencyService.precisionFactor, }), ], ...this.options, }, ); this.chart.on('draw', data => { if (data.type === 'line' || data.type === 'area') { data.element.animate({ d: { begin: 2000 * data.index, dur: 2000, from: data.path.clone().scale(1, 0).translate(0, data.chartRect.height()).stringify(), to: data.path.clone().stringify(), easing: easings.easeOutQuint, }, }); } }); // Create the gradient definition on created event (always after chart re-render) this.chart.on('created', ctx => { const defs = ctx.svg.elem('defs'); defs.elem('linearGradient', { id: 'gradient', x1: 0, y1: 1, x2: 0, y2: 0, }) .elem('stop', { offset: 0, 'stop-color': 'var(--color-primary-400)', 'stop-opacity': 0.3, }) .parent() ?.elem('stop', { offset: 1, 'stop-color': 'var(--color-primary-500)', }); }); } ngOnChanges(changes: SimpleChanges) { if ('entries' in changes && this.chart) { this.chart.update(this.entriesToLineChartData(this.entries ?? [])); } } ngOnDestroy() { this.chart?.detach(); } private entriesToLineChartData(entries: ChartEntry[]): LineChartData { const labels = entries.map(({ label }) => label); const series = [ entries.map(({ label, value, formatOptions }) => ({ meta: { label, formatOptions }, value })), ]; return { labels, series }; } }
/** * Based on https://github.com/tmmdata/chartist-plugin-tooltip/blob/master/src/scripts/chartist-plugin-tooltip.js * */ /* global Chartist */ import { DrawEvent, LineChart } from 'chartist'; import { ChartFormatOptions } from './chart.component'; const defaultOptions = { currency: undefined, currencyPrecision: 2, currencyPrecisionFactor: 100, currencyFormatCallback: undefined, tooltipOffset: { x: 0, y: -20, }, anchorToPoint: false, appendToBody: false, class: undefined, pointClass: 'ct-point', }; export function tooltipPlugin(userOptions?: Partial<typeof defaultOptions>) { return function tooltip(chart: LineChart) { const options = { ...defaultOptions, ...userOptions, }; const $chart = (chart as any).container as HTMLDivElement; let $toolTip = $chart.querySelector('.chartist-tooltip') as HTMLDivElement; if (!$toolTip) { $toolTip = document.createElement('div'); $toolTip.className = !options.class ? 'chartist-tooltip' : 'chartist-tooltip ' + options.class; if (!options.appendToBody) { $chart.appendChild($toolTip); } else { document.body.appendChild($toolTip); } } let height = $toolTip.offsetHeight; let width = $toolTip.offsetWidth; const points: Array<{ event: DrawEvent; x: number; }> = []; function getClosestPoint(mouseX: number): DrawEvent { let closestElement: DrawEvent | null = null; let closestDistance = Infinity; // Iterate through the points array to find the closest element for (const point of points) { const elementX = point.x; const distance = calculateDistance(mouseX, elementX); if (distance < closestDistance) { closestElement = point.event; closestDistance = distance; } } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return closestElement!; } chart.on('draw', data => { if (data.type === 'point') { const element = data.element; points[data.index] = { event: data, x: data.element.getNode().getBoundingClientRect().x, }; } }); hide($toolTip); function on(event, selector, callback) { $chart.addEventListener( event, function (e) { if (!selector || hasClass(e.target, selector)) { callback(e); } }, { passive: true }, ); } on('mousemove', undefined, (event: MouseEvent) => { const closestPoint = getClosestPoint(event.clientX); if (!closestPoint) { return; } points.forEach(point => point.event.element.removeClass('ct-tooltip-hover')); closestPoint.element.addClass('ct-tooltip-hover'); const $point = closestPoint.element.getNode() as HTMLElement; const meta: { label: string; formatOptions: ChartFormatOptions; } = closestPoint.meta; const value = $point.getAttribute('ct:value'); const dateFormatter = new Intl.DateTimeFormat(meta.formatOptions.locale); const formattedValue = meta.formatOptions.formatValueAs === 'currency' ? new Intl.NumberFormat(meta.formatOptions.locale, { style: 'currency', currency: meta.formatOptions.currencyCode, minimumFractionDigits: options.currencyPrecision, maximumFractionDigits: options.currencyPrecision, }).format(+(value ?? 0) / options.currencyPrecisionFactor) : new Intl.NumberFormat(meta.formatOptions.locale).format(+(value ?? 0)); const tooltipText = ` <div class="tooltip-date">${dateFormatter.format(new Date(meta.label))}</div> <div class="tooltip-value">${formattedValue}</div> `; $toolTip.innerHTML = tooltipText; setPosition($point); show($toolTip); // Remember height and width to avoid wrong position in IE height = $toolTip.offsetHeight; width = $toolTip.offsetWidth; }); on('mouseleave', undefined, () => { hide($toolTip); }); function setPosition(element: HTMLElement) { height = height || $toolTip.offsetHeight; width = width || $toolTip.offsetWidth; const { x: elX, y: elY, width: elWidth, height: elHeight } = element.getBoundingClientRect(); const offsetX = -width / 2 + options.tooltipOffset.x; const offsetY = -height + options.tooltipOffset.y; let anchorX; let anchorY; if (!options.appendToBody) { const box = $chart.getBoundingClientRect(); const left = elX - box.left - window.pageXOffset; const top = elY - box.top - window.pageYOffset; $toolTip.style.top = (anchorY || top) + offsetY + 'px'; $toolTip.style.left = (anchorX || left) + offsetX + 'px'; } else { $toolTip.style.top = elY + offsetY + 'px'; $toolTip.style.left = elX + offsetX + 'px'; } } }; } function show(element) { if (!hasClass(element, 'tooltip-show')) { element.className = element.className + ' tooltip-show'; } } function hide(element) { const regex = new RegExp('tooltip-show' + '\\s*', 'gi'); element.className = element.className.replace(regex, '').trim(); } function hasClass(element, className) { return (' ' + element.getAttribute('class') + ' ').indexOf(' ' + className + ' ') > -1; } function calculateDistance(x1, x2) { return Math.abs(x2 - x1); }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; /** * @description * A chip component for displaying a label with an optional action icon. * * @example * ```HTML * <vdr-chip [colorFrom]="item.value" * icon="close" * (iconClick)="clear(item)"> * {{ item.value }}</vdr-chip> * ``` * @docsCategory components */ @Component({ selector: 'vdr-chip', templateUrl: './chip.component.html', styleUrls: ['./chip.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ChipComponent { /** * @description * The icon should be the name of one of the available Clarity icons: https://clarity.design/foundation/icons/shapes/ * */ @Input() icon: string; @Input() invert = false; /** * @description * If set, the chip will have an auto-generated background * color based on the string value passed in. */ @Input() colorFrom = ''; /** * @description * The color of the chip can also be one of the standard status colors. */ @Input() colorType: 'error' | 'success' | 'warning'; @Output() iconClick = new EventEmitter<MouseEvent>(); }
import { ChangeDetectionStrategy, Component, EventEmitter, forwardRef, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, } from '@angular/core'; import { AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, UntypedFormControl, UntypedFormGroup, ValidationErrors, Validator, Validators, } from '@angular/forms'; import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { ConfigArg, ConfigArgDefinition, ConfigurableOperation, ConfigurableOperationDefinition, } from '../../../common/generated-types'; import { getDefaultConfigArgValue } from '../../../common/utilities/configurable-operation-utils'; import { interpolateDescription } from '../../../common/utilities/interpolate-description'; import { CurrencyService } from '../../../providers/currency/currency.service'; /** * A form input which renders a card with the internal form fields of the given ConfigurableOperation. */ @Component({ selector: 'vdr-configurable-input', templateUrl: './configurable-input.component.html', styleUrls: ['./configurable-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: ConfigurableInputComponent, multi: true, }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => ConfigurableInputComponent), multi: true, }, ], }) export class ConfigurableInputComponent implements OnInit, OnChanges, OnDestroy, ControlValueAccessor, Validator { @Input() operation?: ConfigurableOperation; @Input() operationDefinition?: ConfigurableOperationDefinition; @Input() readonly = false; @Input() removable = true; @Input() position = 0; @Input() hideDescription = false; @Output() remove = new EventEmitter<ConfigurableOperation>(); argValues: { [name: string]: any } = {}; onChange: (val: any) => void; onTouch: () => void; form = new UntypedFormGroup({}); positionChange$: Observable<number>; private positionChangeSubject = new BehaviorSubject<number>(0); private subscription: Subscription; constructor(private currencyService: CurrencyService) {} interpolateDescription(): string { if (this.operationDefinition) { return interpolateDescription( this.operationDefinition, this.form.value, this.currencyService.precisionFactor, ); } else { return ''; } } ngOnInit() { this.positionChange$ = this.positionChangeSubject.asObservable(); } ngOnChanges(changes: SimpleChanges) { if ('operation' in changes || 'operationDefinition' in changes) { this.createForm(); } if ('position' in changes) { this.positionChangeSubject.next(this.position); } } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouch = fn; } setDisabledState(isDisabled: boolean) { if (isDisabled) { this.form.disable(); } else { this.form.enable(); } } writeValue(value: any): void { if (value) { this.form.patchValue(value); } } trackByName(index: number, arg: ConfigArg): string { return arg.name; } getArgDef(arg: ConfigArg): ConfigArgDefinition | undefined { return this.operationDefinition?.args.find(a => a.name === arg.name); } private createForm() { if (!this.operation) { return; } if (this.subscription) { this.subscription.unsubscribe(); } this.form = new UntypedFormGroup({}); (this.form as any).__id = Math.random().toString(36).substr(10); if (this.operation.args) { for (const arg of this.operationDefinition?.args || []) { let value: any = this.operation.args.find(a => a.name === arg.name)?.value; if (value === undefined) { value = getDefaultConfigArgValue(arg); } const validators = arg.list ? undefined : arg.required ? Validators.required : undefined; this.form.addControl(arg.name, new UntypedFormControl(value, validators)); } } this.subscription = this.form.valueChanges.subscribe(value => { if (this.onChange) { this.onChange({ code: this.operation && this.operation.code, args: value, }); } if (this.onTouch) { this.onTouch(); } }); } validate(c: AbstractControl): ValidationErrors | null { if (this.form.invalid) { return { required: true, }; } return null; } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, forwardRef, OnDestroy } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { Subscription } from 'rxjs'; import { CurrencyCode } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; @Component({ selector: 'vdr-currency-code-selector', templateUrl: './currency-code-selector.component.html', styleUrls: ['./currency-code-selector.component.css'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CurrencyCodeSelectorComponent), multi: true, }, ], }) export class CurrencyCodeSelectorComponent implements ControlValueAccessor, OnDestroy { currencyCodes = Object.values(CurrencyCode); private subscription: Subscription; private locale: string; protected value: string | undefined; onChangeFn: (value: any) => void; onTouchFn: (value: any) => void; searchCurrencyCodes = (term: string, item: CurrencyCode) => { const currencyCodeName = new Intl.DisplayNames([this.locale], { type: 'currency', }).of(item); return currencyCodeName?.toLowerCase().includes(term.toLowerCase()); }; constructor(dataService?: DataService, changeDetectorRef?: ChangeDetectorRef) { if (dataService && changeDetectorRef) { this.subscription = dataService.client .uiState() .mapStream(data => data.uiState) .subscribe(({ language, locale }) => { this.locale = language.replace(/_/g, '-'); if (locale) { this.locale += `-${locale}`; } changeDetectorRef.markForCheck(); }); } } writeValue(obj: any): void { this.value = obj; } registerOnChange(fn: any): void { this.onChangeFn = fn; } registerOnTouched(fn: any): void { this.onTouchFn = fn; } ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } }
import { Component, Injectable } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { ServerConfigService } from '@vendure/admin-ui/core'; import { Type } from '@vendure/common/lib/shared-types'; import { of } from 'rxjs'; import { LanguageCode } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; import { LocaleCurrencyNamePipe } from '../../pipes/locale-currency-name.pipe'; import { AffixedInputComponent } from '../affixed-input/affixed-input.component'; import { CurrencyInputComponent } from './currency-input.component'; class MockServerConfigService { serverConfig = { moneyStrategyPrecision: 2, }; } describe('CurrencyInputComponent', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [FormsModule], providers: [ { provide: DataService, useClass: MockDataService }, { provide: ServerConfigService, useClass: MockServerConfigService }, ], declarations: [ TestControlValueAccessorComponent, TestSimpleComponent, CurrencyInputComponent, AffixedInputComponent, LocaleCurrencyNamePipe, ], }).compileComponents(); })); it('should display the price as decimal with a simple binding', fakeAsync(() => { const fixture = createAndRunChangeDetection(TestSimpleComponent); const nativeInput = getNativeInput(fixture); expect(nativeInput.value).toBe('1.23'); })); it('should display the price as decimal', fakeAsync(() => { const fixture = createAndRunChangeDetection(TestControlValueAccessorComponent); const nativeInput = getNativeInput(fixture); expect(nativeInput.value).toBe('1.23'); })); it('should display 2 decimal places for multiples of 10', fakeAsync(() => { const fixture = createAndRunChangeDetection(TestControlValueAccessorComponent, 120); const nativeInput = getNativeInput(fixture); expect(nativeInput.value).toBe('1.20'); })); it('should discard decimal places from input value', fakeAsync(() => { const fixture = createAndRunChangeDetection(TestControlValueAccessorComponent, 123.5); const nativeInput = getNativeInput(fixture); expect(nativeInput.value).toBe('1.23'); })); it('should correctly round decimal value ', fakeAsync(() => { const fixture = createAndRunChangeDetection(TestControlValueAccessorComponent); const nativeInput = fixture.debugElement.query(By.css('input[type="number"]')); nativeInput.triggerEventHandler('input', { target: { value: 1.13 } }); tick(); fixture.detectChanges(); expect(fixture.componentInstance.price).toBe(113); })); it('should update model with integer values for values of more than 2 decimal places', fakeAsync(() => { const fixture = createAndRunChangeDetection(TestControlValueAccessorComponent); const nativeInput = fixture.debugElement.query(By.css('input[type="number"]')); nativeInput.triggerEventHandler('input', { target: { value: 1.567 } }); tick(); fixture.detectChanges(); expect(fixture.componentInstance.price).toBe(157); })); describe('currencies without minor units', () => { it('displays JPY without decimal places', fakeAsync(() => { MockDataService.language = LanguageCode.en; const fixture = createAndRunChangeDetection(TestSimpleComponent, 429900, 'JPY'); const nativeInput = getNativeInput(fixture); expect(nativeInput.value).toBe('4299'); })); it('increments JPY with a step of 1', fakeAsync(() => { MockDataService.language = LanguageCode.en; const fixture = createAndRunChangeDetection(TestSimpleComponent, 429900, 'JPY'); const nativeInputDebugEl = fixture.debugElement.query(By.css('input[type="number"]')); const nativeInput = getNativeInput(fixture); expect(nativeInput.step).toBe('1'); })); }); describe('currencyCode display', () => { it('displays currency code in correct position (prefix)', fakeAsync(() => { MockDataService.language = LanguageCode.en; const fixture = createAndRunChangeDetection(TestSimpleComponent, 4299, 'GBP'); const prefix = fixture.debugElement.query(By.css('.prefix')); const suffix = fixture.debugElement.query(By.css('.suffix')); expect(prefix.nativeElement.innerHTML).toBe('£'); expect(suffix).toBeNull(); })); it('displays currency code in correct position (suffix)', fakeAsync(() => { MockDataService.language = LanguageCode.fr; const fixture = createAndRunChangeDetection(TestSimpleComponent, 4299, 'GBP'); const prefix = fixture.debugElement.query(By.css('.prefix')); const suffix = fixture.debugElement.query(By.css('.suffix')); expect(prefix).toBeNull(); expect(suffix.nativeElement.innerHTML).toBe('£GB'); })); }); function createAndRunChangeDetection<T extends TestControlValueAccessorComponent | TestSimpleComponent>( component: Type<T>, priceValue = 123, currencyCode = '', ): ComponentFixture<T> { const fixture = TestBed.createComponent(component); if (fixture.componentInstance instanceof TestSimpleComponent && currencyCode) { fixture.componentInstance.currencyCode = currencyCode; } fixture.componentInstance.price = priceValue; fixture.detectChanges(); tick(); fixture.detectChanges(); return fixture; } function getNativeInput(_fixture: ComponentFixture<TestControlValueAccessorComponent>): HTMLInputElement { return _fixture.debugElement.query(By.css('input[type="number"]')).nativeElement; } }); @Component({ selector: 'vdr-test-component', template: ` <vdr-currency-input [(ngModel)]="price"></vdr-currency-input> `, }) class TestControlValueAccessorComponent { price = 123; } @Component({ selector: 'vdr-test-component', template: ` <vdr-currency-input [value]="price" [currencyCode]="currencyCode"></vdr-currency-input> `, }) class TestSimpleComponent { currencyCode = ''; price = 123; } @Injectable() class MockDataService { static language: LanguageCode = LanguageCode.en; client = { uiState() { return { mapStream(mapFn: any) { return of( mapFn({ uiState: { language: MockDataService.language, }, }), ); }, }; }, }; }
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs'; import { map } from 'rxjs/operators'; import { DataService } from '../../../data/providers/data.service'; import { CurrencyService } from '../../../providers/currency/currency.service'; /** * @description * A form input control which displays currency in decimal format, whilst working * with the integer cent value in the background. * * @example * ```HTML * <vdr-currency-input * [(ngModel)]="entityPrice" * [currencyCode]="currencyCode" * ></vdr-currency-input> * ``` * * @docsCategory components */ @Component({ selector: 'vdr-currency-input', templateUrl: './currency-input.component.html', styleUrls: ['./currency-input.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: CurrencyInputComponent, multi: true, }, ], }) export class CurrencyInputComponent implements ControlValueAccessor, OnInit, OnChanges, OnDestroy { @Input() disabled = false; @Input() readonly = false; @Input() value: number; @Input() currencyCode = ''; @Output() valueChange = new EventEmitter(); prefix$: Observable<string>; suffix$: Observable<string>; hasFractionPart = true; onChange: (val: any) => void; onTouch: () => void; _inputValue: string; private currencyCode$ = new BehaviorSubject<string>(''); private subscription: Subscription; readonly precision: number; readonly precisionFactor: number; constructor(private dataService: DataService, private currencyService: CurrencyService) { this.precision = currencyService.precision; this.precisionFactor = currencyService.precisionFactor; } ngOnInit() { const languageCode$ = this.dataService.client.uiState().mapStream(data => data.uiState.language); const shouldPrefix$ = combineLatest(languageCode$, this.currencyCode$).pipe( map(([languageCode, currencyCode]) => { if (!currencyCode) { return ''; } const locale = languageCode.replace(/_/g, '-'); const parts = ( new Intl.NumberFormat(locale, { style: 'currency', currency: currencyCode, currencyDisplay: 'symbol', }) as any ).formatToParts(); const NaNString = parts.find(p => p.type === 'nan')?.value ?? 'NaN'; const localised = new Intl.NumberFormat(locale, { style: 'currency', currency: currencyCode, currencyDisplay: 'symbol', }).format(undefined as any); return localised.indexOf(NaNString) > 0; }), ); this.prefix$ = shouldPrefix$.pipe(map(shouldPrefix => (shouldPrefix ? this.currencyCode : ''))); this.suffix$ = shouldPrefix$.pipe(map(shouldPrefix => (shouldPrefix ? '' : this.currencyCode))); this.subscription = combineLatest(languageCode$, this.currencyCode$).subscribe( ([languageCode, currencyCode]) => { if (!currencyCode) { return ''; } const locale = languageCode.replace(/_/g, '-'); const parts = ( new Intl.NumberFormat(locale, { style: 'currency', currency: currencyCode, currencyDisplay: 'symbol', }) as any ).formatToParts(123.45); this.hasFractionPart = !!parts.find(p => p.type === 'fraction'); this._inputValue = this.toNumericString(this._inputValue); }, ); } ngOnChanges(changes: SimpleChanges) { if ('value' in changes) { this.writeValue(changes['value'].currentValue); } if ('currencyCode' in changes) { this.currencyCode$.next(this.currencyCode); } } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouch = fn; } setDisabledState(isDisabled: boolean) { this.disabled = isDisabled; } onInput(value: string) { const integerValue = Math.round(+value * this.currencyService.precisionFactor); if (typeof this.onChange === 'function') { this.onChange(integerValue); } this.valueChange.emit(integerValue); const delta = Math.abs(Number(this._inputValue) - Number(value)); if (0.009 < delta && delta < 0.011) { this._inputValue = this.toNumericString(value); } else { this._inputValue = value; } } onFocus() { if (typeof this.onTouch === 'function') { this.onTouch(); } } writeValue(value: any): void { const numericValue = +value; if (!Number.isNaN(numericValue)) { this._inputValue = this.toNumericString(this.currencyService.toMajorUnits(Math.floor(value))); } } private toNumericString(value: number | string): string { return this.hasFractionPart ? Number(value).toFixed(this.precision) : Number(value).toFixed(0); } }
import { ChangeDetectionStrategy, Component, ComponentFactoryResolver, ComponentRef, Injector, Input, OnDestroy, OnInit, ViewContainerRef, } from '@angular/core'; import { UntypedFormGroup } from '@angular/forms'; import { Observable } from 'rxjs'; import { CustomDetailComponentLocationId } from '../../../common/component-registry-types'; import { CustomDetailComponent } from '../../../providers/custom-detail-component/custom-detail-component-types'; import { CustomDetailComponentService } from '../../../providers/custom-detail-component/custom-detail-component.service'; @Component({ selector: 'vdr-custom-detail-component-host', templateUrl: './custom-detail-component-host.component.html', styleUrls: ['./custom-detail-component-host.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomDetailComponentHostComponent implements OnInit, OnDestroy { @Input() locationId: CustomDetailComponentLocationId; @Input() entity$: Observable<any>; @Input() detailForm: UntypedFormGroup; private componentRefs: Array<ComponentRef<CustomDetailComponent>> = []; constructor( private viewContainerRef: ViewContainerRef, private customDetailComponentService: CustomDetailComponentService, private injector: Injector, ) {} ngOnInit(): void { const customComponents = this.customDetailComponentService.getCustomDetailComponentsFor( this.locationId, ); for (const config of customComponents) { const componentRef = this.viewContainerRef.createComponent(config.component, { injector: Injector.create({ parent: this.injector, providers: config.providers ?? [], }), }); componentRef.instance.entity$ = this.entity$; componentRef.instance.detailForm = this.detailForm; this.componentRefs.push(componentRef); } } ngOnDestroy() { for (const ref of this.componentRefs) { ref.destroy(); } } }
import { Component, Input, OnInit } from '@angular/core'; import { UntypedFormGroup } from '@angular/forms'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { InputComponentConfig } from '../../../common/component-registry-types'; import { CustomFieldConfig, CustomFieldsFragment, LanguageCode } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; import { CustomFieldComponentService, CustomFieldEntityName, } from '../../../providers/custom-field-component/custom-field-component.service'; /** * This component renders the appropriate type of form input control based * on the "type" property of the provided CustomFieldConfig. */ @Component({ selector: 'vdr-custom-field-control', templateUrl: './custom-field-control.component.html', styleUrls: ['./custom-field-control.component.scss'], }) export class CustomFieldControlComponent implements OnInit { @Input() entityName: CustomFieldEntityName; @Input('customFieldsFormGroup') formGroup: UntypedFormGroup; @Input() customField: CustomFieldsFragment; @Input() compact = false; @Input() showLabel = true; @Input() readonly = false; hasCustomControl = false; uiLanguage$: Observable<LanguageCode>; constructor( private dataService: DataService, private customFieldComponentService: CustomFieldComponentService, ) {} ngOnInit() { this.uiLanguage$ = this.dataService.client .uiState() .stream$.pipe(map(({ uiState }) => uiState.language)); } getFieldDefinition(): CustomFieldConfig & { ui?: InputComponentConfig } { const config: CustomFieldsFragment & { ui?: InputComponentConfig } = { ...this.customField, }; const id = this.customFieldComponentService.customFieldComponentExists( this.entityName, this.customField.name, ); if (id) { config.ui = { component: id }; } switch (config.__typename) { case 'IntCustomFieldConfig': return { ...config, min: config.intMin, max: config.intMax, step: config.intStep, }; case 'FloatCustomFieldConfig': return { ...config, min: config.floatMin, max: config.floatMax, step: config.floatStep, }; case 'DateTimeCustomFieldConfig': return { ...config, min: config.datetimeMin, max: config.datetimeMax, step: config.datetimeStep, }; default: return { ...config, }; } } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { CustomerFragment } from '../../../common/generated-types'; @Component({ selector: 'vdr-customer-label', templateUrl: './customer-label.component.html', styleUrls: ['./customer-label.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerLabelComponent { @Input() customer: CustomerFragment; }
import { Component, ContentChild, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { LocalizedString } from '../../../common/generated-types'; import { DataTableSort } from '../../../providers/data-table/data-table-sort'; @Component({ selector: 'vdr-dt2-column', template: ``, exportAs: 'row', }) export class DataTable2ColumnComponent<T> implements OnInit { @Input() id: string; /** * When set to true, this column will expand to use available width */ @Input() expand = false; @Input() heading: string; @Input() align: 'left' | 'right' | 'center' = 'left'; @Input() sort?: DataTableSort<any>; @Input() optional = true; @Input() hiddenByDefault = false; @Input() orderable = true; #visible = true; #onColumnChangeFns: Array<() => void> = []; get visible() { return this.#visible; } @ContentChild(TemplateRef, { static: false }) template: TemplateRef<any>; ngOnInit() { this.#visible = this.hiddenByDefault ? false : true; } setVisibility(isVisible: boolean) { this.#visible = isVisible; this.#onColumnChangeFns.forEach(fn => fn()); } resetVisibility() { this.setVisibility(!this.hiddenByDefault); } onColumnChange(callback: () => void) { this.#onColumnChangeFns.push(callback); } }
import { Injectable, Provider, Type } from '@angular/core'; import { PageLocationId } from '../../../common/component-registry-types'; export type DataTableLocationId = | { [location in PageLocationId]: location extends `${string}-list` ? location : never; }[PageLocationId] | 'collection-contents' | 'edit-options-list' | 'manage-product-variant-list' | 'customer-order-list' | 'product-detail-variants-list' | string; export type DataTableColumnId = | 'id' | 'created-at' | 'updated-at' | 'name' | 'code' | 'description' | 'slug' | 'enabled' | 'sku' | 'price' | 'price-with-tax' | 'status' | 'state' | 'image' | 'quantity' | 'total' | 'stock-on-hand' | string; /** * @description * Components which are to be used to render custom cells in a data table should implement this interface. * * The `rowItem` property is the data object for the row, e.g. the `Product` object if used * in the `product-list` table. * * @docsCategory custom-table-components */ export interface CustomColumnComponent { rowItem: any; } /** * @description * Configures a {@link CustomDetailComponent} to be placed in the given location. * * @docsCategory custom-table-components */ export interface DataTableComponentConfig { /** * @description * The location in the UI where the custom component should be placed. */ tableId: DataTableLocationId; /** * @description * The column in the table where the custom component should be placed. */ columnId: DataTableColumnId; /** * @description * The component to render in the table cell. This component should implement the * {@link CustomColumnComponent} interface. */ component: Type<CustomColumnComponent>; providers?: Provider[]; } type CompoundId = `${DataTableLocationId}.${DataTableColumnId}`; @Injectable({ providedIn: 'root', }) export class DataTableCustomComponentService { private configMap = new Map<CompoundId, DataTableComponentConfig>(); registerCustomComponent(config: DataTableComponentConfig) { const id = this.compoundId(config.tableId, config.columnId); this.configMap.set(id, config); } getCustomComponentsFor( tableId: DataTableLocationId, columnId: DataTableColumnId, ): DataTableComponentConfig | undefined { return this.configMap.get(this.compoundId(tableId, columnId)); } private compoundId(tableId: DataTableLocationId, columnId: DataTableColumnId): CompoundId { return `${tableId}.${columnId}`; } }
import { Component, ContentChild, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { CustomFieldConfig, LanguageCode } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; import { DataTableSortCollection } from '../../../providers/data-table/data-table-sort-collection'; import { CustomFieldLabelPipe } from '../../pipes/custom-field-label.pipe'; import { DataTable2ColumnComponent } from './data-table-column.component'; const labelPipe = new CustomFieldLabelPipe(); @Component({ selector: 'vdr-dt2-custom-field-column', templateUrl: './data-table-custom-field-column.component.html', styleUrls: ['./data-table-custom-field-column.component.scss'], exportAs: 'row', }) export class DataTableCustomFieldColumnComponent<T> extends DataTable2ColumnComponent<T> implements OnInit { @Input() customField: CustomFieldConfig; @Input() sorts?: DataTableSortCollection<any, any[]>; @ViewChild(TemplateRef, { static: false }) template: TemplateRef<any>; protected uiLanguage$: Observable<LanguageCode>; constructor(protected dataService: DataService) { super(); this.uiLanguage$ = this.dataService.client .uiState() .stream$.pipe(map(({ uiState }) => uiState.language)); } ngOnInit() { this.uiLanguage$.subscribe(uiLanguage => { this.heading = Array.isArray(this.customField.label) && this.customField.label.length > 0 ? this.customField.label.find(l => l.languageCode === uiLanguage)?.value ?? this.customField.name : this.customField.name; }); this.hiddenByDefault = true; this.sort = this.sorts?.get(this.customField.name); this.id = this.customField.name; this.heading = labelPipe.transform(this.customField, null); super.ngOnInit(); } }
import { Component, ContentChild, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'vdr-dt2-search', templateUrl: `./data-table-search.component.html`, styleUrls: ['./data-table-search.component.scss'], }) export class DataTable2SearchComponent { @Input() searchTermControl: FormControl<string>; @Input() searchTermPlaceholder: string | undefined; @ViewChild(TemplateRef, { static: true }) template: TemplateRef<any>; }
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, EventEmitter, inject, Injector, Input, OnChanges, OnDestroy, Output, QueryList, SimpleChanges, TemplateRef, } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { PaginationService } from 'ngx-pagination'; import { Observable, Subject } from 'rxjs'; import { distinctUntilChanged, map, takeUntil } from 'rxjs/operators'; import { LanguageCode } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; import { DataTableFilterCollection } from '../../../providers/data-table/data-table-filter-collection'; import { DataTableConfig, LocalStorageService } from '../../../providers/local-storage/local-storage.service'; import { BulkActionMenuComponent } from '../bulk-action-menu/bulk-action-menu.component'; import { FilterPresetService } from '../data-table-filter-presets/filter-preset.service'; import { DataTable2ColumnComponent } from './data-table-column.component'; import { DataTableComponentConfig, DataTableCustomComponentService, DataTableLocationId, } from './data-table-custom-component.service'; import { DataTableCustomFieldColumnComponent } from './data-table-custom-field-column.component'; import { DataTable2SearchComponent } from './data-table-search.component'; /** * @description * A table for displaying PaginatedList results. It is designed to be used inside components which * extend the {@link BaseListComponent} or {@link TypedBaseListComponent} class. * * @example * ```html * <vdr-data-table-2 * id="product-review-list" * [items]="items$ | async" * [itemsPerPage]="itemsPerPage$ | async" * [totalItems]="totalItems$ | async" * [currentPage]="currentPage$ | async" * [filters]="filters" * (pageChange)="setPageNumber($event)" * (itemsPerPageChange)="setItemsPerPage($event)" * > * <vdr-bulk-action-menu * locationId="product-review-list" * [hostComponent]="this" * [selectionManager]="selectionManager" * /> * <vdr-dt2-search * [searchTermControl]="searchTermControl" * searchTermPlaceholder="Filter by title" * /> * <vdr-dt2-column [heading]="'common.id' | translate" [hiddenByDefault]="true"> * <ng-template let-review="item"> * {{ review.id }} * </ng-template> * </vdr-dt2-column> * <vdr-dt2-column * [heading]="'common.created-at' | translate" * [hiddenByDefault]="true" * [sort]="sorts.get('createdAt')" * > * <ng-template let-review="item"> * {{ review.createdAt | localeDate : 'short' }} * </ng-template> * </vdr-dt2-column> * <vdr-dt2-column * [heading]="'common.updated-at' | translate" * [hiddenByDefault]="true" * [sort]="sorts.get('updatedAt')" * > * <ng-template let-review="item"> * {{ review.updatedAt | localeDate : 'short' }} * </ng-template> * </vdr-dt2-column> * <vdr-dt2-column [heading]="'common.name' | translate" [optional]="false" [sort]="sorts.get('name')"> * <ng-template let-review="item"> * <a class="button-ghost" [routerLink]="['./', review.id]" * ><span>{{ review.name }}</span> * <clr-icon shape="arrow right"></clr-icon> * </a> * </ng-template> * </vdr-dt2-column> * </vdr-data-table-2> * ``` * * @docsCategory components */ @Component({ selector: 'vdr-data-table-2', templateUrl: 'data-table2.component.html', styleUrls: ['data-table2.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [PaginationService, FilterPresetService], }) export class DataTable2Component<T> implements AfterContentInit, OnChanges, OnDestroy { @Input() id: DataTableLocationId; @Input() items: T[]; @Input() itemsPerPage: number; @Input() currentPage: number; @Input() totalItems: number; @Input() emptyStateLabel: string; @Input() filters: DataTableFilterCollection; @Input() activeIndex = -1; @Output() pageChange = new EventEmitter<number>(); @Output() itemsPerPageChange = new EventEmitter<number>(); @ContentChildren(DataTable2ColumnComponent) columns: QueryList<DataTable2ColumnComponent<T>>; @ContentChildren(DataTableCustomFieldColumnComponent) customFieldColumns: QueryList<DataTableCustomFieldColumnComponent<T>>; @ContentChild(DataTable2SearchComponent) searchComponent: DataTable2SearchComponent; @ContentChild(BulkActionMenuComponent) bulkActionMenuComponent: BulkActionMenuComponent; @ContentChild('vdrDt2CustomSearch') customSearchTemplate: TemplateRef<any>; @ContentChildren(TemplateRef) templateRefs: QueryList<TemplateRef<any>>; injector = inject(Injector); route = inject(ActivatedRoute); filterPresetService = inject(FilterPresetService); dataTableCustomComponentService = inject(DataTableCustomComponentService); protected customComponents = new Map<string, { config: DataTableComponentConfig; injector: Injector }>(); rowTemplate: TemplateRef<any>; currentStart: number; currentEnd: number; // This is used to apply a `user-select: none` CSS rule to the table, // which allows shift-click multi-row selection disableSelect = false; showSearchFilterRow = false; protected uiLanguage$: Observable<LanguageCode>; protected destroy$ = new Subject<void>(); constructor( protected changeDetectorRef: ChangeDetectorRef, protected localStorageService: LocalStorageService, protected dataService: DataService, ) { this.uiLanguage$ = this.dataService.client .uiState() .stream$.pipe(map(({ uiState }) => uiState.language)); } get selectionManager() { return this.bulkActionMenuComponent?.selectionManager; } get allColumns() { return [...(this.columns ?? []), ...(this.customFieldColumns ?? [])]; } get visibleSortedColumns() { return this.sortedColumns.filter(c => c.visible); } get sortedColumns() { const columns = this.allColumns; const dataTableConfig = this.getDataTableConfig(); for (const [id, index] of Object.entries(dataTableConfig[this.id].order)) { const column = columns.find(c => c.id === id); const currentIndex = columns.findIndex(c => c.id === id); if (currentIndex !== -1 && column) { columns.splice(currentIndex, 1); columns.splice(index, 0, column); } } return columns; } private shiftDownHandler = (event: KeyboardEvent) => { if (event.shiftKey && !this.disableSelect) { this.disableSelect = true; this.changeDetectorRef.markForCheck(); } }; private shiftUpHandler = (event: KeyboardEvent) => { if (this.disableSelect) { this.disableSelect = false; this.changeDetectorRef.markForCheck(); } }; ngOnChanges(changes: SimpleChanges) { if (changes.items) { this.currentStart = this.itemsPerPage * (this.currentPage - 1); this.currentEnd = this.currentStart + changes.items.currentValue?.length; this.selectionManager?.setCurrentItems(this.items); } } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); if (this.selectionManager) { document.removeEventListener('keydown', this.shiftDownHandler); document.removeEventListener('keyup', this.shiftUpHandler); } } ngAfterContentInit(): void { this.rowTemplate = this.templateRefs.last; const dataTableConfig = this.getDataTableConfig(); if (!this.id) { console.warn(`No id was assigned to the data table component`); } const updateColumnVisibility = () => { dataTableConfig[this.id].visibility = this.allColumns .filter(c => (c.visible && c.hiddenByDefault) || (!c.visible && !c.hiddenByDefault)) .map(c => c.id); this.localStorageService.set('dataTableConfig', dataTableConfig); }; this.allColumns.forEach(column => { if (dataTableConfig?.[this.id]?.visibility.includes(column.id)) { column.setVisibility(column.hiddenByDefault); } column.onColumnChange(updateColumnVisibility); const config = this.dataTableCustomComponentService.getCustomComponentsFor(this.id, column.id); if (config) { const injector = Injector.create({ parent: this.injector, providers: config.providers ?? [], }); this.customComponents.set(column.id, { config, injector }); } }); if (this.selectionManager) { document.addEventListener('keydown', this.shiftDownHandler, { passive: true }); document.addEventListener('keyup', this.shiftUpHandler, { passive: true }); this.bulkActionMenuComponent.onClearSelection(() => { this.changeDetectorRef.markForCheck(); }); this.selectionManager.setCurrentItems(this.items); } this.showSearchFilterRow = !!this.filters?.activeFilters.length || (dataTableConfig?.[this.id]?.showSearchFilterRow ?? false); this.columns.changes.subscribe(() => { this.changeDetectorRef.markForCheck(); }); this.selectionManager?.selectionChanges$ .pipe(takeUntil(this.destroy$)) .subscribe(() => this.changeDetectorRef.markForCheck()); if (this.selectionManager) { this.dataService.client .userStatus() .mapStream(({ userStatus }) => userStatus.activeChannelId) .pipe(distinctUntilChanged(), takeUntil(this.destroy$)) .subscribe(() => { this.selectionManager?.clearSelection(); }); } } onColumnReorder(event: { column: DataTable2ColumnComponent<any>; newIndex: number }) { const naturalIndex = this.allColumns.findIndex(c => c.id === event.column.id); const dataTableConfig = this.getDataTableConfig(); if (naturalIndex === event.newIndex) { delete dataTableConfig[this.id].order[event.column.id]; } else { dataTableConfig[this.id].order[event.column.id] = event.newIndex; } this.localStorageService.set('dataTableConfig', dataTableConfig); } onColumnsReset() { const dataTableConfig = this.getDataTableConfig(); dataTableConfig[this.id].order = {}; dataTableConfig[this.id].visibility = []; this.localStorageService.set('dataTableConfig', dataTableConfig); } toggleSearchFilterRow() { this.showSearchFilterRow = !this.showSearchFilterRow; const dataTableConfig = this.getDataTableConfig(); dataTableConfig[this.id].showSearchFilterRow = this.showSearchFilterRow; this.localStorageService.set('dataTableConfig', dataTableConfig); } trackByFn(index: number, item: any) { if ((item as any).id != null) { return (item as any).id; } else { return index; } } onToggleAllClick() { this.selectionManager?.toggleSelectAll(); } onRowClick(item: T, event: MouseEvent) { this.selectionManager?.toggleSelection(item, event); } protected getDataTableConfig(): DataTableConfig { const dataTableConfig = this.localStorageService.get('dataTableConfig') ?? {}; if (!dataTableConfig[this.id]) { dataTableConfig[this.id] = { visibility: [], order: {}, showSearchFilterRow: false, filterPresets: [], }; } return dataTableConfig; } }
import { CdkDragDrop } from '@angular/cdk/drag-drop'; import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { LanguageCode } from '../../../common/generated-types'; import { DataTable2ColumnComponent } from '../data-table-2/data-table-column.component'; @Component({ selector: 'vdr-data-table-colum-picker', templateUrl: './data-table-column-picker.component.html', styleUrls: ['./data-table-column-picker.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DataTableColumnPickerComponent { @Input() columns: Array<DataTable2ColumnComponent<any>>; @Input() uiLanguage: LanguageCode; @Output() reorder = new EventEmitter<{ column: DataTable2ColumnComponent<any>; newIndex: number }>(); @Output() resetColumns = new EventEmitter<void>(); toggleColumn(column: DataTable2ColumnComponent<any>) { column.setVisibility(!column.visible); } drop(event: CdkDragDrop<Array<DataTable2ColumnComponent<any>>>) { this.reorder.emit({ column: event.item.data, newIndex: event.currentIndex, }); } reset() { this.columns.forEach(c => c.resetVisibility()); this.resetColumns.emit(); } }
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { from, merge, Observable, of, Subject, switchMap } from 'rxjs'; import { LanguageCode, LocalizedString } from '../../../common/generated-types'; import { DataTableFilter } from '../../../providers/data-table/data-table-filter'; import { FilterWithValue } from '../../../providers/data-table/data-table-filter-collection'; @Component({ selector: 'vdr-data-table-filter-label', templateUrl: './data-table-filter-label.component.html', styleUrls: ['./data-table-filter-label.component.scss'], changeDetection: ChangeDetectionStrategy.Default, }) export class DataTableFilterLabelComponent implements OnInit { @Input() filterWithValue: FilterWithValue; protected customFilterLabel$?: Observable<string>; ngOnInit() { const filterValueUpdate$ = new Subject<void>(); this.filterWithValue.onUpdate(() => filterValueUpdate$.next()); this.customFilterLabel$ = merge(of(this.filterWithValue), filterValueUpdate$).pipe( switchMap(() => { if (this.filterWithValue?.filter.type.kind === 'custom') { const labelResult = this.filterWithValue.filter.type.getLabel(this.filterWithValue.value); return typeof labelResult === 'string' ? of(labelResult) : from(labelResult); } else { return of(''); } }), ); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnDestroy, OnInit, ViewChild, } from '@angular/core'; import { FormControl } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { merge, Subject } from 'rxjs'; import { distinctUntilChanged, map, takeUntil } from 'rxjs/operators'; import { DataTableFilterCollection } from '../../../providers/data-table/data-table-filter-collection'; import { DropdownComponent } from '../dropdown/dropdown.component'; import { FilterPresetService } from './filter-preset.service'; @Component({ selector: 'vdr-add-filter-preset-button', templateUrl: './add-filter-preset-button.component.html', styleUrls: ['./add-filter-preset-button.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AddFilterPresetButtonComponent implements OnInit, OnDestroy { @Input({ required: true }) dataTableId: string; @Input({ required: true }) filters: DataTableFilterCollection; @ViewChild('addPresetDropdown') addPresetDropdown: DropdownComponent; selectedFilterPreset: string | undefined; filterPresetName = new FormControl(''); private destroy$ = new Subject<void>(); constructor( private filterPresetService: FilterPresetService, private changeDetector: ChangeDetectorRef, private route: ActivatedRoute, ) {} ngOnInit() { merge( this.route.queryParamMap.pipe( map(qpm => qpm.get('filters')), distinctUntilChanged(), takeUntil(this.destroy$), ), this.filterPresetService.presetChanges$, this.filters.valueChanges, ).subscribe(() => { this.changeDetector.markForCheck(); this.updateSelectedFilterPreset(); }); } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } saveFilterPreset() { const name = this.filterPresetName.value; if (this.filters && name) { const value = this.filters.serialize(); this.filterPresetService.saveFilterPreset({ dataTableId: this.dataTableId, name, value, }); this.filterPresetName.setValue(''); this.addPresetDropdown.toggleOpen(); } this.updateSelectedFilterPreset(); } private updateSelectedFilterPreset() { this.selectedFilterPreset = this.filterPresetService .getFilterPresets(this.dataTableId) .find(p => p.value === this.filters.serialize())?.name; } }
import { CdkDragDrop } from '@angular/cdk/drag-drop'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnDestroy, OnInit, } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Observable, Subject } from 'rxjs'; import { distinctUntilChanged, map, startWith, takeUntil } from 'rxjs/operators'; import { DataTableFilterCollection } from '../../../providers/data-table/data-table-filter-collection'; import { ModalService } from '../../../providers/modal/modal.service'; import { FilterPresetService } from './filter-preset.service'; import { RenameFilterPresetDialogComponent } from './rename-filter-preset-dialog.component'; @Component({ selector: 'vdr-data-table-filter-presets', templateUrl: './data-table-filter-presets.component.html', styleUrls: ['./data-table-filter-presets.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DataTableFilterPresetsComponent implements OnInit, OnDestroy { @Input({ required: true }) dataTableId: string; @Input({ required: true }) filters: DataTableFilterCollection; serializedActiveFilters: string; filterPresets$: Observable<Array<{ name: string; value: string }>>; private destroy$ = new Subject<void>(); constructor( private route: ActivatedRoute, private filterPresetService: FilterPresetService, private modalService: ModalService, private changeDetectorRef: ChangeDetectorRef, ) {} ngOnInit() { this.route.queryParamMap .pipe( map(qpm => qpm.get('filters')), distinctUntilChanged(), takeUntil(this.destroy$), ) .subscribe(() => { this.serializedActiveFilters = this.filters.serialize(); this.changeDetectorRef.markForCheck(); }); this.serializedActiveFilters = this.filters.serialize(); this.filterPresets$ = this.filterPresetService.presetChanges$.pipe( startWith(this.filterPresetService.getFilterPresets(this.dataTableId)), ); } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } deleteFilterPreset(name: string) { this.filterPresetService.deleteFilterPreset({ dataTableId: this.dataTableId, name, }); this.serializedActiveFilters = this.filters.serialize(); } renameFilterPreset(name: string) { this.modalService .fromComponent(RenameFilterPresetDialogComponent, { closable: true, locals: { name, }, }) .subscribe(result => { if (result) { this.filterPresetService.renameFilterPreset({ dataTableId: this.dataTableId, oldName: name, newName: result, }); } }); } drop(event: CdkDragDrop<any>) { this.filterPresetService.reorderPresets(this.dataTableId, event.previousIndex, event.currentIndex); } }
import { moveItemInArray } from '@angular/cdk/drag-drop'; import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; import { DataTableConfig, LocalStorageService } from '../../../providers/local-storage/local-storage.service'; @Injectable({ providedIn: 'root', }) export class FilterPresetService { presetChanges$: Observable<Array<{ name: string; value: string }>>; private _presetChanges = new Subject<Array<{ name: string; value: string }>>(); constructor(private localStorageService: LocalStorageService) { this.presetChanges$ = this._presetChanges.asObservable(); } protected getDataTableConfig(dataTableId: string): DataTableConfig { const dataTableConfig = this.localStorageService.get('dataTableConfig') ?? {}; if (!dataTableConfig[dataTableId]) { dataTableConfig[dataTableId] = { visibility: [], order: {}, showSearchFilterRow: false, filterPresets: [], }; } return dataTableConfig; } getFilterPresets(dataTableId: string): Array<{ name: string; value: string }> { const dataTableConfig = this.getDataTableConfig(dataTableId); return dataTableConfig[dataTableId].filterPresets ?? []; } saveFilterPreset(config: { dataTableId: string; name: string; value: string }) { const dataTableConfig = this.getDataTableConfig(config.dataTableId); const filterPresets = dataTableConfig[config.dataTableId].filterPresets ?? []; const existingName = filterPresets.find(p => p.name === config.name); if (existingName) { existingName.value = config.value; } else { filterPresets.push({ name: config.name, value: config.value, }); } dataTableConfig[config.dataTableId].filterPresets = filterPresets; this.localStorageService.set('dataTableConfig', dataTableConfig); this._presetChanges.next(filterPresets); } deleteFilterPreset(config: { dataTableId: string; name: string }) { const dataTableConfig = this.getDataTableConfig(config.dataTableId); dataTableConfig[config.dataTableId].filterPresets = dataTableConfig[ config.dataTableId ].filterPresets.filter(p => p.name !== config.name); this.localStorageService.set('dataTableConfig', dataTableConfig); this._presetChanges.next(dataTableConfig[config.dataTableId].filterPresets); } reorderPresets(dataTableId: string, fromIndex: number, toIndex: number) { const presets = this.getFilterPresets(dataTableId); moveItemInArray(presets, fromIndex, toIndex); const dataTableConfig = this.getDataTableConfig(dataTableId); dataTableConfig[dataTableId].filterPresets = presets; this.localStorageService.set('dataTableConfig', dataTableConfig); this._presetChanges.next(presets); } renameFilterPreset(config: { dataTableId: string; oldName: string; newName: string }) { const dataTableConfig = this.getDataTableConfig(config.dataTableId); const filterPresets = dataTableConfig[config.dataTableId].filterPresets ?? []; const existingName = filterPresets.find(p => p.name === config.oldName); if (existingName) { existingName.name = config.newName; dataTableConfig[config.dataTableId].filterPresets = filterPresets; this.localStorageService.set('dataTableConfig', dataTableConfig); this._presetChanges.next(filterPresets); } } }
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { Dialog } from '../../../providers/modal/modal.types'; @Component({ selector: 'vdr-rename-filter-preset-dialog', templateUrl: './rename-filter-preset-dialog.component.html', styleUrls: ['./rename-filter-preset-dialog.component.css'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RenameFilterPresetDialogComponent implements Dialog<string> { name: string; resolveWith: (result?: string) => void; rename() { this.resolveWith(this.name); } }
import { Directive, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[vdrCustomFilterComponentHost]', }) export class CustomFilterComponentDirective { constructor(public viewContainerRef: ViewContainerRef) {} }
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentRef, HostListener, Input, ViewChild, } from '@angular/core'; import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { FormInputComponent } from '../../../common/component-registry-types'; import { DateOperators } from '../../../common/generated-types'; import { DataTableFilter, KindValueMap } from '../../../providers/data-table/data-table-filter'; import { DataTableFilterCollection, FilterWithValue, } from '../../../providers/data-table/data-table-filter-collection'; import { I18nService } from '../../../providers/i18n/i18n.service'; import { DropdownComponent } from '../dropdown/dropdown.component'; import { CustomFilterComponentDirective } from './custom-filter-component.directive'; @Component({ selector: 'vdr-data-table-filters', templateUrl: './data-table-filters.component.html', styleUrls: ['./data-table-filters.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DataTableFiltersComponent implements AfterViewInit { @Input() filters: DataTableFilterCollection; @Input() filterWithValue?: FilterWithValue; @ViewChild('dropdown', { static: true }) dropdown: DropdownComponent; @ViewChild('customComponentHost', { static: false, read: CustomFilterComponentDirective }) set customComponentHost(content: CustomFilterComponentDirective) { this._customComponentHost = content; } _customComponentHost: CustomFilterComponentDirective; protected state: 'new' | 'active' = 'new'; protected formControl: AbstractControl; protected selectedFilter: DataTableFilter | undefined; protected customComponent?: ComponentRef<FormInputComponent>; @HostListener('window:keydown.f', ['$event']) onFKeyPress(event: KeyboardEvent) { if (event.target instanceof HTMLElement) { if ( event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA' || event.target.classList.contains('vdr-prosemirror') || event.target.classList.contains('code-editor') ) { return; } } if (!this.dropdown.isOpen && this.state === 'new') { this.dropdown.toggleOpen(); } } constructor( private i18nService: I18nService, private changeDetectorRef: ChangeDetectorRef, ) {} ngAfterViewInit() { this.dropdown.onOpenChange(isOpen => { if (!isOpen && this.state === 'new') { this.selectedFilter = undefined; } }); if (this.filterWithValue) { const { filter, value } = this.filterWithValue; this.selectFilter(filter, value); this.state = 'active'; } setTimeout(() => this.changeDetectorRef.markForCheck()); } selectFilter(filter: DataTableFilter, value?: any) { this.selectedFilter = filter; if (filter.isId()) { this.formControl = new FormGroup( { operator: new FormControl(value?.operator ?? 'eq'), term: new FormControl(value?.term ?? ''), }, control => { if (!control.value.term) { return { noSelection: true }; } return null; }, ); } if (filter.isText()) { this.formControl = new FormGroup( { operator: new FormControl(value?.operator ?? 'contains'), term: new FormControl(value?.term ?? ''), }, control => { if (!control.value.term) { return { noSelection: true }; } return null; }, ); } if (filter.isNumber()) { this.formControl = new FormGroup( { operator: new FormControl(value?.operator ?? 'gt'), amount: new FormControl(value?.amount ?? ''), }, control => { if (control.value.amount == null) { return { noSelection: true }; } return null; }, ); } else if (filter.isSelect()) { this.formControl = new FormArray( filter.type.options.map(o => new FormControl(value?.includes(o.value) ?? false)), control => (control.value.some(Boolean) ? null : { noSelection: true }), ); } else if (filter.isBoolean()) { this.formControl = new FormControl(value ?? false); } else if (filter.isDateRange()) { this.formControl = new FormGroup( { mode: new FormControl('relative'), relativeValue: new FormControl(value?.relativeValue ?? 30), relativeUnit: new FormControl(value?.relativeUnit ?? 'day'), start: new FormControl(value?.start ?? null), end: new FormControl(value?.end ?? null), }, control => { const val = control.value; const mode = val.mode; if (mode === 'range' && val.start && val.end && val.start > val.end) { return { invalidRange: true }; } if (mode === 'range' && !val.start && !val.end) { return { noSelection: true }; } return null; }, ); } else if (filter.isCustom() && this._customComponentHost) { // this.#customComponentHost.viewContainerRef.clear(); this.customComponent = this._customComponentHost.viewContainerRef.createComponent( filter.type.component, ); this.formControl = new FormControl<any>(value ?? []); this.customComponent.instance.config = {}; this.customComponent.instance.formControl = new FormControl<any>(value ?? []); } } activate(event: Event) { event.preventDefault(); if (!this.selectedFilter) { return; } let value: any; const type = this.selectedFilter?.type; switch (type.kind) { case 'boolean': value = !!this.formControl.value as KindValueMap[typeof type.kind]['raw']; break; case 'dateRange': { const mode = this.formControl.value.mode ?? 'relative'; const relativeValue = this.formControl.value.relativeValue ?? 30; const relativeUnit = this.formControl.value.relativeUnit ?? 'day'; const start = this.formControl.value.start ?? undefined; const end = this.formControl.value.end ?? undefined; value = { mode, relativeValue, relativeUnit, start, end, } as KindValueMap[typeof type.kind]['raw']; break; } case 'number': value = { amount: Number(this.formControl.value.amount), operator: this.formControl.value.operator, } as KindValueMap[typeof type.kind]['raw']; break; case 'select': const options = this.formControl.value .map((v, i) => (v ? type.options[i].value : undefined)) .filter(v => !!v); value = options as KindValueMap[typeof type.kind]['raw']; break; case 'text': value = { operator: this.formControl.value.operator, term: this.formControl.value.term, } as KindValueMap[typeof type.kind]['raw']; break; case 'id': value = { operator: this.formControl.value.operator, term: this.formControl.value.term, } as KindValueMap[typeof type.kind]['raw']; break; case 'custom': value = this.customComponent?.instance.formControl.value; this.formControl.setValue(value); if (this.state === 'new') { this._customComponentHost.viewContainerRef.clear(); } break; default: assertNever(type); } if (this.state === 'new') { this.selectedFilter.activate(value); } else { this.filterWithValue?.updateValue(value); } this.dropdown.toggleOpen(); } deactivate() { if (this.filterWithValue) { const index = this.filters.activeFilters.indexOf(this.filterWithValue); this.filters.removeActiveFilterAtIndex(index); } } }
import { Component, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'; @Component({ selector: 'vdr-dt-column', template: ` <ng-template><ng-content></ng-content></ng-template> `, }) export class DataTableColumnComponent { /** * When set to true, this column will expand to use avaiable width */ @Input() expand = false; @ViewChild(TemplateRef, { static: true }) template: TemplateRef<any>; }
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { NgxPaginationModule } from 'ngx-pagination'; import { TestingCommonModule } from '../../../../../../testing/testing-common.module'; import { ItemsPerPageControlsComponent } from '../items-per-page-controls/items-per-page-controls.component'; import { PaginationControlsComponent } from '../pagination-controls/pagination-controls.component'; import { SelectToggleComponent } from '../select-toggle/select-toggle.component'; import { DataTableColumnComponent } from './data-table-column.component'; import { DataTableComponent } from './data-table.component'; describe('DataTableComponent', () => { let component: DataTableComponent<any>; let fixture: ComponentFixture<DataTableComponent<any>>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [NgxPaginationModule, TestingCommonModule], declarations: [ DataTableComponent, DataTableColumnComponent, PaginationControlsComponent, ItemsPerPageControlsComponent, SelectToggleComponent, ], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(DataTableComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, QueryList, SimpleChanges, TemplateRef, } from '@angular/core'; import { PaginationService } from 'ngx-pagination'; import { Subscription } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { SelectionManager } from '../../../common/utilities/selection-manager'; import { DataTableColumnComponent } from './data-table-column.component'; /** * @description * A table for displaying PaginatedList results. It is designed to be used inside components which * extend the {@link BaseListComponent} class. * * **Deprecated** This component is deprecated. Use the {@link DataTable2Component} instead. * * @example * ```HTML * <vdr-data-table * [items]="items$ | async" * [itemsPerPage]="itemsPerPage$ | async" * [totalItems]="totalItems$ | async" * [currentPage]="currentPage$ | async" * (pageChange)="setPageNumber($event)" * (itemsPerPageChange)="setItemsPerPage($event)" * > * <!-- The header columns are defined first --> * <vdr-dt-column>{{ 'common.name' | translate }}</vdr-dt-column> * <vdr-dt-column></vdr-dt-column> * <vdr-dt-column></vdr-dt-column> * * <!-- Then we define how a row is rendered --> * <ng-template let-taxRate="item"> * <td class="left align-middle">{{ taxRate.name }}</td> * <td class="left align-middle">{{ taxRate.category.name }}</td> * <td class="left align-middle">{{ taxRate.zone.name }}</td> * <td class="left align-middle">{{ taxRate.value }}%</td> * <td class="right align-middle"> * <vdr-table-row-action * iconShape="edit" * [label]="'common.edit' | translate" * [linkTo]="['./', taxRate.id]" * ></vdr-table-row-action> * </td> * <td class="right align-middle"> * <vdr-dropdown> * <button type="button" class="btn btn-link btn-sm" vdrDropdownTrigger> * {{ 'common.actions' | translate }} * <clr-icon shape="caret down"></clr-icon> * </button> * <vdr-dropdown-menu vdrPosition="bottom-right"> * <button * type="button" * class="delete-button" * (click)="deleteTaxRate(taxRate)" * [disabled]="!(['DeleteSettings', 'DeleteTaxRate'] | hasPermission)" * vdrDropdownItem * > * <clr-icon shape="trash" class="is-danger"></clr-icon> * {{ 'common.delete' | translate }} * </button> * </vdr-dropdown-menu> * </vdr-dropdown> * </td> * </ng-template> * </vdr-data-table> * ``` * * @docsCategory components * @deprecated Use the DataTable2 component instead. */ @Component({ selector: 'vdr-data-table', templateUrl: 'data-table.component.html', styleUrls: ['data-table.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [PaginationService], }) export class DataTableComponent<T> implements AfterContentInit, OnChanges, OnInit, OnDestroy { @Input() items: T[]; @Input() itemsPerPage: number; @Input() currentPage: number; @Input() totalItems: number; @Input() emptyStateLabel: string; @Input() selectionManager?: SelectionManager<T>; @Output() pageChange = new EventEmitter<number>(); @Output() itemsPerPageChange = new EventEmitter<number>(); /** @deprecated pass a SelectionManager instance instead */ @Input() allSelected: boolean; /** @deprecated pass a SelectionManager instance instead */ @Input() isRowSelectedFn: ((item: T) => boolean) | undefined; /** @deprecated pass a SelectionManager instance instead */ @Output() allSelectChange = new EventEmitter<void>(); /** @deprecated pass a SelectionManager instance instead */ @Output() rowSelectChange = new EventEmitter<{ event: MouseEvent; item: T }>(); @ContentChildren(DataTableColumnComponent) columns: QueryList<DataTableColumnComponent>; @ContentChildren(TemplateRef) templateRefs: QueryList<TemplateRef<any>>; rowTemplate: TemplateRef<any>; currentStart: number; currentEnd: number; // This is used to apply a `user-select: none` CSS rule to the table, // which allows shift-click multi-row selection disableSelect = false; private subscription: Subscription | undefined; constructor(private changeDetectorRef: ChangeDetectorRef) {} private shiftDownHandler = (event: KeyboardEvent) => { if (event.shiftKey && !this.disableSelect) { this.disableSelect = true; this.changeDetectorRef.markForCheck(); } }; private shiftUpHandler = (event: KeyboardEvent) => { if (this.disableSelect) { this.disableSelect = false; this.changeDetectorRef.markForCheck(); } }; ngOnInit() { if (typeof this.isRowSelectedFn === 'function' || this.selectionManager) { document.addEventListener('keydown', this.shiftDownHandler, { passive: true }); document.addEventListener('keyup', this.shiftUpHandler, { passive: true }); } this.subscription = this.selectionManager?.selectionChanges$.subscribe(() => this.changeDetectorRef.markForCheck(), ); } ngOnChanges(changes: SimpleChanges) { if (changes.items) { this.currentStart = this.itemsPerPage * (this.currentPage - 1); this.currentEnd = this.currentStart + changes.items.currentValue?.length; this.selectionManager?.setCurrentItems(this.items); } } ngOnDestroy() { if (typeof this.isRowSelectedFn === 'function' || this.selectionManager) { document.removeEventListener('keydown', this.shiftDownHandler); document.removeEventListener('keyup', this.shiftUpHandler); } this.subscription?.unsubscribe(); } ngAfterContentInit(): void { this.rowTemplate = this.templateRefs.last; } trackByFn(index: number, item: any) { if ((item as any).id != null) { return (item as any).id; } else { return index; } } onToggleAllClick() { this.allSelectChange.emit(); this.selectionManager?.toggleSelectAll(); } onRowClick(item: T, event: MouseEvent) { this.rowSelectChange.emit({ event, item }); this.selectionManager?.toggleSelection(item, event); } }
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DayOfWeek } from './types'; export const dayOfWeekIndex: { [day in DayOfWeek]: number } = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6, }; export const weekDayNames = [ _('datetime.weekday-su'), _('datetime.weekday-mo'), _('datetime.weekday-tu'), _('datetime.weekday-we'), _('datetime.weekday-th'), _('datetime.weekday-fr'), _('datetime.weekday-sa'), ];
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Input, OnDestroy, OnInit, ViewChild, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { Observable, Subscription } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { DropdownComponent } from '../dropdown/dropdown.component'; import { dayOfWeekIndex, weekDayNames } from './constants'; import { DatetimePickerService } from './datetime-picker.service'; import { CalendarView, DayCell, DayOfWeek } from './types'; export type CurrentView = { date: Date; month: number; year: number; }; /** * @description * A form input for selecting datetime values. * * @example * ```HTML * <vdr-datetime-picker [(ngModel)]="startDate"></vdr-datetime-picker> * ``` * * @docsCategory components */ @Component({ selector: 'vdr-datetime-picker', templateUrl: './datetime-picker.component.html', styleUrls: ['./datetime-picker.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ DatetimePickerService, { provide: NG_VALUE_ACCESSOR, useExisting: DatetimePickerComponent, multi: true, }, ], }) export class DatetimePickerComponent implements ControlValueAccessor, AfterViewInit, OnInit, OnDestroy { /** * @description * The range above and below the current year which is selectable from * the year select control. If a min or max value is set, these will * override the yearRange. */ @Input() yearRange; /** * @description * The day that the week should start with in the calendar view. */ @Input() weekStartDay: DayOfWeek = 'mon'; /** * @description * The granularity of the minutes time picker */ @Input() timeGranularityInterval = 5; /** * @description * The minimum date as an ISO string */ @Input() min: string | null = null; /** * @description * The maximum date as an ISO string */ @Input() max: string | null = null; /** * @description * Sets the readonly state */ @Input() readonly = false; @ViewChild('dropdownComponent', { static: true }) dropdownComponent: DropdownComponent; @ViewChild('datetimeInput', { static: true }) datetimeInput: ElementRef<HTMLInputElement>; @ViewChild('calendarTable') calendarTable: ElementRef<HTMLTableElement>; disabled = false; calendarView$: Observable<CalendarView>; current$: Observable<CurrentView>; selected$: Observable<Date | null>; selectedHours$: Observable<number | null>; selectedMinutes$: Observable<number | null>; years: number[]; weekdays: string[] = []; hours: number[]; minutes: number[]; private onChange: (val: any) => void; private onTouch: () => void; private subscription: Subscription; constructor( private changeDetectorRef: ChangeDetectorRef, private datetimePickerService: DatetimePickerService, ) {} ngOnInit() { this.datetimePickerService.setWeekStartingDay(this.weekStartDay); this.datetimePickerService.setMin(this.min); this.datetimePickerService.setMax(this.max); this.populateYearsSelection(); this.populateWeekdays(); this.populateHours(); this.populateMinutes(); this.calendarView$ = this.datetimePickerService.calendarView$; this.current$ = this.datetimePickerService.viewing$.pipe( map(date => ({ date, month: date.getMonth() + 1, year: date.getFullYear(), })), ); this.selected$ = this.datetimePickerService.selected$; this.selectedHours$ = this.selected$.pipe(map(date => date && date.getHours())); this.selectedMinutes$ = this.selected$.pipe(map(date => date && date.getMinutes())); this.subscription = this.datetimePickerService.selected$.subscribe(val => { if (this.onChange) { this.onChange(val == null ? val : val.toISOString()); } }); } ngAfterViewInit(): void { this.dropdownComponent.onOpenChange(isOpen => { if (isOpen) { this.calendarTable.nativeElement.focus(); } }); } ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouch = fn; } setDisabledState(isDisabled: boolean) { this.disabled = isDisabled; } writeValue(value: string | null) { this.datetimePickerService.selectDatetime(value); } prevMonth() { this.datetimePickerService.viewPrevMonth(); } nextMonth() { this.datetimePickerService.viewNextMonth(); } selectToday() { this.datetimePickerService.selectToday(); } setYear(event: Event) { const target = event.target as HTMLSelectElement; this.datetimePickerService.viewYear(parseInt(target.value, 10)); } setMonth(event: Event) { const target = event.target as HTMLSelectElement; this.datetimePickerService.viewMonth(parseInt(target.value, 10)); } selectDay(day: DayCell) { if (day.disabled) { return; } day.select(); } clearValue() { this.datetimePickerService.selectDatetime(null); } handleCalendarKeydown(event: KeyboardEvent) { switch (event.key) { case 'ArrowDown': return this.datetimePickerService.viewJumpDown(); case 'ArrowUp': return this.datetimePickerService.viewJumpUp(); case 'ArrowRight': return this.datetimePickerService.viewJumpRight(); case 'ArrowLeft': return this.datetimePickerService.viewJumpLeft(); case 'Enter': return this.datetimePickerService.selectViewed(); } } setHour(event: Event) { const target = event.target as HTMLSelectElement; this.datetimePickerService.selectHour(parseInt(target.value, 10)); } setMinute(event: Event) { const target = event.target as HTMLSelectElement; this.datetimePickerService.selectMinute(parseInt(target.value, 10)); } closeDatepicker() { this.dropdownComponent.toggleOpen(); this.datetimeInput.nativeElement.focus(); } private populateYearsSelection() { const yearRange = this.yearRange ?? 10; const currentYear = new Date().getFullYear(); const min = (this.min && new Date(this.min).getFullYear()) || currentYear - yearRange; const max = (this.max && new Date(this.max).getFullYear()) || currentYear + yearRange; const spread = max - min + 1; this.years = Array.from({ length: spread }).map((_, i) => min + i); } private populateWeekdays() { const weekStartDayIndex = dayOfWeekIndex[this.weekStartDay]; for (let i = 0; i < 7; i++) { this.weekdays.push(weekDayNames[(i + weekStartDayIndex + 0) % 7]); } } private populateHours() { this.hours = Array.from({ length: 24 }).map((_, i) => i); } private populateMinutes() { const minutes: number[] = []; for (let i = 0; i < 60; i += this.timeGranularityInterval) { minutes.push(i); } this.minutes = minutes; } }
import { Injectable } from '@angular/core'; import dayjs from 'dayjs'; import { BehaviorSubject, combineLatest, Observable } from 'rxjs'; import { distinctUntilChanged, map } from 'rxjs/operators'; import { dayOfWeekIndex } from './constants'; import { CalendarView, DayCell, DayOfWeek } from './types'; @Injectable() export class DatetimePickerService { calendarView$: Observable<CalendarView>; selected$: Observable<Date | null>; viewing$: Observable<Date>; private selectedDatetime$ = new BehaviorSubject<dayjs.Dayjs | null>(null); private viewingDatetime$ = new BehaviorSubject<dayjs.Dayjs>(dayjs()); private weekStartDayIndex: number; private min: dayjs.Dayjs | null = null; private max: dayjs.Dayjs | null = null; private jumping = false; constructor() { this.selected$ = this.selectedDatetime$.pipe( map(value => value && value.toDate()), distinctUntilChanged((a, b) => a?.getTime() === b?.getTime()), ); this.viewing$ = this.viewingDatetime$.pipe(map(value => value.toDate())); this.weekStartDayIndex = dayOfWeekIndex['mon']; this.calendarView$ = combineLatest(this.viewingDatetime$, this.selectedDatetime$).pipe( map(([viewing, selected]) => this.generateCalendarView(viewing, selected)), ); } setWeekStartingDay(weekStartDay: DayOfWeek) { this.weekStartDayIndex = dayOfWeekIndex[weekStartDay]; } setMin(min?: string | null) { if (typeof min === 'string') { this.min = dayjs(min); } } setMax(max?: string | null) { if (typeof max === 'string') { this.max = dayjs(max); } } selectDatetime(date: Date | string | dayjs.Dayjs | null) { let viewingValue: dayjs.Dayjs; let selectedValue: dayjs.Dayjs | null = null; if (date == null || date === '') { viewingValue = dayjs(); } else { viewingValue = dayjs(date); selectedValue = dayjs(date); } this.selectedDatetime$.next(selectedValue); this.viewingDatetime$.next(viewingValue); } selectHour(hourOfDay: number) { const current = this.selectedDatetime$.value || dayjs(); const next = current.hour(hourOfDay); this.selectedDatetime$.next(next); this.viewingDatetime$.next(next); } selectMinute(minutePastHour: number) { const current = this.selectedDatetime$.value || dayjs(); const next = current.minute(minutePastHour); this.selectedDatetime$.next(next); this.viewingDatetime$.next(next); } viewNextMonth() { this.jumping = false; const current = this.viewingDatetime$.value; this.viewingDatetime$.next(current.add(1, 'month')); } viewPrevMonth() { this.jumping = false; const current = this.viewingDatetime$.value; this.viewingDatetime$.next(current.subtract(1, 'month')); } viewToday() { this.jumping = false; this.viewingDatetime$.next(dayjs()); } viewJumpDown() { this.jumping = true; const current = this.viewingDatetime$.value; this.viewingDatetime$.next(current.add(1, 'week')); } viewJumpUp() { this.jumping = true; const current = this.viewingDatetime$.value; this.viewingDatetime$.next(current.subtract(1, 'week')); } viewJumpRight() { this.jumping = true; const current = this.viewingDatetime$.value; this.viewingDatetime$.next(current.add(1, 'day')); } viewJumpLeft() { this.jumping = true; const current = this.viewingDatetime$.value; this.viewingDatetime$.next(current.subtract(1, 'day')); } selectToday() { this.jumping = false; this.selectDatetime(dayjs()); } selectViewed() { this.jumping = false; this.selectDatetime(this.viewingDatetime$.value); } viewMonth(month: number) { this.jumping = false; const current = this.viewingDatetime$.value; this.viewingDatetime$.next(current.month(month - 1)); } viewYear(year: number) { this.jumping = false; const current = this.viewingDatetime$.value; this.viewingDatetime$.next(current.year(year)); } private generateCalendarView(viewing: dayjs.Dayjs, selected: dayjs.Dayjs | null): CalendarView { if (!viewing.isValid() || (selected && !selected.isValid())) { return []; } const start = viewing.startOf('month'); const end = viewing.endOf('month'); const today = dayjs(); const daysInMonth = viewing.daysInMonth(); const selectedDayOfMonth = selected && selected.get('date'); const startDayOfWeek = start.day(); const startIndex = (7 + (startDayOfWeek - this.weekStartDayIndex)) % 7; const calendarView: CalendarView = []; let week: DayCell[] = []; // Add the days at the tail of the previous month if (0 < startIndex) { const prevMonth = viewing.subtract(1, 'month'); const daysInPrevMonth = prevMonth.daysInMonth(); const prevIsCurrentMonth = prevMonth.isSame(today, 'month'); for (let i = daysInPrevMonth - startIndex + 1; i <= daysInPrevMonth; i++) { const thisDay = viewing.subtract(1, 'month').date(i); week.push({ dayOfMonth: i, selected: false, inCurrentMonth: false, isToday: prevIsCurrentMonth && today.get('date') === i, isViewing: false, disabled: !this.isInBounds(thisDay), select: () => { this.selectDatetime(thisDay); }, }); } } // Add this month's days const isCurrentMonth = viewing.isSame(today, 'month'); for (let i = 1; i <= daysInMonth; i++) { if ((i + startIndex - 1) % 7 === 0) { calendarView.push(week); week = []; } const thisDay = start.add(i - 1, 'day'); const isViewingThisMonth = !!selected && selected.isSame(viewing, 'month') && selected.isSame(viewing, 'year'); week.push({ dayOfMonth: i, selected: i === selectedDayOfMonth && isViewingThisMonth, inCurrentMonth: true, isToday: isCurrentMonth && today.get('date') === i, isViewing: this.jumping && viewing.date() === i, disabled: !this.isInBounds(thisDay), select: () => { this.selectDatetime(thisDay); }, }); } // Add the days at the start of the next month const emptyCellsEnd = 7 - ((startIndex + daysInMonth) % 7); if (emptyCellsEnd !== 7) { const nextMonth = viewing.add(1, 'month'); const nextIsCurrentMonth = nextMonth.isSame(today, 'month'); for (let i = 1; i <= emptyCellsEnd; i++) { const thisDay = end.add(i, 'day'); week.push({ dayOfMonth: i, selected: false, inCurrentMonth: false, isToday: nextIsCurrentMonth && today.get('date') === i, isViewing: false, disabled: !this.isInBounds(thisDay), select: () => { this.selectDatetime(thisDay); }, }); } } calendarView.push(week); return calendarView; } private isInBounds(date: dayjs.Dayjs): boolean { if (this.min && this.min.isAfter(date)) { return false; } if (this.max && this.max.isBefore(date)) { return false; } return true; } }
export interface DayCell { dayOfMonth: number; inCurrentMonth: boolean; selected: boolean; isToday: boolean; isViewing: boolean; disabled: boolean; select: () => void; } export type CalendarView = DayCell[][]; export type DayOfWeek = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
import { Directive, HostListener, Inject } from '@angular/core'; import { DropdownComponent } from './dropdown.component'; @Directive({ selector: '[vdrDropdownItem]', // eslint-disable-next-line host: { '[class.dropdown-item]': 'true' }, }) export class DropdownItemDirective { constructor( @Inject(DropdownComponent) private dropdown: DropdownComponent | Promise<DropdownComponent>, ) {} @HostListener('click', ['$event']) async onDropdownItemClick() { (await this.dropdown).onClick(); } }
import { ConnectedPosition, Overlay, OverlayRef, PositionStrategy } from '@angular/cdk/overlay'; import { TemplatePortal } from '@angular/cdk/portal'; import { AfterViewInit, ChangeDetectionStrategy, Component, HostListener, Input, OnDestroy, OnInit, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import { Subscription } from 'rxjs'; import { LocalizationDirectionType, LocalizationService, } from '../../../providers/localization/localization.service'; import { DropdownComponent } from './dropdown.component'; export type DropdownPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; /** * A dropdown menu modelled on the Clarity Dropdown component (https://v1.clarity.design/dropdowns). * * This was created because the Clarity implementation (at this time) does not handle edge detection. Instead * we make use of the Angular CDK's Overlay module to manage the positioning. * * The API of this component (and its related Components & Directives) are based on the Clarity version, * albeit only a subset which is currently used in this application. */ @Component({ selector: 'vdr-dropdown-menu', template: ` <ng-template #menu> <div [dir]="direction$ | async"> <div class="dropdown open"> <div class="dropdown-menu" [ngClass]="customClasses"> <div class="dropdown-content-wrapper" [cdkTrapFocus]="true" [cdkTrapFocusAutoCapture]="true" > <ng-content></ng-content> </div> </div> </div> </div> </ng-template> `, styleUrls: ['./dropdown-menu.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DropdownMenuComponent implements AfterViewInit, OnInit, OnDestroy { direction$: LocalizationDirectionType; @Input('vdrPosition') private position: DropdownPosition = 'bottom-left'; @Input() customClasses: string; @ViewChild('menu', { static: true }) private menuTemplate: TemplateRef<any>; private menuPortal: TemplatePortal; private overlayRef: OverlayRef; private backdropClickSub: Subscription; @HostListener('window:keydown.escape', ['$event']) onEscapeKeydown(event: KeyboardEvent) { if (this.dropdown.isOpen) { if (this.overlayRef.overlayElement.contains(document.activeElement)) { this.dropdown.toggleOpen(); } } } @HostListener('window:keydown', ['$event']) onArrowKey(event: KeyboardEvent) { if ( this.dropdown.isOpen && document.activeElement instanceof HTMLElement && (event.key === 'ArrowDown' || event.key === 'ArrowUp') ) { const dropdownItems = Array.from( this.overlayRef.overlayElement.querySelectorAll<HTMLElement>('.dropdown-item'), ); const currentIndex = dropdownItems.indexOf(document.activeElement); if (currentIndex === -1) { return; } if (event.key === 'ArrowDown') { const nextItem = dropdownItems[(currentIndex + 1) % dropdownItems.length]; nextItem.focus(); } if (event.key === 'ArrowUp') { const previousItem = dropdownItems[(currentIndex - 1 + dropdownItems.length) % dropdownItems.length]; previousItem.focus(); } } } constructor( private overlay: Overlay, private viewContainerRef: ViewContainerRef, private dropdown: DropdownComponent, private localizationService: LocalizationService, ) {} ngOnInit(): void { this.direction$ = this.localizationService.direction$; this.dropdown.onOpenChange(isOpen => { if (isOpen) { this.overlayRef.attach(this.menuPortal); } else { this.overlayRef.detach(); } }); } ngAfterViewInit() { this.overlayRef = this.overlay.create({ hasBackdrop: true, backdropClass: 'clear-backdrop', positionStrategy: this.getPositionStrategy(), maxHeight: '70vh', }); this.menuPortal = new TemplatePortal(this.menuTemplate, this.viewContainerRef); this.backdropClickSub = this.overlayRef.backdropClick().subscribe(() => { this.dropdown.toggleOpen(); }); } ngOnDestroy(): void { if (this.overlayRef) { this.overlayRef.dispose(); } if (this.backdropClickSub) { this.backdropClickSub.unsubscribe(); } } private getPositionStrategy(): PositionStrategy { const position: { [K in DropdownPosition]: ConnectedPosition } = { ['top-left']: { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', }, ['top-right']: { originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom', }, ['bottom-left']: { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', }, ['bottom-right']: { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top', }, }; const pos = position[this.position]; return this.overlay .position() .flexibleConnectedTo(this.dropdown.trigger) .withPositions([pos, this.invertPosition(pos)]) .withViewportMargin(12) .withPush(true); } /** Inverts an overlay position. */ private invertPosition(pos: ConnectedPosition): ConnectedPosition { const inverted = { ...pos }; inverted.originY = pos.originY === 'top' ? 'bottom' : 'top'; inverted.overlayY = pos.overlayY === 'top' ? 'bottom' : 'top'; return inverted; } }
import { Directive, ElementRef, HostListener } from '@angular/core'; import { DropdownComponent } from './dropdown.component'; @Directive({ selector: '[vdrDropdownTrigger]', }) export class DropdownTriggerDirective { constructor(private dropdown: DropdownComponent, private elementRef: ElementRef) { dropdown.setTriggerElement(this.elementRef); } @HostListener('click', ['$event']) onDropdownTriggerClick(event: any): void { this.dropdown.toggleOpen(); } }
import { ChangeDetectionStrategy, Component, ElementRef, Input } from '@angular/core'; /** * @description * Used for building dropdown menus. * * @example * ```HTML * <vdr-dropdown> * <button class="btn btn-outline" vdrDropdownTrigger> * <clr-icon shape="plus"></clr-icon> * Select type * </button> * <vdr-dropdown-menu vdrPosition="bottom-left"> * <button * *ngFor="let typeName of allTypes" * type="button" * vdrDropdownItem * (click)="selectType(typeName)" * > * typeName * </button> * </vdr-dropdown-menu> * </vdr-dropdown> * ``` * @docsCategory components */ @Component({ selector: 'vdr-dropdown', templateUrl: './dropdown.component.html', styleUrls: ['./dropdown.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DropdownComponent { isOpen = false; private onOpenChangeCallbacks: Array<(isOpen: boolean) => void> = []; public trigger: ElementRef; @Input() manualToggle = false; onClick() { if (!this.manualToggle) { this.toggleOpen(); } } toggleOpen() { this.isOpen = !this.isOpen; this.onOpenChangeCallbacks.forEach(fn => fn(this.isOpen)); } onOpenChange(callback: (isOpen: boolean) => void) { this.onOpenChangeCallbacks.push(callback); } setTriggerElement(elementRef: ElementRef) { this.trigger = elementRef; } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { lastValueFrom, Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { ConfigurableOperation, DuplicateEntityDocument, GetEntityDuplicatorsDocument, GetEntityDuplicatorsQuery, } from '../../../common/generated-types'; import { configurableDefinitionToInstance, toConfigurableOperationInput, } from '../../../common/utilities/configurable-operation-utils'; import { DataService } from '../../../data/providers/data.service'; import { Dialog } from '../../../providers/modal/modal.types'; import { NotificationService } from '../../../providers/notification/notification.service'; type EntityDuplicatorDef = GetEntityDuplicatorsQuery['entityDuplicators'][0]; @Component({ selector: 'vdr-duplicate-entity-dialog', templateUrl: './duplicate-entity-dialog.component.html', styleUrls: ['./duplicate-entity-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DuplicateEntityDialogComponent<T extends { id: string }> implements OnInit, Dialog<boolean> { resolveWith: (result?: boolean | undefined) => void; protected entityDuplicators$: Observable<EntityDuplicatorDef[]>; protected selectedDuplicator: EntityDuplicatorDef | undefined; protected duplicatorInstance: ConfigurableOperation; protected formGroup = new FormControl<ConfigurableOperation>({ code: '', args: [], }); title?: string; entities: T[]; entityName: string; getEntityName: (entity: T) => string; constructor( private dataService: DataService, private notificationService: NotificationService, private changeDetectorRef: ChangeDetectorRef, ) {} ngOnInit() { this.entityDuplicators$ = this.dataService .query(GetEntityDuplicatorsDocument) .mapSingle(data => data.entityDuplicators.filter(d => d.forEntities.includes(this.entityName))) .pipe( tap(duplicators => { if (0 < duplicators.length) { this.setSelectedDuplicator(duplicators[0]); } }), ); } setSelectedDuplicator(duplicator: EntityDuplicatorDef) { this.selectedDuplicator = duplicator; this.duplicatorInstance = configurableDefinitionToInstance(this.selectedDuplicator); this.formGroup.patchValue(this.duplicatorInstance); this.changeDetectorRef.markForCheck(); } async duplicate() { const selectedDuplicator = this.selectedDuplicator; const formValue = this.formGroup.value; if (!selectedDuplicator || !formValue) { return; } const duplicatorInput = toConfigurableOperationInput(this.duplicatorInstance, formValue); const succeeded: string[] = []; const failed: Array<{ name: string; message: string }> = []; for (const entity of this.entities) { const { duplicateEntity } = await lastValueFrom( this.dataService.mutate(DuplicateEntityDocument, { input: { entityId: entity.id, entityName: this.entityName, duplicatorInput, }, }), ); switch (duplicateEntity.__typename) { case 'DuplicateEntitySuccess': succeeded.push(this.getEntityName(entity)); break; case 'DuplicateEntityError': failed.push({ name: this.getEntityName(entity), message: duplicateEntity.duplicationError, }); break; case undefined: break; default: assertNever(duplicateEntity); } } if (0 < succeeded.length) { this.notificationService.success(_('common.notify-duplicate-success'), { count: succeeded.length, names: succeeded.join(', '), }); } if (0 < failed.length) { const failedCount = failed.length; const maxNotices = 5; const excess = failedCount - maxNotices; for (let i = 0; i < Math.min(failedCount, maxNotices); i++) { const failedItem = failed[i]; this.notificationService.error(_('common.notify-duplicate-error'), { name: failedItem.name, error: failedItem.message, }); } if (excess > 0) { this.notificationService.error(_('common.notify-duplicate-error-excess'), { count: excess }); } } this.resolveWith(true); } cancel() { this.resolveWith(); } }
import { gql } from 'apollo-angular'; export const GET_ENTITY_DUPLICATORS = gql` query GetEntityDuplicators { entityDuplicators { code description forEntities requiresPermission args { name type required defaultValue list ui label description } } } `; export const DUPLICATE_ENTITY = gql` mutation DuplicateEntity($input: DuplicateEntityInput!) { duplicateEntity(input: $input) { ... on DuplicateEntitySuccess { newEntityId } ... on ErrorResult { errorCode message } ... on DuplicateEntityError { duplicationError } } } `;
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { Dialog } from '../../../providers/modal/modal.types'; @Component({ selector: 'vdr-edit-note-dialog', templateUrl: './edit-note-dialog.component.html', styleUrls: ['./edit-note-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class EditNoteDialogComponent implements Dialog<{ note: string; isPrivate?: boolean }> { displayPrivacyControls = true; noteIsPrivate = true; note = ''; resolveWith: (result?: { note: string; isPrivate?: boolean }) => void; confirm() { this.resolveWith({ note: this.note, isPrivate: this.noteIsPrivate, }); } cancel() { this.resolveWith(); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-empty-placeholder', templateUrl: './empty-placeholder.component.html', styleUrls: ['./empty-placeholder.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class EmptyPlaceholderComponent { @Input() emptyStateLabel: string; }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-entity-info', templateUrl: './entity-info.component.html', styleUrls: ['./entity-info.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class EntityInfoComponent { @Input() small = false; @Input() entity: { id: string; createdAt?: string; updatedAt?: string }; }
export interface ExtensionHostOptions { extensionUrl: string; openInNewTab?: boolean; } export class ExtensionHostConfig { public extensionUrl: string; public openInNewTab: boolean; constructor(options: ExtensionHostOptions) { this.extensionUrl = options.extensionUrl; this.openInNewTab = options.openInNewTab != null ? options.openInNewTab : false; } }
import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, OnDestroy, OnInit, ViewChild, } from '@angular/core'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; import { ActivatedRoute } from '@angular/router'; import { SharedModule } from '../../shared.module'; import { ExtensionHostConfig } from './extension-host-config'; import { ExtensionHostService } from './extension-host.service'; /** * This component uses an iframe to embed an external url into the Admin UI, and uses the PostMessage * protocol to allow cross-frame communication between the two frames. */ @Component({ selector: 'vdr-extension-host', templateUrl: './extension-host.component.html', styleUrls: ['./extension-host.component.scss'], changeDetection: ChangeDetectionStrategy.Default, standalone: true, imports: [SharedModule], providers: [ExtensionHostService], }) export class ExtensionHostComponent implements OnInit, AfterViewInit, OnDestroy { extensionUrl: SafeResourceUrl; openInIframe = true; extensionWindowIsOpen = false; private config: ExtensionHostConfig; private extensionWindow?: Window; @ViewChild('extensionFrame') private extensionFrame: ElementRef<HTMLIFrameElement>; constructor( private route: ActivatedRoute, private sanitizer: DomSanitizer, private extensionHostService: ExtensionHostService, ) {} ngOnInit() { const { data } = this.route.snapshot; if (!this.isExtensionHostConfig(data.extensionHostConfig)) { throw new Error( `Expected an ExtensionHostConfig object, got ${JSON.stringify(data.extensionHostConfig)}`, ); } this.config = data.extensionHostConfig; this.openInIframe = !this.config.openInNewTab; this.extensionUrl = this.sanitizer.bypassSecurityTrustResourceUrl( this.config.extensionUrl || 'about:blank', ); } ngAfterViewInit() { if (this.openInIframe) { const extensionWindow = this.extensionFrame.nativeElement.contentWindow; if (extensionWindow) { this.extensionHostService.init(extensionWindow, this.route.snapshot); } } } ngOnDestroy(): void { if (this.extensionWindow) { this.extensionWindow.close(); } } launchExtensionWindow() { const extensionWindow = window.open(this.config.extensionUrl); if (!extensionWindow) { return; } this.extensionHostService.init(extensionWindow, this.route.snapshot); this.extensionWindowIsOpen = true; this.extensionWindow = extensionWindow; let timer: number; function pollWindowState(extwindow: Window, onClosed: () => void) { if (extwindow.closed) { window.clearTimeout(timer); onClosed(); } else { timer = window.setTimeout(() => pollWindowState(extwindow, onClosed), 250); } } pollWindowState(extensionWindow, () => { this.extensionWindowIsOpen = false; this.extensionHostService.destroy(); }); } private isExtensionHostConfig(input: any): input is ExtensionHostConfig { return input.hasOwnProperty('extensionUrl'); } }
import { Injectable, OnDestroy } from '@angular/core'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { ActiveRouteData, ExtensionMessage, MessageResponse } from '@vendure/common/lib/extension-host-types'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { parse } from 'graphql'; import { merge, Observer, Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; import { DataService } from '../../../data/providers/data.service'; import { NotificationService } from '../../../providers/notification/notification.service'; @Injectable() export class ExtensionHostService implements OnDestroy { private extensionWindow: Window; private routeSnapshot: ActivatedRouteSnapshot; private cancellationMessage$ = new Subject<string>(); private destroyMessage$ = new Subject<void>(); constructor(private dataService: DataService, private notificationService: NotificationService) {} init(extensionWindow: Window, routeSnapshot: ActivatedRouteSnapshot) { this.extensionWindow = extensionWindow; this.routeSnapshot = routeSnapshot; window.addEventListener('message', this.handleMessage); } destroy() { window.removeEventListener('message', this.handleMessage); this.destroyMessage$.next(); } ngOnDestroy(): void { this.destroy(); } private handleMessage = (message: MessageEvent<ExtensionMessage>) => { const { data, origin } = message; if (this.isExtensionMessage(data)) { const cancellation$ = this.cancellationMessage$.pipe( filter(requestId => requestId === data.requestId), ); const end$ = merge(cancellation$, this.destroyMessage$); switch (data.type) { case 'cancellation': { this.cancellationMessage$.next(data.requestId); break; } case 'destroy': { this.destroyMessage$.next(); break; } case 'active-route': { const routeData: ActiveRouteData = { url: window.location.href, origin: window.location.origin, pathname: window.location.pathname, params: this.routeSnapshot.params, queryParams: this.routeSnapshot.queryParams, fragment: this.routeSnapshot.fragment, }; this.sendMessage( { data: routeData, error: false, complete: false, requestId: data.requestId }, origin, ); this.sendMessage( { data: null, error: false, complete: true, requestId: data.requestId }, origin, ); break; } case 'graphql-query': { const { document, variables, fetchPolicy } = data.data; this.dataService .query(parse(document), variables, fetchPolicy) .stream$.pipe(takeUntil(end$)) .subscribe(this.createObserver(data.requestId, origin)); break; } case 'graphql-mutation': { const { document, variables } = data.data; this.dataService .mutate(parse(document), variables) .pipe(takeUntil(end$)) .subscribe(this.createObserver(data.requestId, origin)); break; } case 'notification': { this.notificationService.notify(data.data); break; } default: assertNever(data); } } }; private createObserver(requestId: string, origin: string): Observer<any> { return { next: data => this.sendMessage({ data, error: false, complete: false, requestId }, origin), error: err => this.sendMessage({ data: err, error: true, complete: false, requestId }, origin), complete: () => this.sendMessage({ data: null, error: false, complete: true, requestId }, origin), }; } private sendMessage(response: MessageResponse, origin: string) { this.extensionWindow.postMessage(response, origin); } private isExtensionMessage(input: any): input is ExtensionMessage { return ( input.hasOwnProperty('type') && input.hasOwnProperty('data') && input.hasOwnProperty('requestId') ); } }
import { Route } from '@angular/router'; import { ExtensionHostConfig, ExtensionHostOptions } from './extension-host-config'; import { ExtensionHostComponent } from './extension-host.component'; export interface ExternalFrameOptions extends ExtensionHostOptions { path: string; breadcrumbLabel: string; } /** * This function is used to conveniently configure a UI extension route to * host an external URL from the Admin UI using the {@link ExtensionHostComponent} * * @example * ```ts * \@NgModule({ * imports: [ * RouterModule.forChild([ * hostExternalFrame({ * path: '', * breadcrumbLabel: 'Vue.js App', * extensionUrl: './assets/vue-app/index.html', * openInNewTab: false, * }), * ]), * ], * }) export class VueUiExtensionModule {} * ``` */ export function hostExternalFrame(options: ExternalFrameOptions): Route { const pathMatch = options.path === '' ? 'full' : 'prefix'; return { path: options.path, pathMatch, component: ExtensionHostComponent, data: { breadcrumb: [ { label: options.breadcrumbLabel, link: ['./'], }, ], extensionHostConfig: new ExtensionHostConfig(options), }, }; }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { FacetValueFragment } from '../../../common/generated-types'; @Component({ selector: 'vdr-facet-value-chip', templateUrl: './facet-value-chip.component.html', styleUrls: ['./facet-value-chip.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FacetValueChipComponent { @Input() facetValue: FacetValueFragment; @Input() removable = true; @Input() displayFacetName = true; @Output() remove = new EventEmitter<void>(); }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { NgSelectComponent } from '@ng-select/ng-select'; import { concat, merge, Observable, of, Subject, Subscription } from 'rxjs'; import { debounceTime, distinctUntilChanged, mapTo, switchMap, tap } from 'rxjs/operators'; import { FacetValue, FacetValueFragment } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; /** * @description * A form control for selecting facet values. * * @example * ```HTML * <vdr-facet-value-selector * [facets]="facets" * (selectedValuesChange)="selectedValues = $event" * ></vdr-facet-value-selector> * ``` * The `facets` input should be provided from the parent component * like this: * * @example * ```ts * this.facets = this.dataService * .facet.getAllFacets() * .mapSingle(data => data.facets.items); * ``` * @docsCategory components */ @Component({ selector: 'vdr-facet-value-selector', templateUrl: './facet-value-selector.component.html', styleUrls: ['./facet-value-selector.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: FacetValueSelectorComponent, multi: true, }, ], }) export class FacetValueSelectorComponent implements OnInit, OnDestroy, ControlValueAccessor { @Output() selectedValuesChange = new EventEmitter<FacetValueFragment[]>(); @Input() readonly = false; @Input() transformControlValueAccessorValue: (value: FacetValueFragment[]) => any[] = value => value; searchInput$ = new Subject<string>(); searchLoading = false; searchResults$: Observable<FacetValueFragment[]>; selectedIds$ = new Subject<string[]>(); @ViewChild(NgSelectComponent) private ngSelect: NgSelectComponent; onChangeFn: (val: any) => void; onTouchFn: () => void; disabled = false; value: Array<string | FacetValueFragment>; private subscription: Subscription; constructor( private dataService: DataService, private changeDetectorRef: ChangeDetectorRef, ) {} ngOnInit(): void { this.initSearchResults(); } private initSearchResults() { const searchItems$ = this.searchInput$.pipe( debounceTime(200), distinctUntilChanged(), tap(() => (this.searchLoading = true)), switchMap(term => { if (!term) { return of([]); } return this.dataService.facet .getFacetValues({ take: 100, filter: { name: { contains: term } } }) .mapSingle(result => result.facetValues.items); }), tap(() => (this.searchLoading = false)), ); this.subscription = this.selectedIds$ .pipe( switchMap(ids => { if (!ids.length) { return of([]); } return this.dataService.facet .getFacetValues({ take: 100, filter: { id: { in: ids } } }, 'cache-first') .mapSingle(result => result.facetValues.items); }), ) .subscribe(val => { this.value = val; this.changeDetectorRef.markForCheck(); }); const clear$ = this.selectedValuesChange.pipe(mapTo([])); this.searchResults$ = concat(of([]), merge(searchItems$, clear$)); } ngOnDestroy() { this.subscription?.unsubscribe(); } onChange(selected: FacetValueFragment[]) { if (this.readonly) { return; } for (const sel of selected) { console.log(`selected: ${sel.facet.name}:${sel.code}`); } this.selectedValuesChange.emit(selected); if (this.onChangeFn) { const transformedValue = this.transformControlValueAccessorValue(selected); this.onChangeFn(transformedValue); } } registerOnChange(fn: any) { this.onChangeFn = fn; } registerOnTouched(fn: any) { this.onTouchFn = fn; } setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } focus() { this.ngSelect.focus(); } writeValue(obj: string | FacetValueFragment[] | Array<string | number> | null): void { let valueIds: string[] | undefined; if (typeof obj === 'string') { try { const facetValueIds = JSON.parse(obj) as string[]; valueIds = facetValueIds; } catch (err) { // TODO: log error throw err; } } else if (Array.isArray(obj)) { const isIdArray = (input: unknown[]): input is Array<string | number> => input.every(i => typeof i === 'number' || typeof i === 'string'); if (isIdArray(obj)) { valueIds = obj.map(fv => fv.toString()); } else { valueIds = obj.map(fv => fv.id); } } if (valueIds) { // this.value = valueIds; this.selectedIds$.next(valueIds); } } }
import { CdkDragEnd } from '@angular/cdk/drag-drop'; import { ChangeDetectionStrategy, Component, ElementRef, EventEmitter, HostBinding, Input, Output, ViewChild, } from '@angular/core'; export type Point = { x: number; y: number }; @Component({ selector: 'vdr-focal-point-control', templateUrl: './focal-point-control.component.html', styleUrls: ['./focal-point-control.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FocalPointControlComponent { @Input() visible = false; @Input() editable = false; @HostBinding('style.width.px') @Input() width: number; @HostBinding('style.height.px') @Input() height: number; @Input() fpx = 0.5; @Input() fpy = 0.5; @Output() focalPointChange = new EventEmitter<Point>(); @ViewChild('frame', { static: true }) frame: ElementRef<HTMLDivElement>; @ViewChild('dot', { static: true }) dot: ElementRef<HTMLDivElement>; get initialPosition(): Point { return this.focalPointToOffset(this.fpx == null ? 0.5 : this.fpx, this.fpy == null ? 0.5 : this.fpy); } onDragEnded(event: CdkDragEnd) { const { x, y } = this.getCurrentFocalPoint(); this.fpx = x; this.fpy = y; this.focalPointChange.emit({ x, y }); } private getCurrentFocalPoint(): Point { const { left: dotLeft, top: dotTop, width, height } = this.dot.nativeElement.getBoundingClientRect(); const { left: frameLeft, top: frameTop } = this.frame.nativeElement.getBoundingClientRect(); const xInPx = dotLeft - frameLeft + width / 2; const yInPx = dotTop - frameTop + height / 2; return { x: xInPx / this.width, y: yInPx / this.height, }; } private focalPointToOffset(x: number, y: number): Point { const { width, height } = this.dot.nativeElement.getBoundingClientRect(); return { x: x * this.width - width / 2, y: y * this.height - height / 2, }; } }
import { Directive, ElementRef, Optional } from '@angular/core'; import { NgControl } from '@angular/forms'; type InputElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement; /* eslint-disable @angular-eslint/directive-selector */ @Directive({ selector: 'input, textarea, select, vdr-currency-input' }) export class FormFieldControlDirective { constructor( private elementRef: ElementRef<InputElement>, @Optional() public formControlName: NgControl, ) {} get valid(): boolean { return !!this.formControlName && !!this.formControlName.valid; } get touched(): boolean { return !!this.formControlName && !!this.formControlName.touched; } setReadOnly(value: boolean) { const input = this.elementRef.nativeElement; if (isSelectElement(input)) { input.disabled = value; } else { input.readOnly = value; } } } function isSelectElement(value: InputElement): value is HTMLSelectElement { return value.hasOwnProperty('selectedIndex'); }
import { Component, ContentChild, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { FormFieldControlDirective } from './form-field-control.directive'; /** * A form field wrapper which handles the correct layout and validation error display for * a form control. */ @Component({ selector: 'vdr-form-field', templateUrl: './form-field.component.html', styleUrls: ['./form-field.component.scss'], }) export class FormFieldComponent implements OnInit { @Input() label: string; @Input() for: string; @Input() tooltip: string; /** * A map of error message codes (required, pattern etc.) to messages to display * when those errors are present. */ @Input() errors: { [key: string]: string } = {}; /** * If set to true, the input will be initially set to "readOnly", and an "edit" button * will be displayed which allows the field to be edited. */ @Input() readOnlyToggle = false; @Output() readOnlyToggleChange = new EventEmitter<boolean>(); @ContentChild(FormFieldControlDirective, { static: true }) formFieldControl: FormFieldControlDirective; isReadOnly = false; ngOnInit() { if (this.readOnlyToggle) { this.isReadOnly = true; this.setReadOnly(true); } this.isReadOnly = this.readOnlyToggle; } setReadOnly(value: boolean) { this.formFieldControl.setReadOnly(value); this.isReadOnly = value; this.readOnlyToggleChange.emit(value); } getErrorMessage(): string | undefined { if (!this.formFieldControl || !this.formFieldControl.formControlName) { return; } const errors = this.formFieldControl.formControlName.dirty && this.formFieldControl.formControlName.errors; if (errors) { for (const errorKey of Object.keys(errors)) { if (this.errors[errorKey]) { return this.errors[errorKey]; } } } } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; /** * Like the {@link FormFieldComponent} but for content which is not a form control. Used * to keep a consistent layout with other form fields in the form. */ @Component({ selector: 'vdr-form-item', templateUrl: './form-item.component.html', styleUrls: ['./form-item.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FormItemComponent { @Input() label: string; @Input() tooltip: string; }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { AddressFragment, OrderAddress } from '../../../common/generated-types'; @Component({ selector: 'vdr-formatted-address', templateUrl: './formatted-address.component.html', styleUrls: ['./formatted-address.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FormattedAddressComponent { @Input() address: AddressFragment | OrderAddress; getCountryName(): string { if (this.isAddressFragment(this.address)) { return this.address.country.name; } else { return this.address.country || ''; } } getCustomFields(): Array<{ key: string; value: any }> { const customFields = (this.address as any).customFields; if (customFields) { return Object.entries(customFields) .filter(([key]) => key !== '__typename') .map(([key, value]) => ({ key, value: (value as any)?.toString() ?? '-' })); } else { return []; } } private isAddressFragment(input: AddressFragment | OrderAddress): input is AddressFragment { return typeof input.country !== 'string'; } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-help-tooltip', templateUrl: './help-tooltip.component.html', styleUrls: ['./help-tooltip.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class HelpTooltipComponent { @Input() content: string; @Input() position: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left' | 'right' | 'left'; }
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'vdr-history-entry-detail', templateUrl: './history-entry-detail.component.html', styleUrls: ['./history-entry-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class HistoryEntryDetailComponent {}
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; /** * A control for setting the number of items per page in a paginated list. */ @Component({ selector: 'vdr-items-per-page-controls', templateUrl: './items-per-page-controls.component.html', styleUrls: ['./items-per-page-controls.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ItemsPerPageControlsComponent { @Input() itemsPerPage = 10; @Output() itemsPerPageChange = new EventEmitter<number>(); }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-labeled-data', templateUrl: './labeled-data.component.html', styleUrls: ['./labeled-data.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class LabeledDataComponent { @Input() label: string; }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, forwardRef, Input, OnDestroy, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { Subscription } from 'rxjs'; import { DataService } from '../../../data/providers/data.service'; @Component({ selector: 'vdr-language-code-selector', templateUrl: './language-code-selector.component.html', styleUrls: ['./language-code-selector.component.css'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => LanguageCodeSelectorComponent), multi: true, }, ], }) export class LanguageCodeSelectorComponent implements ControlValueAccessor, OnDestroy { @Input() languageCodes: string[]; private subscription: Subscription; private locale: string; protected value: string | undefined; onChangeFn: (value: any) => void; onTouchFn: (value: any) => void; searchLanguageCodes = (term: string, item: string) => { let languageCodeName = item; const languagePart = item.split('_')[0]; try { languageCodeName = new Intl.DisplayNames([this.locale], { type: 'language', }).of(languagePart) ?? item; } catch (e) { // ignore } return languageCodeName?.toLowerCase().includes(term.toLowerCase()); }; constructor(dataService?: DataService, changeDetectorRef?: ChangeDetectorRef) { if (dataService && changeDetectorRef) { this.subscription = dataService.client .uiState() .mapStream(data => data.uiState) .subscribe(({ language, locale }) => { this.locale = language.replace(/_/g, '-'); if (locale) { this.locale += `-${locale}`; } changeDetectorRef.markForCheck(); }); } } writeValue(obj: any): void { this.value = obj; } registerOnChange(fn: any): void { this.onChangeFn = fn; } registerOnTouched(fn: any): void { this.onTouchFn = fn; } ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } }
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { LanguageCode } from '../../../common/generated-types'; @Component({ selector: 'vdr-language-selector', templateUrl: './language-selector.component.html', styleUrls: ['./language-selector.component.scss'], }) export class LanguageSelectorComponent { @Input() currentLanguageCode: LanguageCode; @Input() availableLanguageCodes: LanguageCode[]; @Input() disabled = false; @Output() languageCodeChange = new EventEmitter<LanguageCode>(); }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { Observable } from 'rxjs'; import { LanguageCode, LocalizedString } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; @Component({ selector: 'vdr-localized-text', templateUrl: './localized-text.component.html', styleUrls: ['./localized-text.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class LocalizedTextComponent { @Input() text: LocalizedString[] | string; uiLanguage$: Observable<LanguageCode>; constructor(private dataService: DataService) { this.uiLanguage$ = this.dataService.client.uiState().mapStream(data => data.uiState.language); } isString(value: string | LocalizedString[]): value is string { return typeof value === 'string'; } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { forkJoin, Observable } from 'rxjs'; import { GetTagListQuery } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; import { Dialog } from '../../../providers/modal/modal.types'; @Component({ selector: 'vdr-manage-tags-dialog', templateUrl: './manage-tags-dialog.component.html', styleUrls: ['./manage-tags-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ManageTagsDialogComponent implements Dialog<boolean>, OnInit { resolveWith: (result: boolean | undefined) => void; allTags$: Observable<GetTagListQuery['tags']['items']>; toDelete: string[] = []; toUpdate: Array<{ id: string; value: string }> = []; constructor(private dataService: DataService) {} ngOnInit(): void { this.allTags$ = this.dataService.product.getTagList().mapStream(data => data.tags.items); } toggleDelete(id: string) { const marked = this.markedAsDeleted(id); if (marked) { this.toDelete = this.toDelete.filter(_id => _id !== id); } else { this.toDelete.push(id); } } markedAsDeleted(id: string): boolean { return this.toDelete.includes(id); } updateTagValue(id: string, value: string) { const exists = this.toUpdate.find(i => i.id === id); if (exists) { exists.value = value; } else { this.toUpdate.push({ id, value }); } } saveChanges() { const operations: Array<Observable<any>> = []; for (const id of this.toDelete) { operations.push(this.dataService.product.deleteTag(id)); } for (const item of this.toUpdate) { if (!this.toDelete.includes(item.id)) { operations.push(this.dataService.product.updateTag(item)); } } return forkJoin(operations).subscribe(() => this.resolveWith(true)); } }
import { Directive, OnInit, TemplateRef } from '@angular/core'; import { ModalDialogComponent } from './modal-dialog.component'; /** * A helper directive used to correctly embed the modal buttons in the {@link ModalDialogComponent}. */ @Directive({ selector: '[vdrDialogButtons]' }) export class DialogButtonsDirective implements OnInit { constructor(private modal: ModalDialogComponent<any>, private templateRef: TemplateRef<any>) {} ngOnInit() { // setTimeout due to https://github.com/angular/angular/issues/15634 setTimeout(() => this.modal.registerButtonsTemplate(this.templateRef)); } }
import { Component, EventEmitter, Input, OnInit, Output, Type, ViewContainerRef } from '@angular/core'; /** * A helper component used to embed a component instance into the {@link ModalDialogComponent} */ @Component({ selector: 'vdr-dialog-component-outlet', template: ``, }) export class DialogComponentOutletComponent implements OnInit { @Input() component: Type<any>; @Output() create = new EventEmitter<any>(); constructor(private viewContainerRef: ViewContainerRef) {} ngOnInit() { const componentRef = this.viewContainerRef.createComponent(this.component); this.create.emit(componentRef.instance); } }
import { Directive, OnInit, TemplateRef } from '@angular/core'; import { ModalDialogComponent } from './modal-dialog.component'; /** * A helper directive used to correctly embed the modal title in the {@link ModalDialogComponent}. */ @Directive({ selector: '[vdrDialogTitle]' }) export class DialogTitleDirective implements OnInit { constructor(private modal: ModalDialogComponent<any>, private templateRef: TemplateRef<any>) {} ngOnInit() { // setTimeout due to https://github.com/angular/angular/issues/15634 setTimeout(() => this.modal.registerTitleTemplate(this.templateRef)); } }
import { Component, OnInit, TemplateRef, Type } from '@angular/core'; import { Subject } from 'rxjs'; import { LocalizationDirectionType, LocalizationService, } from '../../../providers/localization/localization.service'; import { Dialog, ModalOptions } from '../../../providers/modal/modal.types'; import { DialogButtonsDirective } from './dialog-buttons.directive'; /** * This component should only be instantiated dynamically by the ModalService. It should not be used * directly in templates. See {@link ModalService.fromComponent} method for more detail. */ @Component({ selector: 'vdr-modal-dialog', templateUrl: './modal-dialog.component.html', styleUrls: ['./modal-dialog.component.scss'], }) export class ModalDialogComponent<T extends Dialog<any>> implements OnInit { direction$: LocalizationDirectionType; childComponentType: Type<T>; closeModal: (result?: any) => void; titleTemplateRef$ = new Subject<TemplateRef<any>>(); buttonsTemplateRef$ = new Subject<TemplateRef<any>>(); options?: ModalOptions<T>; /** * */ constructor(private localizationService: LocalizationService) {} ngOnInit(): void { this.direction$ = this.localizationService.direction$; } /** * This callback is invoked when the childComponentType is instantiated in the * template by the {@link DialogComponentOutletComponent}. * Once we have the instance, we can set the resolveWith function and any * locals which were specified in the config. */ onCreate(componentInstance: T) { componentInstance.resolveWith = (result?: any) => { this.closeModal(result); }; if (this.options && this.options.locals) { // eslint-disable-next-line for (const key in this.options.locals) { componentInstance[key] = this.options.locals[key] as T[Extract<keyof T, string>]; } } } /** * This should be called by the {@link DialogTitleDirective} only */ registerTitleTemplate(titleTemplateRef: TemplateRef<any>) { this.titleTemplateRef$.next(titleTemplateRef); } /** * This should be called by the {@link DialogButtonsDirective} only */ registerButtonsTemplate(buttonsTemplateRef: TemplateRef<any>) { this.buttonsTemplateRef$.next(buttonsTemplateRef); } /** * Called when the modal is closed by clicking the X or the mask. */ modalOpenChange(status: any) { if (status === false) { this.closeModal(); } } }
import { ChangeDetectionStrategy, Component, Input, OnChanges, OnInit, Optional, SkipSelf, } from '@angular/core'; /** * @description * This component displays a plain JavaScript object as an expandable tree. * * @example * ```HTML * <vdr-object-tree [value]="payment.metadata"></vdr-object-tree> * ``` * * @docsCategory components */ @Component({ selector: 'vdr-object-tree', templateUrl: './object-tree.component.html', styleUrls: ['./object-tree.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ObjectTreeComponent implements OnChanges { @Input() value: { [key: string]: any } | string; @Input() isArrayItem = false; depth: number; expanded: boolean; valueIsArray: boolean; entries: Array<{ key: string; value: any }>; constructor(@Optional() @SkipSelf() parent: ObjectTreeComponent) { if (parent) { this.depth = parent.depth + 1; } else { this.depth = 0; } } ngOnChanges() { this.entries = this.getEntries(this.value); this.expanded = this.depth === 0 || this.isArrayItem; this.valueIsArray = Object.keys(this.value).every(v => Number.isInteger(+v)); } isObject(value: any): boolean { return typeof value === 'object' && value !== null; } private getEntries(inputValue: { [key: string]: any } | string): Array<{ key: string; value: any }> { if (!this.isObject(inputValue)) { return [{ key: '', value: inputValue }]; } return Object.entries(inputValue).map(([key, value]) => ({ key, value })); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; /** * @description * Displays the state of an order in a colored chip. * * @example * ```HTML * <vdr-order-state-label [state]="order.state"></vdr-order-state-label> * ``` * @docsCategory components */ @Component({ selector: 'vdr-order-state-label', templateUrl: './order-state-label.component.html', styleUrls: ['./order-state-label.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderStateLabelComponent { @Input() state: string; get chipColorType() { switch (this.state) { case 'AddingItems': case 'ArrangingPayment': return ''; case 'Delivered': return 'success'; case 'Cancelled': case 'Draft': return 'error'; case 'PaymentAuthorized': case 'PaymentSettled': case 'PartiallyDelivered': case 'PartiallyShipped': case 'Shipped': default: return 'warning'; } } }
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'vdr-page-block', templateUrl: './page-block.component.html', styleUrls: ['./page-block.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageBlockComponent {}
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'vdr-page-body', templateUrl: './page-body.component.html', styleUrls: ['./page-body.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageBodyComponent {}
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'vdr-page-detail-layout', templateUrl: './page-detail-layout.component.html', styleUrls: ['./page-detail-layout.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageDetailLayoutComponent {}
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'vdr-page-detail-sidebar', template: ` <ng-content></ng-content> `, changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageDetailSidebarComponent {}