content
stringlengths
28
1.34M
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-page-entity-info', templateUrl: './page-entity-info.component.html', styleUrls: ['./page-entity-info.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageEntityInfoComponent { @Input() entity: { id: string; createdAt?: string; updatedAt?: string }; }
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'vdr-page-header-description', templateUrl: './page-header-description.component.html', styleUrls: ['./page-header-description.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageHeaderDescriptionComponent {}
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { IsActiveMatchOptions } from '@angular/router'; export interface HeaderTab { id: string; label: string; icon?: string; route?: string[]; } @Component({ selector: 'vdr-page-header-tabs', templateUrl: './page-header-tabs.component.html', styleUrls: ['./page-header-tabs.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageHeaderTabsComponent { @Input() tabs: HeaderTab[] = []; readonly routerLinkActiveOptions: IsActiveMatchOptions = { matrixParams: 'ignored', queryParams: 'ignored', fragment: 'ignored', paths: 'exact', }; }
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'vdr-page-header', templateUrl: './page-header.component.html', styleUrls: ['./page-header.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageHeaderComponent {}
import { ChangeDetectionStrategy, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; import { BehaviorSubject, combineLatest, Observable } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { titleSetter } from '../../../common/title-setter'; import { BreadcrumbService } from '../../../providers/breadcrumb/breadcrumb.service'; @Component({ selector: 'vdr-page-title', templateUrl: './page-title.component.html', styleUrls: [`./page-title.component.scss`], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageTitleComponent implements OnInit, OnChanges { @Input() title = ''; private titleChange$ = new BehaviorSubject<string | undefined>(undefined); protected title$: Observable<string>; readonly setTitle = titleSetter(); constructor(private breadcrumbService: BreadcrumbService) {} ngOnInit() { this.title$ = combineLatest(this.titleChange$, this.breadcrumbService.breadcrumbs$).pipe( map(([title, breadcrumbs]) => { if (title) { return title; } else { return breadcrumbs[breadcrumbs.length - 1].label; } }), tap(title => this.setTitle(title)), ); } ngOnChanges(changes: SimpleChanges) { if (changes.title) { this.titleChange$.next(changes.title.currentValue); } } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Observable, of, switchMap } from 'rxjs'; import { PageLocationId } from '../../../common/component-registry-types'; import { PageService } from '../../../providers/page/page.service'; import { HeaderTab } from '../page-header-tabs/page-header-tabs.component'; @Component({ selector: 'vdr-page', templateUrl: './page.component.html', styleUrls: ['./page.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PageComponent { headerTabs: HeaderTab[] = []; @Input() protected locationId: PageLocationId; @Input() protected description: string; entity$: Observable<{ id: string; createdAt?: string; updatedAt?: string } | undefined>; constructor(private route: ActivatedRoute, private pageService: PageService) { this.locationId = this.route.snapshot.data.locationId; this.description = this.route.snapshot.data.description ?? ''; this.headerTabs = this.pageService.getPageTabs(this.locationId).map(tab => ({ id: tab.tab, label: tab.tab, icon: tab.tabIcon, route: tab.route ? [tab.route] : ['./'], })); this.entity$ = this.route.data.pipe( switchMap(data => (data.entity as Observable<any>) ?? of(undefined)), ); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; @Component({ selector: 'vdr-pagination-controls', templateUrl: './pagination-controls.component.html', styleUrls: ['./pagination-controls.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PaginationControlsComponent { @Input() id?: number; @Input() currentPage: number; @Input() itemsPerPage: number; @Input() totalItems: number; @Output() pageChange = new EventEmitter<number>(); }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { PaginationInstance } from 'ngx-pagination'; import { BehaviorSubject, combineLatest, Observable } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { GetProductVariantsForMultiSelectorDocument, SearchProductsQuery, } from '../../../common/generated-types'; import { SelectionManager } from '../../../common/utilities/selection-manager'; import { DataService } from '../../../data/providers/data.service'; import { Dialog } from '../../../providers/modal/modal.types'; export type SearchItem = SearchProductsQuery['search']['items'][number]; @Component({ selector: 'vdr-product-multi-selector-dialog', templateUrl: './product-multi-selector-dialog.component.html', styleUrls: ['./product-multi-selector-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ProductMultiSelectorDialogComponent implements OnInit, Dialog<SearchItem[]> { mode: 'product' | 'variant' = 'product'; initialSelectionIds: string[] = []; items$: Observable<SearchItem[]>; facetValues$: Observable<SearchProductsQuery['search']['facetValues']>; searchTerm$ = new BehaviorSubject<string>(''); searchFacetValueIds$ = new BehaviorSubject<string[]>([]); paginationConfig: PaginationInstance = { currentPage: 1, itemsPerPage: 25, totalItems: 1, }; selectionManager: SelectionManager<SearchItem>; resolveWith: (result?: SearchItem[]) => void; private paginationConfig$ = new BehaviorSubject<PaginationInstance>(this.paginationConfig); constructor(private dataService: DataService, private changeDetector: ChangeDetectorRef) {} ngOnInit(): void { const idFn = this.mode === 'product' ? (a: SearchItem, b: SearchItem) => a.productId === b.productId : (a: SearchItem, b: SearchItem) => a.productVariantId === b.productVariantId; this.selectionManager = new SelectionManager<SearchItem>({ multiSelect: true, itemsAreEqual: idFn, additiveMode: true, }); const searchQueryResult = this.dataService.product.searchProducts( '', this.paginationConfig.itemsPerPage, 0, ); const result$ = combineLatest( this.searchTerm$, this.searchFacetValueIds$, this.paginationConfig$, ).subscribe(([term, facetValueIds, pagination]) => { const take = +pagination.itemsPerPage; const skip = (pagination.currentPage - 1) * take; return searchQueryResult.ref.refetch({ input: { skip, take, term, facetValueIds, groupByProduct: this.mode === 'product' }, }); }); this.items$ = searchQueryResult.stream$.pipe( tap(data => { this.paginationConfig.totalItems = data.search.totalItems; this.selectionManager.setCurrentItems(data.search.items); }), map(data => data.search.items), ); this.facetValues$ = searchQueryResult.stream$.pipe(map(data => data.search.facetValues)); if (this.initialSelectionIds.length) { if (this.mode === 'product') { this.dataService.product .getProducts({ filter: { id: { in: this.initialSelectionIds, }, }, }) .single$.subscribe(({ products }) => { this.selectionManager.selectMultiple( products.items.map( product => ({ productId: product.id, productName: product.name, } as SearchItem), ), ); this.changeDetector.markForCheck(); }); } else { this.dataService .query(GetProductVariantsForMultiSelectorDocument, { options: { filter: { id: { in: this.initialSelectionIds, }, }, }, }) .single$.subscribe(({ productVariants }) => { this.selectionManager.selectMultiple( productVariants.items.map( variant => ({ productVariantId: variant.id, productVariantName: variant.name, } as SearchItem), ), ); this.changeDetector.markForCheck(); }); } } } trackByFn(index: number, item: SearchItem) { return item.productId; } setSearchTerm(term: string) { this.searchTerm$.next(term); } setFacetValueIds(ids: string[]) { this.searchFacetValueIds$.next(ids); } toggleSelection(item: SearchItem, event: MouseEvent) { this.selectionManager.toggleSelection(item, event); } clearSelection() { this.selectionManager.selectMultiple([]); } isSelected(item: SearchItem) { return this.selectionManager.isSelected(item); } entityInfoClick(event: MouseEvent) { event.preventDefault(); event.stopPropagation(); } pageChange(page: number) { this.paginationConfig.currentPage = page; this.paginationConfig$.next(this.paginationConfig); } itemsPerPageChange(itemsPerPage: number) { this.paginationConfig.itemsPerPage = itemsPerPage; this.paginationConfig$.next(this.paginationConfig); } select() { this.resolveWith(this.selectionManager.selection); } cancel() { this.resolveWith(); } }
import { gql } from 'apollo-angular'; import { ASSET_FRAGMENT } from '../../../data/definitions/product-definitions'; export const GET_PRODUCT_VARIANTS_FOR_MULTI_SELECTOR = gql` query GetProductVariantsForMultiSelector($options: ProductVariantListOptions!) { productVariants(options: $options) { items { id createdAt updatedAt productId enabled languageCode name price currencyCode priceWithTax trackInventory outOfStockThreshold stockLevels { id createdAt updatedAt stockLocationId stockOnHand stockAllocated stockLocation { id createdAt updatedAt name } } useGlobalOutOfStockThreshold sku featuredAsset { ...Asset } } totalItems } } ${ASSET_FRAGMENT} `;
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 } from '../../../common/generated-types'; import { SingleSearchSelectionModelFactory } from '../../../common/single-search-selection-model'; type FacetValueResult = SearchProductsQuery['search']['facetValues'][number]; @Component({ selector: 'vdr-product-search-input', templateUrl: './product-search-input.component.html', styleUrls: ['./product-search-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [{ provide: SELECTION_MODEL_FACTORY, useValue: SingleSearchSelectionModelFactory }], }) export class ProductSearchInputComponent { @Input() facetValueResults: FacetValueResult; @Output() searchTermChange = new EventEmitter<string>(); @Output() facetValueChange = new EventEmitter<string[]>(); @ViewChild('selectComponent', { static: true }) private selectComponent: NgSelectComponent; private lastTerm = ''; private lastFacetValueIds: string[] = []; setSearchTerm(term: string | null) { if (term) { this.selectComponent.select({ label: term, value: { label: term } }); } else { const currentTerm = this.selectComponent.selectedItems.find(i => !this.isFacetValueItem(i.value)); if (currentTerm) { this.selectComponent.unselect(currentTerm); } } } setFacetValues(ids: string[]) { const items = this.selectComponent.items; this.selectComponent.selectedItems.forEach(item => { if (this.isFacetValueItem(item.value) && !ids.includes(item.value.facetValue.id)) { this.selectComponent.unselect(item); } }); ids.map(id => items?.find(item => this.isFacetValueItem(item) && item.facetValue.id === id)) .filter(notNullOrUndefined) .forEach(item => { const isSelected = this.selectComponent.selectedItems.find(i => { const val = i.value; if (this.isFacetValueItem(val)) { return val.facetValue.id === item.facetValue.id; } return false; }); if (!isSelected) { this.selectComponent.select({ label: '', value: item }); } }); } filterFacetResults = (term: string, item: FacetValueResult | { label: string }) => { if (!this.isFacetValueItem(item)) { return false; } const cix = term.indexOf(':'); const facetName = cix > -1 ? term.toLowerCase().slice(0, cix) : null; const facetVal = cix > -1 ? term.toLowerCase().slice(cix + 1) : term.toLowerCase(); if (facetName) { return ( item.facetValue.facet.name.toLowerCase().includes(facetName) && item.facetValue.name.toLocaleLowerCase().includes(facetVal) ); } return ( item.facetValue.name.toLowerCase().includes(term.toLowerCase()) || item.facetValue.facet.name.toLowerCase().includes(term.toLowerCase()) ); }; onSelectChange(selectedItems: Array<FacetValueResult | { label: string }>) { if (!Array.isArray(selectedItems)) { selectedItems = [selectedItems]; } const searchTermItem = selectedItems.find(item => !this.isFacetValueItem(item)) as | { label: string } | undefined; const searchTerm = searchTermItem ? searchTermItem.label : ''; const facetValueIds = selectedItems.filter(this.isFacetValueItem).map(i => i.facetValue.id); if (searchTerm !== this.lastTerm) { this.searchTermChange.emit(searchTerm); this.lastTerm = searchTerm; } if (this.lastFacetValueIds.join(',') !== facetValueIds.join(',')) { this.facetValueChange.emit(facetValueIds); this.lastFacetValueIds = facetValueIds; } } addTagFn(item: any) { return { label: item }; } isSearchHeaderSelected(): boolean { return this.selectComponent.itemsList.markedIndex === -1; } private isFacetValueItem = (input: unknown): input is FacetValueResult => typeof input === 'object' && !!input && input.hasOwnProperty('facetValue'); }
import { ChangeDetectionStrategy, Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'; import { NgSelectComponent } from '@ng-select/ng-select'; import { concat, merge, Observable, of, Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, mapTo, switchMap, tap } from 'rxjs/operators'; import { ProductSelectorSearchQuery } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; /** * @description * A component for selecting product variants via an autocomplete-style select input. * * @example * ```HTML * <vdr-product-variant-selector * (productSelected)="selectResult($event)"></vdr-product-selector> * ``` * * @docsCategory components */ @Component({ selector: 'vdr-product-variant-selector', templateUrl: './product-variant-selector.component.html', styleUrls: ['./product-variant-selector.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ProductVariantSelectorComponent implements OnInit { searchInput$ = new Subject<string>(); searchLoading = false; searchResults$: Observable<ProductSelectorSearchQuery['search']['items']>; @Output() productSelected = new EventEmitter<ProductSelectorSearchQuery['search']['items'][number]>(); @ViewChild('autoComplete', { static: true }) private ngSelect: NgSelectComponent; constructor(private dataService: DataService) {} 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.product .productSelectorSearch(term, 10) .mapSingle(result => result.search.items); }), tap(() => (this.searchLoading = false)), ); const clear$ = this.productSelected.pipe(mapTo([])); this.searchResults$ = concat(of([]), merge(searchItems$, clear$)); } selectResult(product?: ProductSelectorSearchQuery['search']['items'][number]) { if (product) { this.productSelected.emit(product); this.ngSelect.clearModel(); } } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, TemplateRef, } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; import { debounceTime, throttleTime } from 'rxjs/operators'; @Component({ selector: 'vdr-radio-card-fieldset', template: `<fieldset><ng-content></ng-content></fieldset> `, styleUrls: ['radio-card-fieldset.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RadioCardFieldsetComponent<T = any> implements OnInit, OnChanges, OnDestroy { @Input() selectedItemId: string; @Input() idFn: (item: T) => string; @Output() selectItem = new EventEmitter<T>(); groupName = 'radio-group-' + Math.random().toString(36); selectedIdChange$ = new Subject<string>(); focussedId: string | undefined = undefined; private idChange$ = new Subject<T>(); private subscription: Subscription; constructor(private changeDetector: ChangeDetectorRef) {} ngOnInit() { this.subscription = this.idChange$ .pipe(throttleTime(200)) .subscribe(item => this.selectItem.emit(item)); } ngOnChanges(changes: SimpleChanges) { if ('selectedItemId' in changes) { this.selectedIdChange$.next(this.selectedItemId); } } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } isSelected(item: T): boolean { return this.selectedItemId === this.idFn(item); } isFocussed(item: T): boolean { return this.focussedId === this.idFn(item); } selectChanged(item: T) { this.idChange$.next(item); } setFocussedId(item: T | undefined) { this.focussedId = item && this.idFn(item); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, Input, OnDestroy, OnInit, TemplateRef, } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; import { RadioCardFieldsetComponent } from './radio-card-fieldset.component'; @Component({ selector: 'vdr-radio-card', templateUrl: './radio-card.component.html', styleUrls: ['./radio-card.component.scss'], exportAs: 'VdrRadioCard', changeDetection: ChangeDetectionStrategy.OnPush, }) export class RadioCardComponent<T = any> implements OnInit, OnDestroy { @Input() item: T; @ContentChild(TemplateRef) itemTemplate: TemplateRef<T>; constructor(private fieldset: RadioCardFieldsetComponent, private changeDetector: ChangeDetectorRef) {} private idChange$ = new Subject<T>(); private subscription: Subscription; name = this.fieldset.groupName; ngOnInit() { this.subscription = this.fieldset.selectedIdChange$.subscribe(id => { this.changeDetector.markForCheck(); }); } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } isSelected(item: T): boolean { return this.fieldset.isSelected(item); } isFocussed(item: T): boolean { return this.fieldset.isFocussed(item); } selectChanged(item: T) { this.fieldset.selectChanged(item); } setFocussedId(item: T | undefined) { this.fieldset.setFocussedId(item); } getItemId(item: T): string { return this.fieldset.idFn(item); } }
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, HostBinding, Input, OnDestroy, ViewChild, ViewContainerRef, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { ContextMenuService } from './prosemirror/context-menu/context-menu.service'; import { ProsemirrorService } from './prosemirror/prosemirror.service'; /** * @description * A rich text (HTML) editor based on Prosemirror (https://prosemirror.net/) * * @example * ```HTML * <vdr-rich-text-editor * [(ngModel)]="description" * label="Description" * ></vdr-rich-text-editor> * ``` * * @docsCategory components */ @Component({ selector: 'vdr-rich-text-editor', templateUrl: './rich-text-editor.component.html', styleUrls: ['./rich-text-editor.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: RichTextEditorComponent, multi: true, }, ProsemirrorService, ContextMenuService, ], }) export class RichTextEditorComponent implements ControlValueAccessor, AfterViewInit, OnDestroy { @Input() label: string; @Input() set readonly(value: any) { this._readonly = !!value; this.prosemirrorService.setEnabled(!this._readonly); } @HostBinding('class.readonly') _readonly = false; onChange: (val: any) => void; onTouch: () => void; private value: string; @ViewChild('editor', { static: true }) private editorEl: ElementRef<HTMLDivElement>; constructor( private changeDetector: ChangeDetectorRef, private prosemirrorService: ProsemirrorService, private viewContainerRef: ViewContainerRef, public contextMenuService: ContextMenuService, ) {} get menuElement(): HTMLDivElement | null { return this.viewContainerRef.element.nativeElement.querySelector('.ProseMirror-menubar'); } ngAfterViewInit() { this.prosemirrorService.createEditorView({ element: this.editorEl.nativeElement, onTextInput: content => { this.onChange(content); this.changeDetector.markForCheck(); }, isReadOnly: () => !this._readonly, }); if (this.value) { this.prosemirrorService.update(this.value); } } ngOnDestroy() { this.prosemirrorService.destroy(); } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouch = fn; } setDisabledState(isDisabled: boolean) { this.prosemirrorService.setEnabled(!isDisabled); } writeValue(value: any) { if (value !== this.value) { this.value = value; if (this.prosemirrorService) { this.prosemirrorService.update(value); } } } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; import { Dialog } from '../../../../providers/modal/modal.types'; export interface ExternalImageAttrs { src: string; title: string; alt: string; } @Component({ selector: 'vdr-external-image-dialog', templateUrl: './external-image-dialog.component.html', styleUrls: ['./external-image-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ExternalImageDialogComponent implements OnInit, Dialog<ExternalImageAttrs> { form: UntypedFormGroup; resolveWith: (result?: ExternalImageAttrs) => void; previewLoaded = false; existing?: ExternalImageAttrs; ngOnInit(): void { this.form = new UntypedFormGroup({ src: new UntypedFormControl(this.existing ? this.existing.src : '', Validators.required), title: new UntypedFormControl(this.existing ? this.existing.title : ''), alt: new UntypedFormControl(this.existing ? this.existing.alt : ''), }); } select() { this.resolveWith(this.form.value); } onImageLoad(event: Event) { this.previewLoaded = true; } onImageError(event: Event) { this.previewLoaded = false; } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { FormControl, UntypedFormGroup, Validators } from '@angular/forms'; import { Dialog } from '../../../../providers/modal/modal.types'; export interface LinkAttrs { href: string; title: string; target?: string; } @Component({ selector: 'vdr-link-dialog', templateUrl: './link-dialog.component.html', styleUrls: ['./link-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class LinkDialogComponent implements OnInit, Dialog<LinkAttrs> { form: UntypedFormGroup; resolveWith: (result?: LinkAttrs) => void; existing?: LinkAttrs; ngOnInit(): void { this.form = new UntypedFormGroup({ href: new FormControl(this.existing ? this.existing.href : '', Validators.required), title: new FormControl(this.existing ? this.existing.title : ''), target: new FormControl(this.existing ? this.existing.target : null), }); } remove() { this.resolveWith({ title: '', href: '', }); } select() { this.resolveWith(this.form.value); } }
import { Attrs, DOMParser, DOMSerializer, Node, NodeSpec, Mark, MarkSpec } from 'prosemirror-model'; import { NodeViewConstructor } from 'prosemirror-view'; export const iframeNode: NodeSpec = { group: 'block', attrs: { allow: {}, allowfullscreeen: {}, frameborder: {}, height: { default: undefined }, name: { default: '' }, referrerpolicy: {}, sandbox: { default: undefined }, src: {}, srcdoc: { default: undefined }, title: { default: undefined }, width: { default: undefined }, }, parseDOM: [ { tag: 'iframe', getAttrs: node => { if (node instanceof HTMLIFrameElement) { const attrs: Record<string, any> = { allow: node.allow, allowfullscreeen: node.allowFullscreen ?? true, frameborder: node.getAttribute('frameborder'), height: node.height, name: node.name, referrerpolicy: node.referrerPolicy, src: node.src, title: node.title ?? '', width: node.width, // Note: we do not allow the `srcdoc` attribute to be // set as it presents an XSS attack vector }; if (node.sandbox.length) { attrs.sandbox = node.sandbox; } return attrs; } return null; }, }, ], toDOM(node) { return ['iframe', { ...node.attrs, sandbox: 'allow-scripts allow-same-origin' }]; }, }; export const iframeNodeView: NodeViewConstructor = (node, view, getPos, decorations) => { const domSerializer = DOMSerializer.fromSchema(view.state.schema); const wrapper = document.createElement('div'); wrapper.classList.add('iframe-wrapper'); const iframe = domSerializer.serializeNode(node); wrapper.appendChild(iframe); return { dom: wrapper, }; }; export const linkMark: MarkSpec = { attrs: { href: {}, title: { default: null }, target: { default: null }, rel: { default: null }, download: { default: null }, type: { default: null }, }, inclusive: false, parseDOM: [ { tag: 'a[href]', getAttrs(dom: HTMLElement | string) { if (typeof dom !== 'string') { return { href: dom.getAttribute('href'), title: dom.getAttribute('title'), target: dom.getAttribute('target'), rel: dom.getAttribute('rel'), download: dom.getAttribute('download'), type: dom.getAttribute('type'), }; } else { return null; } }, }, ], toDOM(node) { const { href, title, target, rel, download, type } = node.attrs; const attrs = { href, title, rel, download, type }; if (target) { attrs['target'] = target; } return ['a', attrs, 0]; }, };
import { ellipsis, emDash, inputRules, smartQuotes, textblockTypeInputRule, wrappingInputRule, } from 'prosemirror-inputrules'; import { NodeType, Schema } from 'prosemirror-model'; import { Plugin } from 'prosemirror-state'; // : (NodeType) → InputRule // Given a blockquote node type, returns an input rule that turns `"> "` // at the start of a textblock into a blockquote. export function blockQuoteRule(nodeType) { return wrappingInputRule(/^\s*>\s$/, nodeType); } // : (NodeType) → InputRule // Given a list node type, returns an input rule that turns a number // followed by a dot at the start of a textblock into an ordered list. export function orderedListRule(nodeType) { return wrappingInputRule( /^(\d+)\.\s$/, nodeType, match => ({ order: +match[1] }), (match, node) => node.childCount + node.attrs.order === +match[1], ); } // : (NodeType) → InputRule // Given a list node type, returns an input rule that turns a bullet // (dash, plush, or asterisk) at the start of a textblock into a // bullet list. export function bulletListRule(nodeType) { return wrappingInputRule(/^\s*([-+*])\s$/, nodeType); } // : (NodeType) → InputRule // Given a code block node type, returns an input rule that turns a // textblock starting with three backticks into a code block. export function codeBlockRule(nodeType) { return textblockTypeInputRule(/^```$/, nodeType); } // : (NodeType, number) → InputRule // Given a node type and a maximum level, creates an input rule that // turns up to that number of `#` characters followed by a space at // the start of a textblock into a heading whose level corresponds to // the number of `#` signs. export function headingRule(nodeType, maxLevel) { return textblockTypeInputRule(new RegExp('^(#{1,' + maxLevel + '})\\s$'), nodeType, match => ({ level: match[1].length, })); } // : (Schema) → Plugin // A set of input rules for creating the basic block quotes, lists, // code blocks, and heading. export function buildInputRules(schema: Schema): Plugin { const rules = smartQuotes.concat(ellipsis, emDash); let type: NodeType; /* eslint-disable no-cond-assign */ if ((type = schema.nodes.blockquote)) { rules.push(blockQuoteRule(type)); } if ((type = schema.nodes.ordered_list)) { rules.push(orderedListRule(type)); } if ((type = schema.nodes.bullet_list)) { rules.push(bulletListRule(type)); } if ((type = schema.nodes.code_block)) { rules.push(codeBlockRule(type)); } if ((type = schema.nodes.heading)) { rules.push(headingRule(type, 6)); } return inputRules({ rules }); }
import { chainCommands, exitCode, joinDown, joinUp, lift, selectParentNode, setBlockType, toggleMark, wrapIn, } from 'prosemirror-commands'; import { redo, undo } from 'prosemirror-history'; import { undoInputRule } from 'prosemirror-inputrules'; import { MarkType, NodeType, Schema } from 'prosemirror-model'; import { liftListItem, sinkListItem, splitListItem, wrapInList } from 'prosemirror-schema-list'; import { Keymap } from './types'; const mac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false; // :: (Schema, ?Object) → Object // Inspect the given schema looking for marks and nodes from the // basic schema, and if found, add key bindings related to them. // This will add: // // * **Mod-b** for toggling [strong](#schema-basic.StrongMark) // * **Mod-i** for toggling [emphasis](#schema-basic.EmMark) // * **Mod-`** for toggling [code font](#schema-basic.CodeMark) // * **Ctrl-Shift-0** for making the current textblock a paragraph // * **Ctrl-Shift-1** to **Ctrl-Shift-Digit6** for making the current // textblock a heading of the corresponding level // * **Ctrl-Shift-Backslash** to make the current textblock a code block // * **Ctrl-Shift-8** to wrap the selection in an ordered list // * **Ctrl-Shift-9** to wrap the selection in a bullet list // * **Ctrl->** to wrap the selection in a block quote // * **Enter** to split a non-empty textblock in a list item while at // the same time splitting the list item // * **Mod-Enter** to insert a hard break // * **Mod-_** to insert a horizontal rule // * **Backspace** to undo an input rule // * **Alt-ArrowUp** to `joinUp` // * **Alt-ArrowDown** to `joinDown` // * **Mod-BracketLeft** to `lift` // * **Escape** to `selectParentNode` // // You can suppress or map these bindings by passing a `mapKeys` // argument, which maps key names (say `"Mod-B"` to either `false`, to // remove the binding, or a new key name string. export function buildKeymap(schema: Schema, mapKeys?: Keymap) { const keys = {}; let type: MarkType | NodeType; function bind(key: string, cmd: (...args: any[]) => boolean) { if (mapKeys) { const mapped = mapKeys[key]; if (mapped === false) { return; } if (mapped) { key = mapped; } } keys[key] = cmd; } bind('Mod-z', undo); bind('Shift-Mod-z', redo); bind('Backspace', undoInputRule); if (!mac) { bind('Mod-y', redo); } bind('Alt-ArrowUp', joinUp); bind('Alt-ArrowDown', joinDown); bind('Mod-BracketLeft', lift); bind('Escape', selectParentNode); /* eslint-disable no-cond-assign */ if ((type = schema.marks.strong)) { bind('Mod-b', toggleMark(type)); bind('Mod-B', toggleMark(type)); } if ((type = schema.marks.em)) { bind('Mod-i', toggleMark(type)); bind('Mod-I', toggleMark(type)); } if ((type = schema.marks.code)) { bind('Mod-`', toggleMark(type)); } if ((type = schema.nodes.bullet_list)) { bind('Shift-Ctrl-8', wrapInList(type)); } if ((type = schema.nodes.ordered_list)) { bind('Shift-Ctrl-9', wrapInList(type)); } if ((type = schema.nodes.blockquote)) { bind('Ctrl->', wrapIn(type)); } if ((type = schema.nodes.hard_break)) { const br = type; const cmd = chainCommands(exitCode, (state, dispatch) => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion dispatch!(state.tr.replaceSelectionWith(br.create()).scrollIntoView()); return true; }); bind('Mod-Enter', cmd); bind('Shift-Enter', cmd); if (mac) { bind('Ctrl-Enter', cmd); } } if ((type = schema.nodes.list_item)) { bind('Enter', splitListItem(type)); bind('Mod-[', liftListItem(type)); bind('Mod-]', sinkListItem(type)); } if ((type = schema.nodes.paragraph)) { bind('Shift-Ctrl-0', setBlockType(type)); } if ((type = schema.nodes.code_block)) { bind('Shift-Ctrl-\\', setBlockType(type)); } if ((type = schema.nodes.heading)) { for (let i = 1; i <= 6; i++) { bind('Shift-Ctrl-' + i, setBlockType(type, { level: i })); } } if ((type = schema.nodes.horizontal_rule)) { const hr = type; bind('Mod-_', (state, dispatch) => { dispatch(state.tr.replaceSelectionWith(hr.create()).scrollIntoView()); return true; }); } return keys; }
import { Injectable, Injector } from '@angular/core'; import { baseKeymap } from 'prosemirror-commands'; import { dropCursor } from 'prosemirror-dropcursor'; import { gapCursor } from 'prosemirror-gapcursor'; import { history } from 'prosemirror-history'; import { keymap } from 'prosemirror-keymap'; import { DOMParser, DOMSerializer, Schema } from 'prosemirror-model'; import { schema } from 'prosemirror-schema-basic'; import { addListNodes } from 'prosemirror-schema-list'; import { EditorState, Plugin } from 'prosemirror-state'; import { columnResizing, fixTables, tableEditing } from 'prosemirror-tables'; import { EditorView } from 'prosemirror-view'; import { Observable } from 'rxjs'; import { ModalService } from '../../../../providers/modal/modal.service'; import { ContextMenuService } from './context-menu/context-menu.service'; import { iframeNode, iframeNodeView, linkMark } from './custom-nodes'; import { buildInputRules } from './inputrules'; import { buildKeymap } from './keymap'; import { customMenuPlugin } from './menu/menu-plugin'; import { imageContextMenuPlugin } from './plugins/image-plugin'; import { linkSelectPlugin } from './plugins/link-select-plugin'; import { rawEditorPlugin } from './plugins/raw-editor-plugin'; import { getTableNodes, tableContextMenuPlugin } from './plugins/tables-plugin'; import { SetupOptions } from './types'; export interface CreateEditorViewOptions { onTextInput: (content: string) => void; element: HTMLElement; isReadOnly: () => boolean; } @Injectable() export class ProsemirrorService { editorView: EditorView; // Mix the nodes from prosemirror-schema-list into the basic schema to // create a schema with list support. private mySchema = new Schema({ nodes: addListNodes(schema.spec.nodes, 'paragraph block*', 'block') .append(getTableNodes() as any) .addToEnd('iframe', iframeNode), marks: schema.spec.marks.update('link', linkMark), }); private enabled = true; /** * This is a Document used for processing incoming text. It ensures that malicious HTML is not executed by the * actual document that is attached to the browser DOM, which could cause XSS attacks. */ private detachedDoc: Document | null = null; constructor(private injector: Injector, private contextMenuService: ContextMenuService) {} contextMenuItems$: Observable<string>; createEditorView(options: CreateEditorViewOptions) { this.editorView = new EditorView(options.element, { state: this.getStateFromText(''), dispatchTransaction: tr => { if (!this.enabled) { return; } this.editorView.updateState(this.editorView.state.apply(tr)); if (tr.docChanged) { const content = this.getTextFromState(this.editorView.state); options.onTextInput(content); } }, editable: () => options.isReadOnly(), handleDOMEvents: { focus: view => { this.contextMenuService.setVisibility(true); }, blur: view => { this.contextMenuService.setVisibility(false); }, }, nodeViews: { iframe: iframeNodeView, }, }); } update(text: string) { if (this.editorView) { const currentText = this.getTextFromState(this.editorView.state); if (text !== currentText) { let state = this.getStateFromText(text); if (document.body.contains(this.editorView.dom)) { const fix = fixTables(state); if (fix) { state = state.apply(fix.setMeta('addToHistory', false)); } this.editorView.updateState(state); } } } } destroy() { if (this.editorView) { this.editorView.destroy(); } } setEnabled(enabled: boolean) { if (this.editorView) { this.enabled = enabled; // Updating the state causes ProseMirror to check the // `editable()` function from the contructor config object // newly. this.editorView.updateState(this.editorView.state); } } private getStateFromText(text: string | null | undefined): EditorState { const doc = this.getDetachedDoc(); const div = doc.createElement('div'); div.innerHTML = text ?? ''; return EditorState.create({ doc: DOMParser.fromSchema(this.mySchema).parse(div), plugins: this.configurePlugins({ schema: this.mySchema, floatingMenu: false }), }); } private getTextFromState(state: EditorState): string { const doc = this.getDetachedDoc(); const div = doc.createElement('div'); const fragment = DOMSerializer.fromSchema(this.mySchema).serializeFragment(state.doc.content); div.appendChild(fragment); return div.innerHTML; } private configurePlugins(options: SetupOptions) { const plugins = [ buildInputRules(options.schema), keymap(buildKeymap(options.schema, options.mapKeys)), keymap(baseKeymap), dropCursor(), gapCursor(), linkSelectPlugin, columnResizing({}), tableEditing({ allowTableNodeSelection: true }), tableContextMenuPlugin(this.contextMenuService), imageContextMenuPlugin(this.contextMenuService, this.injector.get(ModalService)), rawEditorPlugin(this.contextMenuService, this.injector.get(ModalService)), customMenuPlugin({ floatingMenu: options.floatingMenu, injector: this.injector, schema: options.schema, }), ]; if (options.history !== false) { plugins.push(history()); } return plugins.concat( new Plugin({ props: { attributes: { class: 'vdr-prosemirror' }, }, }), ); } private getDetachedDoc() { if (!this.detachedDoc) { this.detachedDoc = document.implementation.createHTMLDocument(); } return this.detachedDoc; } }
import { MenuItem } from 'prosemirror-menu'; import { Schema } from 'prosemirror-model'; export interface SetupOptions { schema: Schema; mapKeys?: Keymap; menuBar?: boolean; history?: boolean; floatingMenu?: boolean; } export type Keymap = Record<string, string | false>;
import { MarkType, ResolvedPos } from 'prosemirror-model'; /** * Retrieve the start and end position of a mark * "Borrowed" from [tiptap](https://github.com/scrumpy/tiptap) */ export const getMarkRange = ( pmPosition: ResolvedPos | null = null, type: MarkType | null | undefined = null, ): { from: number; to: number } | false => { if (!pmPosition || !type) { return false; } const start = pmPosition.parent.childAfter(pmPosition.parentOffset); if (!start.node) { return false; } const mark = start.node.marks.find(({ type: markType }) => markType === type); if (!mark) { return false; } let startIndex = pmPosition.index(); let startPos = pmPosition.start() + start.offset; while (startIndex > 0 && mark.isInSet(pmPosition.parent.child(startIndex - 1).marks)) { startIndex -= 1; startPos -= pmPosition.parent.child(startIndex).nodeSize; } const endPos = startPos + start.node.nodeSize; return { from: startPos, to: endPos }; };
import { ConnectedPosition, Overlay, OverlayRef, PositionStrategy } from '@angular/cdk/overlay'; import { TemplatePortal } from '@angular/cdk/portal'; import { AfterViewInit, ChangeDetectionStrategy, Component, Input, OnDestroy, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { distinctUntilChanged } from 'rxjs/operators'; import { ContextMenuConfig, ContextMenuItem, ContextMenuService } from './context-menu.service'; type DropdownPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; @Component({ selector: 'vdr-context-menu', templateUrl: './context-menu.component.html', styleUrls: ['./context-menu.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ContextMenuComponent implements AfterViewInit, OnDestroy { @Input() editorMenuElement: HTMLElement | null | undefined; @ViewChild('contextMenu', { static: true }) private menuTemplate: TemplateRef<any>; menuConfig: ContextMenuConfig | undefined; hideTrigger$: Observable<boolean>; private triggerIsHidden = new BehaviorSubject<boolean>(false); private menuPortal: TemplatePortal<any>; private overlayRef: OverlayRef; private contextMenuSub: Subscription; private contentArea: HTMLDivElement | null; private hideTriggerHandler: (() => void) | undefined; constructor( private overlay: Overlay, private viewContainerRef: ViewContainerRef, public contextMenuService: ContextMenuService, ) {} onScroll = () => { if (this.overlayRef?.hasAttached()) { this.overlayRef.updatePosition(); } }; ngAfterViewInit() { this.contentArea = document.querySelector('.content-area'); this.menuPortal = new TemplatePortal(this.menuTemplate, this.viewContainerRef); this.hideTrigger$ = this.triggerIsHidden.asObservable().pipe(distinctUntilChanged()); this.contentArea?.addEventListener('scroll', this.onScroll, { passive: true }); this.contextMenuSub = this.contextMenuService.contextMenu$.subscribe(contextMenuConfig => { this.overlayRef?.dispose(); this.menuConfig = contextMenuConfig; if (contextMenuConfig) { this.overlayRef = this.overlay.create({ hasBackdrop: false, positionStrategy: this.getPositionStrategy(contextMenuConfig.element), maxHeight: '70vh', }); this.overlayRef.attach(this.menuPortal); this.triggerIsHidden.next(false); const triggerButton = this.overlayRef.hostElement.querySelector('.context-menu-trigger'); const editorMenu = this.editorMenuElement; if (triggerButton) { const overlapMarginPx = 5; this.hideTriggerHandler = () => { if (editorMenu && triggerButton) { if ( triggerButton.getBoundingClientRect().top + overlapMarginPx < editorMenu.getBoundingClientRect().bottom ) { this.triggerIsHidden.next(true); } else { this.triggerIsHidden.next(false); } } }; this.contentArea?.addEventListener('scroll', this.hideTriggerHandler, { passive: true }); requestAnimationFrame(() => this.hideTriggerHandler?.()); } } else { if (this.hideTriggerHandler) { this.contentArea?.removeEventListener('scroll', this.hideTriggerHandler); } } }); } triggerClick() { this.contextMenuService.setVisibility(true); } ngOnDestroy(): void { this.overlayRef?.dispose(); this.contextMenuSub?.unsubscribe(); this.contentArea?.removeEventListener('scroll', this.onScroll); if (this.hideTriggerHandler) { this.contentArea?.removeEventListener('scroll', this.hideTriggerHandler); } } clickItem(item: ContextMenuItem) { item.onClick(); } private getPositionStrategy(element: Element): 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['top-left']; return this.overlay .position() .flexibleConnectedTo(element) .withPositions([pos, this.invertPosition(pos)]) .withViewportMargin(0) .withLockedPosition(false) .withPush(false); } /** 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 { Injectable } from '@angular/core'; import { BehaviorSubject, combineLatest, interval, Observable, of, Subject } from 'rxjs'; import { bufferWhen, debounceTime, delayWhen, distinctUntilChanged, filter, map, skip, takeUntil, tap, } from 'rxjs/operators'; export interface ContextMenuConfig { ref: any; iconShape?: string; title: string; element: Element; coords: { left: number; right: number; top: number; bottom: number }; items: ContextMenuItem[]; } export interface ContextMenuItem { separator?: boolean; iconClass?: string; iconShape?: string; label: string; enabled: boolean; onClick: () => void; } @Injectable({ providedIn: 'root' }) export class ContextMenuService { contextMenu$: Observable<ContextMenuConfig | undefined>; private menuIsVisible$ = new BehaviorSubject<boolean>(false); private setContextMenuConfig$ = new Subject<ContextMenuConfig | undefined>(); constructor() { const source$ = this.setContextMenuConfig$.asObservable(); const groupedConfig$ = source$.pipe( bufferWhen(() => source$.pipe(debounceTime(50))), map(group => group.reduce((acc, cur) => { if (!acc) { return cur; } else { if (cur?.ref === acc.ref) { acc.items.push( // de-duplicate items ...(cur?.items.filter(i => !acc.items.find(ai => ai.label === i.label)) ?? []), ); } } return acc; }, undefined as ContextMenuConfig | undefined), ), ); const visible$ = this.menuIsVisible$.pipe(filter(val => val === true)); const isVisible$ = this.menuIsVisible$.pipe( delayWhen(value => (value ? of(value) : interval(250).pipe(takeUntil(visible$)))), distinctUntilChanged(), ); this.contextMenu$ = combineLatest(groupedConfig$, isVisible$).pipe( map(([config, isVisible]) => (isVisible ? config : undefined)), ); } setVisibility(isVisible: boolean) { this.menuIsVisible$.next(isVisible); } setContextMenu(config: ContextMenuConfig) { this.setContextMenuConfig$.next(config); } clearContextMenu() { this.setContextMenuConfig$.next(undefined); } }
import { toggleMark } from 'prosemirror-commands'; import { icons, MenuItem } from 'prosemirror-menu'; import { MarkType } from 'prosemirror-model'; import { EditorState, TextSelection } from 'prosemirror-state'; import { ModalService } from '../../../../../providers/modal/modal.service'; import { LinkAttrs, LinkDialogComponent } from '../../link-dialog/link-dialog.component'; import { markActive, renderClarityIcon } from './menu-common'; function selectionIsWithinLink(state: EditorState, anchor: number, head: number): boolean { const { doc } = state; const headLink = doc .resolve(head) .marks() .find(m => m.type.name === 'link'); const anchorLink = doc .resolve(anchor) .marks() .find(m => m.type.name === 'link'); if (headLink && anchorLink && headLink.eq(anchorLink)) { return true; } return false; } export function linkItem(linkMark: MarkType, modalService: ModalService) { return new MenuItem({ title: 'Add or remove link', render: renderClarityIcon({ shape: 'link', size: 22 }), class: '', css: '', active(state) { return markActive(state, linkMark); }, enable(state) { const { selection } = state; return !selection.empty || selectionIsWithinLink(state, selection.anchor, selection.head); }, run(state: EditorState, dispatch, view) { let attrs: LinkAttrs | undefined; const { selection, doc } = state; if ( selection instanceof TextSelection && selectionIsWithinLink(state, selection.anchor + 1, selection.head - 1) ) { const mark = doc .resolve(selection.anchor + 1) .marks() .find(m => m.type.name === 'link'); if (mark) { attrs = mark.attrs as LinkAttrs; } } modalService .fromComponent(LinkDialogComponent, { closable: true, locals: { existing: attrs, }, }) .subscribe(result => { let tr = state.tr; if (result) { const { $from, $to } = selection.ranges[0]; tr = tr.removeMark($from.pos, $to.pos, linkMark); if (result.href !== '') { tr = tr.addMark($from.pos, $to.pos, linkMark.create(result)); } } dispatch(tr.scrollIntoView()); view.focus(); }); return true; }, }); }
import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { NodeType } from 'prosemirror-model'; import { EditorState } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; export function markActive(state, type) { const { from, $from, to, empty } = state.selection; if (empty) { return type.isInSet(state.storedMarks || $from.marks()); } else { return state.doc.rangeHasMark(from, to, type); } } export function canInsert(state: EditorState, nodeType: NodeType): boolean { const $from = state.selection.$from; for (let d = $from.depth; d >= 0; d--) { const index = $from.index(d); if ($from.node(d).canReplaceWith(index, index, nodeType)) { return true; } } return false; } export interface ClarityIconOptions { shape: string; size?: number; label?: string; } export function renderClarityIcon(options: ClarityIconOptions): (view: EditorView) => HTMLElement { return (view: EditorView) => { const icon = document.createElement('clr-icon'); icon.setAttribute('shape', options.shape); icon.setAttribute('size', (options.size ?? IconSize.Small).toString()); const labelEl = document.createElement('span'); labelEl.textContent = options.label ?? ''; return wrapInMenuItemWithIcon(icon, options.label ? labelEl : undefined); }; } export function wrapInMenuItemWithIcon(...elements: Array<HTMLElement | undefined | null>) { const wrapperEl = document.createElement('span'); wrapperEl.classList.add('menu-item-with-icon'); wrapperEl.append(...elements.filter(notNullOrUndefined)); return wrapperEl; } export const IconSize = { Large: 22, Small: 16, };
import { Injector } from '@angular/core'; import { menuBar } from 'prosemirror-menu'; import { Schema } from 'prosemirror-model'; import { EditorState, Plugin } from 'prosemirror-state'; import { ModalService } from '../../../../../providers/modal/modal.service'; import { buildMenuItems } from './menu'; export interface CustomMenuPluginOptions { floatingMenu?: boolean; schema: Schema; injector: Injector; } export function customMenuPlugin(options: CustomMenuPluginOptions) { const modalService = options.injector.get(ModalService); const pmMenuBarPlugin = menuBar({ floating: options.floatingMenu !== false, content: buildMenuItems(options.schema, modalService).fullMenu, }); return pmMenuBarPlugin; }
import { toggleMark } from 'prosemirror-commands'; import { redo, undo } from 'prosemirror-history'; import { blockTypeItem, Dropdown, icons, joinUpItem, liftItem, MenuItem, selectParentNodeItem, wrapItem, } from 'prosemirror-menu'; import { MarkType, NodeType, Schema } from 'prosemirror-model'; import { wrapInList } from 'prosemirror-schema-list'; import { EditorState } from 'prosemirror-state'; import { ModalService } from '../../../../../providers/modal/modal.service'; import { insertImageItem } from '../plugins/image-plugin'; import { addTable } from '../plugins/tables-plugin'; import { linkItem } from './links'; import { canInsert, IconSize, markActive, renderClarityIcon, wrapInMenuItemWithIcon } from './menu-common'; import { SubMenuWithIcon } from './sub-menu-with-icon'; // Helpers to create specific types of items type CmdItemOptions = Record<string, any> & { iconShape?: string }; function cmdItem(cmd: (...args: any[]) => void, options: CmdItemOptions) { const passedOptions = { label: options.title, run: cmd, render: options.iconShape ? renderClarityIcon({ shape: options.iconShape, size: IconSize.Large }) : undefined, }; // eslint-disable-next-line guard-for-in for (const prop in options) { passedOptions[prop] = options[prop]; } if ((!options.enable || options.enable === true) && !options.select) { passedOptions[options.enable ? 'enable' : 'select'] = state => cmd(state); } return new MenuItem(passedOptions as any); } function markItem(markType, options: CmdItemOptions) { const passedOptions = { active(state) { return markActive(state, markType); }, enable: true, }; // eslint-disable-next-line guard-for-in for (const prop in options) { passedOptions[prop] = options[prop]; } return cmdItem(toggleMark(markType), passedOptions); } function wrapListItem(nodeType, options: CmdItemOptions) { return cmdItem(wrapInList(nodeType, options.attrs), options); } // :: (Schema) → Object // Given a schema, look for default mark and node types in it and // return an object with relevant menu items relating to those marks: // // **`toggleStrong`**`: MenuItem` // : A menu item to toggle the [strong mark](#schema-basic.StrongMark). // // **`toggleEm`**`: MenuItem` // : A menu item to toggle the [emphasis mark](#schema-basic.EmMark). // // **`toggleCode`**`: MenuItem` // : A menu item to toggle the [code font mark](#schema-basic.CodeMark). // // **`toggleLink`**`: MenuItem` // : A menu item to toggle the [link mark](#schema-basic.LinkMark). // // **`insertImage`**`: MenuItem` // : A menu item to insert an [image](#schema-basic.Image). // // **`wrapBulletList`**`: MenuItem` // : A menu item to wrap the selection in a [bullet list](#schema-list.BulletList). // // **`wrapOrderedList`**`: MenuItem` // : A menu item to wrap the selection in an [ordered list](#schema-list.OrderedList). // // **`wrapBlockQuote`**`: MenuItem` // : A menu item to wrap the selection in a [block quote](#schema-basic.BlockQuote). // // **`makeParagraph`**`: MenuItem` // : A menu item to set the current textblock to be a normal // [paragraph](#schema-basic.Paragraph). // // **`makeCodeBlock`**`: MenuItem` // : A menu item to set the current textblock to be a // [code block](#schema-basic.CodeBlock). // // **`makeHead[N]`**`: MenuItem` // : Where _N_ is 1 to 6. Menu items to set the current textblock to // be a [heading](#schema-basic.Heading) of level _N_. // // **`insertHorizontalRule`**`: MenuItem` // : A menu item to insert a horizontal rule. // // The return value also contains some prefabricated menu elements and // menus, that you can use instead of composing your own menu from // scratch: // // **`insertMenu`**`: Dropdown` // : A dropdown containing the `insertImage` and // `insertHorizontalRule` items. // // **`typeMenu`**`: Dropdown` // : A dropdown containing the items for making the current // textblock a paragraph, code block, or heading. // // **`fullMenu`**`: [[MenuElement]]` // : An array of arrays of menu elements for use as the full menu // for, for example the [menu bar](https://github.com/prosemirror/prosemirror-menu#user-content-menubar). export function buildMenuItems(schema: Schema, modalService: ModalService) { const r: Record<string, any> = {}; let type: MarkType | NodeType; /* eslint-disable no-cond-assign */ if ((type = schema.marks.strong)) { r.toggleStrong = markItem(type, { title: 'Toggle strong style', iconShape: 'bold', }); } if ((type = schema.marks.em)) { r.toggleEm = markItem(type, { title: 'Toggle emphasis', iconShape: 'italic', }); } if ((type = schema.marks.code)) { r.toggleCode = markItem(type, { title: 'Toggle code font', icon: icons.code }); } if ((type = schema.marks.link)) { r.toggleLink = linkItem(type, modalService); } if ((type = schema.nodes.image)) { r.insertImage = insertImageItem(type, modalService); } if ((type = schema.nodes.bullet_list)) { r.wrapBulletList = wrapListItem(type, { title: 'Wrap in bullet list', iconShape: 'bullet-list', }); } if ((type = schema.nodes.ordered_list)) { r.wrapOrderedList = wrapListItem(type, { title: 'Wrap in ordered list', iconShape: 'number-list', }); } if ((type = schema.nodes.blockquote)) { r.wrapBlockQuote = wrapItem(type, { title: 'Wrap in block quote', render: renderClarityIcon({ shape: 'block-quote', size: IconSize.Large }), }); } if ((type = schema.nodes.paragraph)) { r.makeParagraph = blockTypeItem(type, { title: 'Change to paragraph', render: renderClarityIcon({ shape: 'text', label: 'Plain' }), }); } if ((type = schema.nodes.code_block)) { r.makeCodeBlock = blockTypeItem(type, { title: 'Change to code block', render: renderClarityIcon({ shape: 'code', label: 'Code' }), }); } if ((type = schema.nodes.heading)) { for (let i = 1; i <= 10; i++) { r['makeHead' + i] = blockTypeItem(type, { title: 'Change to heading ' + i, label: 'Level ' + i, attrs: { level: i }, }); } } if ((type = schema.nodes.horizontal_rule)) { const hr = type; r.insertHorizontalRule = new MenuItem({ title: 'Insert horizontal rule', render: view => { const icon = document.createElement('div'); icon.classList.add('custom-icon', 'hr-icon'); const labelEl = document.createElement('span'); labelEl.textContent = 'Horizontal rule'; return wrapInMenuItemWithIcon(icon, labelEl); }, enable(state) { return canInsert(state, hr); }, run(state: EditorState, dispatch) { dispatch(state.tr.replaceSelectionWith(hr.create())); }, }); } const cut = <T>(arr: T[]): T[] => arr.filter(x => x); r.insertMenu = new Dropdown( cut([ r.insertImage, r.insertHorizontalRule, new MenuItem({ run: (state, dispatch) => { addTable(state, dispatch, { rowsCount: 2, colsCount: 2, withHeaderRow: true, cellContent: '', }); }, render: renderClarityIcon({ shape: 'table', label: 'Table' }), }), ]), { label: 'Insert' }, ); r.typeMenu = new Dropdown( cut([ r.makeParagraph, r.makeCodeBlock, r.makeHead1 && new SubMenuWithIcon( cut([r.makeHead1, r.makeHead2, r.makeHead3, r.makeHead4, r.makeHead5, r.makeHead6]), { label: 'Heading', icon: () => { const icon = document.createElement('div'); icon.textContent = 'H'; icon.classList.add('custom-icon', 'h-icon'); return icon; }, }, ), ]), { label: 'Type...' }, ); const inlineMenu = cut([r.toggleStrong, r.toggleEm, r.toggleLink]); r.inlineMenu = [inlineMenu]; r.blockMenu = [ cut([ r.wrapBulletList, r.wrapOrderedList, r.wrapBlockQuote, joinUpItem, liftItem, selectParentNodeItem, ]), ]; const undoRedo = [ new MenuItem({ title: 'Undo last change', run: undo, enable(state) { return undo(state); }, render: renderClarityIcon({ shape: 'undo', size: IconSize.Large }), }), new MenuItem({ title: 'Redo last undone change', run: redo, enable(state) { return redo(state); }, render: renderClarityIcon({ shape: 'redo', size: IconSize.Large }), }), ]; r.fullMenu = [inlineMenu].concat([[r.insertMenu, r.typeMenu]], [undoRedo], r.blockMenu); return r; }
import { DropdownSubmenu, MenuElement } from 'prosemirror-menu'; import { EditorState } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import { wrapInMenuItemWithIcon } from './menu-common'; export class SubMenuWithIcon extends DropdownSubmenu { private icon: HTMLElement; constructor( content: readonly MenuElement[] | MenuElement, options: { label?: string; icon: () => HTMLElement; }, ) { super(content, options); this.icon = options.icon(); } render(view: EditorView): { dom: HTMLElement; update: (state: EditorState) => boolean; } { const { dom, update } = super.render(view); return { dom: wrapInMenuItemWithIcon(this.icon, dom), update, }; } }
import { MenuItem } from 'prosemirror-menu'; import { Node, NodeType } from 'prosemirror-model'; import { EditorState, NodeSelection, Plugin, Transaction } from 'prosemirror-state'; import { addColumnAfter, addColumnBefore, addRowAfter, addRowBefore, deleteColumn, deleteRow, deleteTable, mergeCells, splitCell, toggleHeaderColumn, toggleHeaderRow, } from 'prosemirror-tables'; import { EditorView } from 'prosemirror-view'; import { ModalService } from '../../../../../providers/modal/modal.service'; import { ExternalImageAttrs, ExternalImageDialogComponent, } from '../../external-image-dialog/external-image-dialog.component'; import { RawHtmlDialogComponent } from '../../raw-html-dialog/raw-html-dialog.component'; import { ContextMenuItem, ContextMenuService } from '../context-menu/context-menu.service'; import { canInsert, renderClarityIcon } from '../menu/menu-common'; export function insertImageItem(nodeType: NodeType, modalService: ModalService) { return new MenuItem({ title: 'Insert image', label: 'Image', render: renderClarityIcon({ shape: 'image', label: 'Image' }), class: '', css: '', enable(state: EditorState) { return canInsert(state, nodeType); }, run(state: EditorState, _, view: EditorView) { let attrs: ExternalImageAttrs | undefined; if (state.selection instanceof NodeSelection && state.selection.node.type === nodeType) { attrs = state.selection.node.attrs as ExternalImageAttrs; } modalService .fromComponent(ExternalImageDialogComponent, { closable: true, locals: { existing: attrs, }, }) .subscribe(result => { if (result) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion view.dispatch(view.state.tr.replaceSelectionWith(nodeType.createAndFill(result)!)); } view.focus(); }); }, }); } export const imageContextMenuPlugin = (contextMenuService: ContextMenuService, modalService: ModalService) => new Plugin({ view: () => ({ update: view => { if (!view.hasFocus()) { return; } const { doc, selection } = view.state; let imageNode: Node | undefined; let imageNodePos = 0; doc.nodesBetween(selection.from, selection.to, (n, pos, parent) => { if (n.type.name === 'image') { imageNode = n; imageNodePos = pos; return false; } }); if (imageNode) { const node = view.nodeDOM(imageNodePos); if (node instanceof HTMLImageElement) { contextMenuService.setContextMenu({ ref: selection, title: 'Image', iconShape: 'image', element: node, coords: view.coordsAtPos(imageNodePos), items: [ { enabled: true, iconShape: 'image', label: 'Image properties', onClick: () => { contextMenuService.clearContextMenu(); modalService .fromComponent(ExternalImageDialogComponent, { closable: true, locals: { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion existing: imageNode!.attrs as ExternalImageAttrs, }, }) .subscribe(result => { if (result) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion view.dispatch( view.state.tr.replaceSelectionWith( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion imageNode!.type.createAndFill(result)!, ), ); } view.focus(); }); }, }, ], }); } } else { contextMenuService.clearContextMenu(); } }, }), });
import { Plugin, TextSelection } from 'prosemirror-state'; import { getMarkRange } from '../utils'; /** * Causes the entire link to be selected when clicked. */ export const linkSelectPlugin = new Plugin({ props: { handleClick(view, pos) { const { doc, tr, schema } = view.state; const range = getMarkRange(doc.resolve(pos), schema.marks.link); if (!range) { return false; } const $start = doc.resolve(range.from); const $end = doc.resolve(range.to); const transaction = tr.setSelection(new TextSelection($start, $end)); view.dispatch(transaction); return true; }, }, });
import { DOMParser, DOMSerializer, Node } from 'prosemirror-model'; import { Plugin } from 'prosemirror-state'; import { Protocol } from 'puppeteer'; import { ModalService } from '../../../../../providers/modal/modal.service'; import { RawHtmlDialogComponent } from '../../raw-html-dialog/raw-html-dialog.component'; import { ContextMenuService } from '../context-menu/context-menu.service'; /** * Implements editing of raw HTML for the selected node in the editor. */ export const rawEditorPlugin = (contextMenuService: ContextMenuService, modalService: ModalService) => new Plugin({ view: _view => { const domParser = DOMParser.fromSchema(_view.state.schema); const domSerializer = DOMSerializer.fromSchema(_view.state.schema); return { update: view => { if (!view.hasFocus()) { return; } let topLevelNode: Node | undefined; const { doc, selection } = view.state; let topLevelNodePos = 0; doc.nodesBetween(selection.from, selection.to, (n, pos, parent) => { if (parent === doc) { topLevelNode = n; topLevelNodePos = pos; return false; } }); if (topLevelNode) { const node = view.nodeDOM(topLevelNodePos); if (node instanceof HTMLElement) { contextMenuService.setContextMenu({ ref: selection, title: '', // iconShape: 'ellipsis-vertical', element: node, coords: view.coordsAtPos(topLevelNodePos), items: [ { enabled: true, iconShape: 'code', label: 'Edit HTML', onClick: () => { contextMenuService.clearContextMenu(); const element = domSerializer.serializeNode( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion topLevelNode!, ) as HTMLElement; modalService .fromComponent(RawHtmlDialogComponent, { size: 'xl', locals: { html: element.outerHTML, }, }) .subscribe(result => { if (result) { const domNode = htmlToDomNode( result, topLevelNode?.isLeaf ? undefined : node, ); if (domNode) { let tr = view.state.tr; const parsedNodeSlice = domParser.parse(domNode); try { tr = tr.replaceRangeWith( topLevelNodePos, topLevelNodePos + (topLevelNode?.nodeSize ?? 0), parsedNodeSlice, ); } catch (err: any) { // eslint-disable-next-line no-console console.error(err); } view.dispatch(tr); view.focus(); } } }); }, }, ], }); } } }, }; }, }); function htmlToDomNode(html: string, wrapInParent?: HTMLElement) { html = `${html.trim()}`; const template = document.createElement('template'); if (wrapInParent) { const parentClone = wrapInParent.cloneNode(false) as HTMLElement; parentClone.innerHTML = html; template.content.appendChild(parentClone); } else { const parent = document.createElement('p'); parent.innerHTML = html; template.content.appendChild(parent); } return template.content.firstChild; }
import { MenuElement, MenuItem } from 'prosemirror-menu'; import { Node, Schema } from 'prosemirror-model'; import { EditorState, Plugin, TextSelection, Transaction } from 'prosemirror-state'; import { addColumnAfter, addColumnBefore, addRowAfter, addRowBefore, deleteColumn, deleteRow, deleteTable, isInTable, mergeCells, splitCell, tableNodes, tableNodeTypes, toggleHeaderCell, toggleHeaderColumn, toggleHeaderRow, } from 'prosemirror-tables'; import { Decoration, DecorationSet } from 'prosemirror-view'; import { ContextMenuItem, ContextMenuService } from '../context-menu/context-menu.service'; import { buildMenuItems } from '../menu/menu'; import { renderClarityIcon } from '../menu/menu-common'; export const tableContextMenuPlugin = (contextMenuService: ContextMenuService) => new Plugin({ view: () => ({ update: view => { if (!view.hasFocus()) { return; } const { doc, selection } = view.state; let tableNode: Node | undefined; let tableNodePos = 0; doc.nodesBetween(selection.from, selection.to, (n, pos, parent) => { if (n.type.name === 'table') { tableNode = n; tableNodePos = pos; return false; } }); if (tableNode) { const node = view.nodeDOM(tableNodePos); if (node instanceof Element) { function createMenuItem( label: string, commandFn: (state: EditorState, dispatch?: (tr: Transaction) => void) => boolean, iconClass?: string, ): ContextMenuItem { const enabled = commandFn(view.state); return { label, enabled, iconClass, onClick: () => { contextMenuService.clearContextMenu(); view.focus(); commandFn(view.state, view.dispatch); }, }; } const separator: ContextMenuItem = { label: '', separator: true, enabled: true, onClick: () => { /**/ }, }; contextMenuService.setContextMenu({ ref: selection, title: 'Table', iconShape: 'table', element: node, coords: view.coordsAtPos(tableNodePos), items: [ createMenuItem('Insert column before', addColumnBefore, 'add-column'), createMenuItem('Insert column after', addColumnAfter, 'add-column'), createMenuItem('Insert row before', addRowBefore, 'add-row'), createMenuItem('Insert row after', addRowAfter, 'add-row'), createMenuItem('Merge cells', mergeCells), createMenuItem('Split cell', splitCell), separator, createMenuItem('Toggle header column', toggleHeaderColumn), createMenuItem('Toggle header row', toggleHeaderRow), separator, createMenuItem('Delete column', deleteColumn), createMenuItem('Delete row', deleteRow), createMenuItem('Delete table', deleteTable), ], }); } } else { contextMenuService.clearContextMenu(); } }, }), }); export function getTableNodes() { return tableNodes({ tableGroup: 'block', cellContent: 'block+', cellAttributes: { background: { default: null, getFromDOM(dom) { return (dom as HTMLElement).style.backgroundColor || null; }, setDOMAttr(value, attrs) { if (value) { attrs.style = (attrs.style || '') + `background-color: ${value};`; } }, }, }, }); } export function getTableMenu(schema: Schema) { function item( label: string, cmd: (state: EditorState, dispatch?: (tr: Transaction) => void) => boolean, iconShape?: string, ) { return new MenuItem({ label, select: cmd, run: cmd, render: iconShape ? renderClarityIcon({ shape: iconShape, label }) : undefined, }); } function separator(): MenuElement { return new MenuItem({ select: state => isInTable(state), run: state => { /**/ }, render: view => { const el = document.createElement('div'); el.classList.add('menu-separator'); return el; }, }); } return [ item('Insert column before', addColumnBefore), item('Insert column after', addColumnAfter), item('Insert row before', addRowBefore), item('Insert row after', addRowAfter), item('Merge cells', mergeCells), item('Split cell', splitCell), separator(), item('Toggle header column', toggleHeaderColumn), item('Toggle header row', toggleHeaderRow), item('Toggle header cells', toggleHeaderCell), separator(), item('Delete column', deleteColumn), item('Delete row', deleteRow), item('Delete table', deleteTable), ]; } export function addTable(state, dispatch, { rowsCount, colsCount, withHeaderRow, cellContent }) { const offset = state.tr.selection.anchor + 1; const nodes = createTable(state, rowsCount, colsCount, withHeaderRow, cellContent); const tr = state.tr.replaceSelectionWith(nodes).scrollIntoView(); const resolvedPos = tr.doc.resolve(offset); tr.setSelection(TextSelection.near(resolvedPos)); dispatch(tr); } function createTable(state, rowsCount, colsCount, withHeaderRow, cellContent) { const types = tableNodeTypes(state.schema); const headerCells: Node[] = []; const cells: Node[] = []; const createCell = (cellType, _cellContent) => _cellContent ? cellType.createChecked(null, _cellContent) : cellType.createAndFill(); for (let index = 0; index < colsCount; index += 1) { const cell = createCell(types.cell, cellContent); if (cell) { cells.push(cell); } if (withHeaderRow) { const headerCell = createCell(types.header_cell, cellContent); if (headerCell) { headerCells.push(headerCell); } } } const rows: Node[] = []; for (let index = 0; index < rowsCount; index += 1) { rows.push(types.row.createChecked(null, withHeaderRow && index === 0 ? headerCells : cells)); } return types.table.createChecked(null, rows); }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { ConfigArgDefinition } from '../../../../common/generated-types'; import { Dialog } from '../../../../providers/modal/modal.types'; import { HtmlEditorFormInputComponent } from '../../../dynamic-form-inputs/code-editor-form-input/html-editor-form-input.component'; @Component({ selector: 'vdr-raw-html-dialog', templateUrl: './raw-html-dialog.component.html', styleUrls: ['./raw-html-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RawHtmlDialogComponent implements OnInit, Dialog<string> { html: string; formControl = new UntypedFormControl(); config: ConfigArgDefinition = { name: '', type: '', list: false, required: true, ui: { component: HtmlEditorFormInputComponent.id }, }; resolveWith: (html: string | undefined) => void; ngOnInit(): void { this.formControl.setValue(this.process(this.html)); } process(str: string) { const div = document.createElement('div'); div.innerHTML = str.trim(); return this.format(div, 0).innerHTML.trim(); } /** * Taken from https://stackoverflow.com/a/26361620/772859 */ format(node: Element, level = 0) { const indentBefore = new Array(level++ + 1).join('\t'); const indentAfter = new Array(level - 1).join('\t'); let textNode: Text; // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < node.children.length; i++) { textNode = document.createTextNode('\n' + indentBefore); node.insertBefore(textNode, node.children[i]); this.format(node.children[i], level); if (node.lastElementChild === node.children[i]) { textNode = document.createTextNode('\n' + indentAfter); node.appendChild(textNode); } } return node; } cancel() { this.resolveWith(undefined); } select() { this.resolveWith(this.formControl.value); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; /** * A simple, stateless toggle button for indicating selection. */ @Component({ selector: 'vdr-select-toggle', templateUrl: './select-toggle.component.html', styleUrls: ['./select-toggle.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SelectToggleComponent { @Input() size: 'small' | 'large' = 'large'; @Input() selected = false; @Input() hiddenWhenOff = false; @Input() disabled = false; @Input() label: string | undefined; @Output() selectedChange = new EventEmitter<boolean>(); }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { Dialog, DialogButtonConfig } from '../../../providers/modal/modal.types'; /** * Used by ModalService.dialog() to host a generic configurable modal dialog. */ @Component({ selector: 'vdr-simple-dialog', templateUrl: './simple-dialog.component.html', styleUrls: ['./simple-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SimpleDialogComponent implements Dialog<any> { resolveWith: (result?: any) => void; title = ''; body = ''; translationVars = {}; buttons: Array<DialogButtonConfig<any>> = []; }
import { AfterContentInit, AfterViewInit, ChangeDetectionStrategy, Component, ContentChild, ElementRef, EventEmitter, Input, Output, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import { fromEvent, merge, Observable, switchMap } from 'rxjs'; import { map, mapTo, startWith, takeUntil } from 'rxjs/operators'; import { SplitViewLeftDirective, SplitViewRightDirective } from './split-view.directive'; @Component({ selector: 'vdr-split-view', templateUrl: './split-view.component.html', styleUrls: ['./split-view.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SplitViewComponent implements AfterContentInit, AfterViewInit { @Input() rightPanelOpen = false; @Output() closeClicked = new EventEmitter<void>(); @ContentChild(SplitViewLeftDirective, { static: true, read: TemplateRef }) leftTemplate: TemplateRef<any>; @ContentChild(SplitViewRightDirective, { static: true, read: SplitViewRightDirective }) rightTemplate: SplitViewRightDirective; @ViewChild('resizeHandle', { static: true, read: ElementRef }) resizeHandle: ElementRef<HTMLDivElement>; protected rightPanelWidth$: Observable<number>; protected leftPanelWidth$: Observable<SafeStyle>; protected resizing$: Observable<boolean>; constructor(private viewContainerRef: ViewContainerRef, private domSanitizer: DomSanitizer) {} ngAfterContentInit(): void { if (!this.leftTemplate) { throw new Error('A <vdr-split-view-left> must be provided'); } if (!this.rightTemplate) { throw new Error('A <vdr-split-view-right> must be provided'); } } ngAfterViewInit() { const hostElement = this.viewContainerRef.element.nativeElement; const hostElementWidth = hostElement.getBoundingClientRect()?.width; const mouseDown$ = merge( fromEvent<MouseEvent>(this.resizeHandle.nativeElement, 'mousedown'), fromEvent<MouseEvent>(this.resizeHandle.nativeElement, 'touchstart'), ); const mouseMove$ = merge( fromEvent<MouseEvent>(document, 'mousemove'), fromEvent<TouchEvent>(document, 'touchmove'), ); const mouseUp$ = merge( fromEvent<MouseEvent>(document, 'mouseup'), fromEvent<TouchEvent>(document, 'touchend'), ); // update right panel width when resize handle is dragged this.rightPanelWidth$ = mouseDown$.pipe( switchMap(() => mouseMove$.pipe(takeUntil(mouseUp$))), map(event => { const clientX = event instanceof MouseEvent ? event.clientX : event.touches[0].clientX; const width = hostElement.getBoundingClientRect().right - clientX; return Math.max(100, Math.min(width, hostElementWidth - 100)); }), startWith(hostElementWidth / 2), ); this.leftPanelWidth$ = this.rightPanelWidth$.pipe( map(width => `calc(var(--surface-width) - ${width}px)`), ); this.resizing$ = merge(mouseDown$.pipe(mapTo(true)), mouseUp$.pipe(mapTo(false))); } close() { this.closeClicked.emit(); } }
import { Directive, Input, TemplateRef } from '@angular/core'; @Directive({ selector: '[vdrSplitViewLeft]', }) export class SplitViewLeftDirective {} @Directive({ selector: '[vdrSplitViewRight]', }) export class SplitViewRightDirective { constructor(public template: TemplateRef<any>) {} @Input() splitViewTitle?: string; }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-status-badge', templateUrl: './status-badge.component.html', styleUrls: ['./status-badge.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class StatusBadgeComponent { @Input() type: 'info' | 'success' | 'warning' | 'error' = 'info'; }
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { AbstractControl } from '@angular/forms'; import { DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { CustomFieldConfig } from '../../../common/generated-types'; import { CustomFieldEntityName } from '../../../providers/custom-field-component/custom-field-component.service'; export type GroupedCustomFields = Array<{ tabName: string; customFields: CustomFieldConfig[] }>; @Component({ selector: 'vdr-tabbed-custom-fields', templateUrl: './tabbed-custom-fields.component.html', styleUrls: ['./tabbed-custom-fields.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TabbedCustomFieldsComponent implements OnInit { @Input() entityName: CustomFieldEntityName; @Input() customFields: CustomFieldConfig[]; @Input() customFieldsFormGroup: AbstractControl; @Input() readonly = false; @Input() compact = false; @Input() showLabel = true; readonly defaultTabName = '__default_tab__'; tabbedCustomFields: GroupedCustomFields; ngOnInit(): void { this.tabbedCustomFields = this.groupByTabs(this.customFields); } customFieldIsSet(name: string): boolean { return !!this.customFieldsFormGroup?.get(name); } componentShouldSpanGrid(customField: CustomFieldConfig): boolean { const smallComponents: DefaultFormComponentId[] = [ 'boolean-form-input', 'currency-form-input', 'date-form-input', 'number-form-input', 'password-form-input', 'select-form-input', 'text-form-input', 'relation-form-input', ]; return ( customField.type === 'text' || customField.type === 'localeText' || customField.type === 'relation' || (customField.ui?.component && !smallComponents.includes(customField.ui?.component)) ); } private groupByTabs(customFieldConfigs: CustomFieldConfig[]): GroupedCustomFields { const tabMap = new Map<string, CustomFieldConfig[]>(); for (const field of customFieldConfigs) { const tabName = field.ui?.tab ?? this.defaultTabName; if (tabMap.has(tabName)) { tabMap.get(tabName)?.push(field); } else { tabMap.set(tabName, [field]); } } return Array.from(tabMap.entries()) .sort((a, b) => (a[0] === this.defaultTabName ? -1 : 1)) .map(([tabName, customFields]) => ({ tabName, customFields })); } }
import { Component, Input, OnInit } from '@angular/core'; /** * A button link to be used as actions in rows of a table. */ @Component({ selector: 'vdr-table-row-action', templateUrl: './table-row-action.component.html', styleUrls: ['./table-row-action.component.scss'], }) export class TableRowActionComponent { @Input() linkTo: any[]; @Input() label: string; @Input() iconShape: string; @Input() disabled = false; }
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { Observable } from 'rxjs'; import { DataService } from '../../../data/providers/data.service'; @Component({ selector: 'vdr-tag-selector', templateUrl: './tag-selector.component.html', styleUrls: ['./tag-selector.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: TagSelectorComponent, multi: true, }, ], }) export class TagSelectorComponent implements OnInit, ControlValueAccessor { @Input() placeholder: string | undefined; allTags$: Observable<string[]>; onChange: (val: any) => void; onTouch: () => void; _value: string[]; disabled: boolean; constructor(private dataService: DataService) {} ngOnInit(): void { this.allTags$ = this.dataService.product .getTagList() .mapStream(data => data.tags.items.map(i => i.value)); } addTagFn(val: string) { return val; } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouch = fn; } setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } writeValue(obj: unknown): void { if (Array.isArray(obj)) { this._value = obj; } } valueChanged(event: string[]) { this.onChange(event); } }
import { ChangeDetectionStrategy, Component, EventEmitter, HostBinding, Input, OnInit, Output, } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; export type TimelineDisplayType = 'success' | 'error' | 'warning' | 'default' | 'muted'; @Component({ selector: 'vdr-timeline-entry', templateUrl: './timeline-entry.component.html', styleUrls: ['./timeline-entry.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TimelineEntryComponent { @Input() displayType: TimelineDisplayType; @Input() createdAt: string; @Input() name: string; @Input() featured: boolean; @Input() iconShape?: string | [string, string]; @Input() isLast?: boolean; @HostBinding('class.collapsed') @Input() collapsed = false; @Output() expandClick = new EventEmitter(); get timelineTitle(): string { return this.collapsed ? _('common.expand-entries') : _('common.collapse-entries'); } getIconShape() { if (this.iconShape) { return typeof this.iconShape === 'string' ? this.iconShape : this.iconShape[0]; } } getIconClass() { if (this.iconShape) { return typeof this.iconShape === 'string' ? '' : this.iconShape[1]; } } }
import { ChangeDetectionStrategy, Component, HostBinding, Input } from '@angular/core'; @Component({ selector: 'vdr-title-input', templateUrl: './title-input.component.html', styleUrls: ['./title-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TitleInputComponent { @HostBinding('class.readonly') @Input() readonly = false; }
import { ChangeDetectionStrategy, Component, ElementRef, HostBinding, Input, isDevMode, OnInit, ViewChild, } from '@angular/core'; import { CodeJar } from 'codejar'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { UIExtensionLocationId } from '../../../common/component-registry-types'; import { DataService } from '../../../data/providers/data.service'; import { DropdownComponent } from '../dropdown/dropdown.component'; type UiExtensionType = 'actionBar' | 'actionBarDropdown' | 'navMenu' | 'detailComponent' | 'dataTable'; @Component({ selector: 'vdr-ui-extension-point', templateUrl: './ui-extension-point.component.html', styleUrls: ['./ui-extension-point.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class UiExtensionPointComponent implements OnInit { @Input() locationId: UIExtensionLocationId; @Input() metadata?: string; @Input() topPx: number; @Input() leftPx: number; @HostBinding('style.display') @Input() display: 'block' | 'inline-block' = 'inline-block'; @Input() api: UiExtensionType; @ViewChild('editor') private editorElementRef: ElementRef<HTMLDivElement>; @ViewChild('dropdownComponent') private dropdownComponent: DropdownComponent; display$: Observable<boolean>; jar: CodeJar; readonly isDevMode = isDevMode(); constructor(private dataService: DataService) {} getCodeTemplate(api: UiExtensionType): string { return codeTemplates[api](this.locationId, this.metadata).trim(); } ngOnInit(): void { this.display$ = this.dataService.client .uiState() .mapStream(({ uiState }) => uiState.displayUiExtensionPoints) .pipe( tap(display => { if (display) { setTimeout(() => { const highlight = (editor: HTMLElement) => { const code = editor.textContent ?? ''; editor.innerHTML = highlightTsCode(this.getCodeTemplate(this.api)); }; this.editorElementRef.nativeElement.contentEditable = 'false'; this.jar = CodeJar(this.editorElementRef.nativeElement, highlight); this.jar.updateCode(this.getCodeTemplate(this.api)); }); } }), ); } } function highlightTsCode(tsCode: string) { tsCode = tsCode.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); return tsCode.replace( // eslint-disable-next-line max-len /\b(abstract|any|as|boolean|break|case|catch|class|const|continue|default|do|else|enum|export|extends|false|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|never|new|null|number|object|of|private|protected|public|readonly|require|return|set|static|string|super|switch|symbol|this|throw|true|try|type|typeof|undefined|var|void|while|with|yield)\b|\/\/.*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^\\"])*"|'[^']*'/g, (match, ...args) => { if (/^"/.test(match) || /^'/.test(match)) { return '<span class="ts-string">' + match + '</span>'; } else if (/\/\/.*|\/\*[\s\S]*?\*\//.test(match)) { return '<span class="ts-comment">' + match + '</span>'; } else if ( // eslint-disable-next-line max-len /\b(abstract|any|as|boolean|break|case|catch|class|const|continue|default|do|else|enum|export|extends|false|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|never|new|null|number|object|of|private|protected|public|readonly|require|return|set|static|string|super|switch|symbol|this|throw|true|try|type|typeof|undefined|var|void|while|with|yield)\b/.test( match, ) ) { return '<span class="ts-keyword">' + match + '</span>'; } else { return '<span class="ts-default">' + match + '</span>'; } }, ); } const codeTemplates: Record< UiExtensionType, (locationId: UIExtensionLocationId, metadata?: string) => string > = { actionBar: locationId => ` import { addActionBarItem } from '@vendure/admin-ui/core'; export default [ addActionBarItem({ id: 'my-button', label: 'My Action', locationId: '${locationId}', }), ];`, actionBarDropdown: locationId => ` import { addActionBarDropdownMenuItem } from '@vendure/admin-ui/core'; export default [ addActionBarDropdownMenuItem({ id: 'my-dropdown-item', label: 'My Action', locationId: '${locationId}', }), ];`, navMenu: locationId => ` import { addNavMenuSection } from '@vendure/admin-ui/core'; export default [ addNavMenuSection({ id: 'my-menu-item', label: 'My Menu Item', items: [{ // ... }], }, '${locationId}', ), ];`, detailComponent: locationId => ` import { registerCustomDetailComponent } from '@vendure/admin-ui/core'; export default [ registerCustomDetailComponent({ locationId: '${locationId}', component: MyCustomComponent, }), ];`, dataTable: (locationId, metadata) => ` import { registerDataTableComponent } from '@vendure/admin-ui/core'; export default [ registerDataTableComponent({ tableId: '${locationId}', columnId: '${metadata}', component: MyCustomComponent, }), ];`, };
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { NgSelectComponent } from '@ng-select/ng-select'; import { gql } from 'apollo-angular'; import { Subject } from 'rxjs'; import { ItemOf } from '../../../common/base-list.component'; import { GetZoneSelectorListDocument, GetZoneSelectorListQuery } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; export const GET_ZONE_SELECTOR_LIST = gql` query GetZoneSelectorList($options: ZoneListOptions) { zones(options: $options) { items { id createdAt updatedAt name } totalItems } } `; type Zone = ItemOf<GetZoneSelectorListQuery, 'zones'>; /** * @description * A form control for selecting zones. * * @docsCategory components */ @Component({ selector: 'vdr-zone-selector', templateUrl: './zone-selector.component.html', styleUrls: ['./zone-selector.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: ZoneSelectorComponent, multi: true, }, ], }) export class ZoneSelectorComponent implements ControlValueAccessor { @Output() selectedValuesChange = new EventEmitter<Zone>(); @Input() readonly = false; @Input() transformControlValueAccessorValue: (value: Zone | undefined) => any = value => value?.id; selectedId$ = new Subject<string>(); @ViewChild(NgSelectComponent) private ngSelect: NgSelectComponent; onChangeFn: (val: any) => void; onTouchFn: () => void; disabled = false; value: string | Zone; zones$ = this.dataService .query(GetZoneSelectorListDocument, { options: { take: 999 } }, 'cache-first') .mapSingle(result => result.zones.items); constructor(private dataService: DataService, private changeDetectorRef: ChangeDetectorRef) {} onChange(selected: Zone) { if (this.readonly) { return; } 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 | Zone | null): void { if (typeof obj === 'string' && obj.length > 0) { this.value = obj; } } }
import { Directive, Input, Optional } from '@angular/core'; import { FormControl, FormControlDirective, FormControlName } from '@angular/forms'; /** * Allows declarative binding to the "disabled" property of a reactive form * control. */ @Directive({ selector: '[vdrDisabled]', }) export class DisabledDirective { @Input('vdrDisabled') set disabled(val: boolean) { const formControl = this.formControlName?.control ?? this.formControl?.form; if (!formControl) { return; } if (!!val === false) { formControl.enable({ emitEvent: false }); } else { formControl.disable({ emitEvent: false }); } } constructor( @Optional() private formControlName: FormControlName, @Optional() private formControl: FormControlDirective, ) {} }
import { ChangeDetectorRef, Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { tap } from 'rxjs/operators'; import { UserStatus } from '../../common/generated-types'; import { DataService } from '../../data/providers/data.service'; import { IfDirectiveBase } from './if-directive-base'; @Directive({ selector: '[vdrIfDefaultChannelActive]', }) export class IfDefaultChannelActiveDirective extends IfDirectiveBase<[]> { constructor( _viewContainer: ViewContainerRef, templateRef: TemplateRef<any>, private dataService: DataService, private changeDetectorRef: ChangeDetectorRef, ) { super(_viewContainer, templateRef, () => this.dataService.client .userStatus() .mapStream(({ userStatus }) => this.defaultChannelIsActive(userStatus)) .pipe(tap(() => this.changeDetectorRef.markForCheck())), ); } /** * A template to show if the current user does not have the specified permission. */ @Input() set vdrIfMultichannelElse(templateRef: TemplateRef<any> | null) { this.setElseTemplate(templateRef); } private defaultChannelIsActive(userStatus: UserStatus): boolean { const defaultChannel = userStatus.channels.find(c => c.code === DEFAULT_CHANNEL_CODE); return !!(defaultChannel && userStatus.activeChannelId === defaultChannel.id); } }
import { Directive, EmbeddedViewRef, OnDestroy, OnInit, TemplateRef, ViewContainerRef } from '@angular/core'; import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { switchMap } from 'rxjs/operators'; /** * A base class for implementing custom *ngIf-style structural directives based on custom conditions. * * @dynamic */ @Directive() export class IfDirectiveBase<Args extends any[]> implements OnInit, OnDestroy { protected updateArgs$ = new BehaviorSubject<Args>([] as any); private readonly _thenTemplateRef: TemplateRef<any> | null = null; private _elseTemplateRef: TemplateRef<any> | null = null; private _thenViewRef: EmbeddedViewRef<any> | null = null; private _elseViewRef: EmbeddedViewRef<any> | null = null; private subscription: Subscription; constructor( private _viewContainer: ViewContainerRef, templateRef: TemplateRef<any>, private updateViewFn: (...args: Args) => Observable<boolean>, ) { this._thenTemplateRef = templateRef; } ngOnInit(): void { this.subscription = this.updateArgs$ .pipe(switchMap(args => this.updateViewFn(...args))) .subscribe(result => { if (result) { this.showThen(); } else { this.showElse(); } }); } ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } protected setElseTemplate(templateRef: TemplateRef<any> | null) { this.assertTemplate('vdrIfPermissionsElse', templateRef); this._elseTemplateRef = templateRef; this._elseViewRef = null; // clear previous view if any. } private showThen() { if (!this._thenViewRef) { this._viewContainer.clear(); this._elseViewRef = null; if (this._thenTemplateRef) { this._thenViewRef = this._viewContainer.createEmbeddedView(this._thenTemplateRef); } } } private showElse() { if (!this._elseViewRef) { this._viewContainer.clear(); this._thenViewRef = null; if (this._elseTemplateRef) { this._elseViewRef = this._viewContainer.createEmbeddedView(this._elseTemplateRef); } } } private assertTemplate(property: string, templateRef: TemplateRef<any> | null): void { const isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView); if (!isTemplateRefOrNull) { throw new Error(`${property} must be a TemplateRef, but received '${templateRef}'.`); } } }
/* eslint-disable @angular-eslint/component-class-suffix */ import { Component, Input } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BehaviorSubject } from 'rxjs'; import { map } from 'rxjs/operators'; import { DataService } from '../../data/providers/data.service'; import { IfMultichannelDirective } from './if-multichannel.directive'; describe('vdrIfMultichannel directive', () => { describe('simple usage', () => { let fixture: ComponentFixture<TestComponentSimple>; beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [TestComponentSimple, IfMultichannelDirective], providers: [{ provide: DataService, useClass: MockDataService }], }).createComponent(TestComponentSimple); fixture.detectChanges(); // initial binding }); it('is multichannel', () => { (fixture.componentInstance.dataService as unknown as MockDataService).setChannels([1, 2]); fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).not.toBeNull(); }); it('not multichannel', () => { (fixture.componentInstance.dataService as unknown as MockDataService).setChannels([1]); fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).toBeNull(); }); }); describe('if-else usage', () => { let fixture: ComponentFixture<TestComponentIfElse>; beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [TestComponentIfElse, IfMultichannelDirective], providers: [{ provide: DataService, useClass: MockDataService }], }).createComponent(TestComponentIfElse); fixture.detectChanges(); // initial binding }); it('is multichannel', () => { (fixture.componentInstance.dataService as unknown as MockDataService).setChannels([1, 2]); fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).not.toBeNull(); const elseEl = fixture.nativeElement.querySelector('.else'); expect(elseEl).toBeNull(); }); it('not multichannel', () => { (fixture.componentInstance.dataService as unknown as MockDataService).setChannels([1]); fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).toBeNull(); const elseEl = fixture.nativeElement.querySelector('.else'); expect(elseEl).not.toBeNull(); }); }); }); @Component({ template: ` <div *vdrIfMultichannel> <span class="then"></span> </div> `, }) export class TestComponentSimple { constructor(public dataService: DataService) {} @Input() permissionToTest = ''; } @Component({ template: ` <ng-template vdrIfMultichannel [vdrIfMultichannelElse]="not"> <span class="then"></span> </ng-template> <ng-template #not><span class="else"></span></ng-template> `, }) export class TestComponentIfElse { constructor(public dataService: DataService) {} @Input() permissionToTest = ''; } class MockDataService { private channels$ = new BehaviorSubject<any[]>([]); setChannels(channels: any[]) { this.channels$.next(channels); } client = { userStatus: () => ({ mapStream: (mapFn: any) => this.channels$.pipe( map(channels => mapFn({ userStatus: { channels, }, }), ), ), }), }; }
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; import { DataService } from '../../data/providers/data.service'; import { IfDirectiveBase } from './if-directive-base'; /** * @description * Structural directive that displays the given element if the Vendure instance has multiple channels * configured. * * @example * ```html * <div *vdrIfMultichannel class="channel-selector"> * <!-- ... --> * </ng-container> * ``` * * @docsCategory directives */ @Directive({ selector: '[vdrIfMultichannel]', }) export class IfMultichannelDirective extends IfDirectiveBase<[]> { constructor( _viewContainer: ViewContainerRef, templateRef: TemplateRef<any>, private dataService: DataService, ) { super(_viewContainer, templateRef, () => this.dataService.client .userStatus() .mapStream(({ userStatus }) => 1 < userStatus.channels.length), ); } /** * A template to show if the current user does not have the specified permission. */ @Input() set vdrIfMultichannelElse(templateRef: TemplateRef<any> | null) { this.setElseTemplate(templateRef); } }
import { Component, Input } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { PermissionsService } from '../../providers/permissions/permissions.service'; import { IfPermissionsDirective } from './if-permissions.directive'; describe('vdrIfPermissions directive', () => { let fixture: ComponentFixture<TestComponent>; beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [TestComponent, IfPermissionsDirective], }).createComponent(TestComponent); fixture.detectChanges(); // initial binding TestBed.inject(PermissionsService).setCurrentUserPermissions(['ValidPermission']); }); it('has permission (single)', () => { fixture.componentInstance.permissionToTest = 'ValidPermission'; fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).not.toBeNull(); const elseEl = fixture.nativeElement.querySelector('.else'); expect(elseEl).toBeNull(); }); it('has permission (array all match)', () => { fixture.componentInstance.permissionToTest = ['ValidPermission']; fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).not.toBeNull(); const elseEl = fixture.nativeElement.querySelector('.else'); expect(elseEl).toBeNull(); }); it('has permission (array not all match)', () => { fixture.componentInstance.permissionToTest = ['ValidPermission', 'InvalidPermission']; fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).not.toBeNull(); const elseEl = fixture.nativeElement.querySelector('.else'); expect(elseEl).toBeNull(); }); it('does not have permission', () => { fixture.componentInstance.permissionToTest = 'InvalidPermission'; fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).toBeNull(); const elseEl = fixture.nativeElement.querySelector('.else'); expect(elseEl).not.toBeNull(); }); it('pass null', () => { fixture.componentInstance.permissionToTest = null; fixture.detectChanges(); const thenEl = fixture.nativeElement.querySelector('.then'); expect(thenEl).not.toBeNull(); const elseEl = fixture.nativeElement.querySelector('.else'); expect(elseEl).toBeNull(); }); }); @Component({ template: ` <div *vdrIfPermissions="permissionToTest; else noPerms"> <span class="then"></span> </div> <ng-template #noPerms><span class="else"></span></ng-template> `, }) export class TestComponent { @Input() permissionToTest: string | string[] | null = ''; }
import { ChangeDetectorRef, Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; import { of } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { Permission } from '../../common/generated-types'; import { PermissionsService } from '../../providers/permissions/permissions.service'; import { IfDirectiveBase } from './if-directive-base'; /** * @description * Conditionally shows/hides templates based on the current active user having the specified permission. * Based on the ngIf source. Also support "else" templates: * * @example * ```html * <button *vdrIfPermissions="'DeleteCatalog'; else unauthorized">Delete Product</button> * <ng-template #unauthorized>Not allowed!</ng-template> * ``` * * The permission can be a single string, or an array. If an array is passed, then _all_ of the permissions * must match (logical AND) * * @docsCategory directives */ @Directive({ selector: '[vdrIfPermissions]', }) export class IfPermissionsDirective extends IfDirectiveBase<Array<Permission[] | null>> { private permissionToCheck: string[] | null = ['__initial_value__']; constructor( _viewContainer: ViewContainerRef, templateRef: TemplateRef<any>, private changeDetectorRef: ChangeDetectorRef, private permissionsService: PermissionsService, ) { super(_viewContainer, templateRef, permissions => { if (permissions == null) { return of(true); } else if (!permissions) { return of(false); } return this.permissionsService.currentUserPermissions$.pipe( map(() => this.permissionsService.userHasPermissions(permissions)), tap(() => this.changeDetectorRef.markForCheck()), ); }); } /** * The permission to check to determine whether to show the template. */ @Input() set vdrIfPermissions(permission: string | string[] | null) { this.permissionToCheck = (permission && (Array.isArray(permission) ? permission : [permission])) || null; this.updateArgs$.next([this.permissionToCheck as Permission[]]); } /** * A template to show if the current user does not have the specified permission. */ @Input() set vdrIfPermissionsElse(templateRef: TemplateRef<any> | null) { this.setElseTemplate(templateRef); this.updateArgs$.next([this.permissionToCheck as Permission[]]); } }
import { FactoryProvider } from '@angular/core'; import { registerFormInputComponent } from '../../extension/register-form-input-component'; import { BooleanFormInputComponent } from './boolean-form-input/boolean-form-input.component'; import { HtmlEditorFormInputComponent } from './code-editor-form-input/html-editor-form-input.component'; import { JsonEditorFormInputComponent } from './code-editor-form-input/json-editor-form-input.component'; import { CombinationModeFormInputComponent } from './combination-mode-form-input/combination-mode-form-input.component'; import { CurrencyFormInputComponent } from './currency-form-input/currency-form-input.component'; import { CustomerGroupFormInputComponent } from './customer-group-form-input/customer-group-form-input.component'; import { DateFormInputComponent } from './date-form-input/date-form-input.component'; import { FacetValueFormInputComponent } from './facet-value-form-input/facet-value-form-input.component'; import { NumberFormInputComponent } from './number-form-input/number-form-input.component'; import { PasswordFormInputComponent } from './password-form-input/password-form-input.component'; import { ProductMultiSelectorFormInputComponent } from './product-multi-selector-form-input/product-multi-selector-form-input.component'; import { ProductSelectorFormInputComponent } from './product-selector-form-input/product-selector-form-input.component'; import { RelationFormInputComponent } from './relation-form-input/relation-form-input.component'; import { RichTextFormInputComponent } from './rich-text-form-input/rich-text-form-input.component'; import { SelectFormInputComponent } from './select-form-input/select-form-input.component'; import { TextFormInputComponent } from './text-form-input/text-form-input.component'; import { TextareaFormInputComponent } from './textarea-form-input/textarea-form-input.component'; export const defaultFormInputs = [ BooleanFormInputComponent, CurrencyFormInputComponent, DateFormInputComponent, FacetValueFormInputComponent, NumberFormInputComponent, SelectFormInputComponent, TextFormInputComponent, ProductSelectorFormInputComponent, CustomerGroupFormInputComponent, PasswordFormInputComponent, RelationFormInputComponent, TextareaFormInputComponent, RichTextFormInputComponent, JsonEditorFormInputComponent, HtmlEditorFormInputComponent, ProductMultiSelectorFormInputComponent, CombinationModeFormInputComponent, ]; /** * Registers the default form input components. */ export function registerDefaultFormInputs(): FactoryProvider[] { return defaultFormInputs.map(cmp => registerFormInputComponent(cmp.id, cmp)); }
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent, InputComponentConfig } from '../../../common/component-registry-types'; /** * @description * A checkbox input. The default input component for `boolean` fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-boolean-form-input', templateUrl: './boolean-form-input.component.html', styleUrls: ['./boolean-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class BooleanFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'boolean-form-input'; readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'boolean-form-input'>; }
import { AfterViewInit, ChangeDetectorRef, Directive, ElementRef, ViewChild } from '@angular/core'; import { UntypedFormControl, ValidatorFn } from '@angular/forms'; import { DefaultFormComponentConfig } from '@vendure/common/lib/shared-types'; import { CodeJar } from 'codejar'; import { FormInputComponent } from '../../../common/component-registry-types'; export interface CodeEditorConfig { validator: ValidatorFn; getErrorMessage: (content: string) => string | undefined; highlight: (content: string, errorPos: number | undefined) => string; } @Directive() export abstract class BaseCodeEditorFormInputComponent implements FormInputComponent, AfterViewInit { readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'json-editor-form-input'>; isValid = true; errorMessage: string | undefined; @ViewChild('editor') private editorElementRef: ElementRef<HTMLDivElement>; jar: CodeJar; private highlight: CodeEditorConfig['highlight']; private getErrorMessage: CodeEditorConfig['getErrorMessage']; protected constructor(protected changeDetector: ChangeDetectorRef) {} get height() { return this.config.ui?.height || this.config.height; } configure(config: CodeEditorConfig) { this.formControl.addValidators(config.validator); this.highlight = config.highlight; this.getErrorMessage = config.getErrorMessage; } ngAfterViewInit() { let lastVal = ''; const highlight = (editor: HTMLElement) => { const code = editor.textContent ?? ''; if (code === lastVal) { return; } lastVal = code; this.errorMessage = this.getErrorMessage(code); this.changeDetector.markForCheck(); editor.innerHTML = this.highlight(code, this.getErrorPos(this.errorMessage)); }; this.jar = CodeJar(this.editorElementRef.nativeElement, highlight); let isFirstUpdate = true; this.jar.onUpdate(value => { if (isFirstUpdate) { isFirstUpdate = false; return; } this.formControl.setValue(value); this.formControl.markAsDirty(); this.isValid = this.formControl.valid; }); this.jar.updateCode(this.formControl.value); if (this.readonly) { this.editorElementRef.nativeElement.contentEditable = 'false'; } } protected getErrorPos(errorMessage: string | undefined): number | undefined { if (!errorMessage) { return; } const matches = errorMessage.match(/at position (\d+)/); const pos = matches?.[1]; return pos != null ? +pos : undefined; } }
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; import { DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent } from '../../../common/component-registry-types'; import { BaseCodeEditorFormInputComponent } from './base-code-editor-form-input.component'; function htmlValidator(): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => null; } const HTML_TAG_RE = /<\/?[^>]+>?/g; /** * @description * A JSON editor input with syntax highlighting and error detection. Works well * with `text` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-html-editor-form-input', templateUrl: './html-editor-form-input.component.html', styleUrls: ['./html-editor-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class HtmlEditorFormInputComponent extends BaseCodeEditorFormInputComponent implements FormInputComponent, AfterViewInit, OnInit { static readonly id: DefaultFormComponentId = 'html-editor-form-input'; constructor(protected changeDetector: ChangeDetectorRef) { super(changeDetector); } ngOnInit() { this.configure({ validator: htmlValidator, highlight: (html: string, errorPos: number | undefined) => { let hasMarkedError = false; return html.replace(HTML_TAG_RE, (match, ...args) => { let errorClass = ''; if (errorPos && !hasMarkedError) { const length = args[0].length; const offset = args[4]; if (errorPos <= length + offset) { errorClass = 'je-error'; hasMarkedError = true; } } return ( '<span class="he-tag' + ' ' + errorClass + '">' + this.encodeHtmlChars(match).replace( /([a-zA-Z0-9-]+=)(["'][^'"]*["'])/g, (_match, ..._args) => `${_args[0]}<span class="he-attr">${_args[1]}</span>`, ) + '</span>' ); }); }, getErrorMessage: (json: string): string | undefined => undefined, }); } private encodeHtmlChars(html: string): string { return html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } }
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; import { DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent } from '../../../common/component-registry-types'; import { BaseCodeEditorFormInputComponent } from './base-code-editor-form-input.component'; export function jsonValidator(): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const error: ValidationErrors = { jsonInvalid: true }; try { JSON.parse(control.value); } catch (e: any) { control.setErrors(error); return error; } control.setErrors(null); return null; }; } /** * @description * A JSON editor input with syntax highlighting and error detection. Works well * with `text` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-json-editor-form-input', templateUrl: './json-editor-form-input.component.html', styleUrls: ['./json-editor-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class JsonEditorFormInputComponent extends BaseCodeEditorFormInputComponent implements FormInputComponent, AfterViewInit, OnInit { static readonly id: DefaultFormComponentId = 'json-editor-form-input'; constructor(protected changeDetector: ChangeDetectorRef) { super(changeDetector); } ngOnInit() { this.configure({ validator: jsonValidator, highlight: (json: string, errorPos: number | undefined) => { json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); let hasMarkedError = false; return json.replace( /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match, ...args) => { let cls = 'number'; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = 'key'; } else { cls = 'string'; } } else if (/true|false/.test(match)) { cls = 'boolean'; } else if (/null/.test(match)) { cls = 'null'; } let errorClass = ''; if (errorPos && !hasMarkedError) { const length = args[0].length; const offset = args[4]; if (errorPos <= length + offset) { errorClass = 'je-error'; hasMarkedError = true; } } return '<span class="je-' + cls + ' ' + errorClass + '">' + match + '</span>'; }, ); }, getErrorMessage: (json: string): string | undefined => { try { JSON.parse(json); } catch (e: any) { return e.message; } return; }, }); } }
import { ChangeDetectionStrategy, Component, OnInit, Optional } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { Observable, of } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { FormInputComponent, InputComponentConfig } from '../../../common/component-registry-types'; import { ConfigurableInputComponent } from '../../components/configurable-input/configurable-input.component'; /** * @description * A special input used to display the "Combination mode" AND/OR toggle. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-combination-mode-form-input', templateUrl: './combination-mode-form-input.component.html', styleUrls: ['./combination-mode-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CombinationModeFormInputComponent implements FormInputComponent, OnInit { static readonly id: DefaultFormComponentId = 'combination-mode-form-input'; readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'combination-mode-form-input'>; selectable$: Observable<boolean>; constructor(@Optional() private configurableInputComponent: ConfigurableInputComponent) {} ngOnInit() { const selectable$ = this.configurableInputComponent ? this.configurableInputComponent.positionChange$.pipe(map(position => 0 < position)) : of(true); this.selectable$ = selectable$.pipe( tap(selectable => { if (!selectable) { this.formControl.setValue(true, { emitEvent: false }); } }), ); } setCombinationModeAnd() { this.formControl.setValue(true); } setCombinationModeOr() { this.formControl.setValue(false); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { Observable } from 'rxjs'; import { FormInputComponent, InputComponentConfig } from '../../../common/component-registry-types'; import { CurrencyCode } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; /** * @description * An input for monetary values. Should be used with `int` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-currency-form-input', templateUrl: './currency-form-input.component.html', styleUrls: ['./currency-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CurrencyFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'currency-form-input'; @Input() readonly: boolean; formControl: UntypedFormControl; currencyCode$: Observable<CurrencyCode>; config: DefaultFormComponentConfig<'currency-form-input'>; constructor(private dataService: DataService) { this.currencyCode$ = this.dataService.settings .getActiveChannel() .mapStream(data => data.activeChannel.defaultCurrencyCode); } }
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { Observable } from 'rxjs'; import { startWith } from 'rxjs/operators'; import { ItemOf } from '../../../common/base-list.component'; import { FormInputComponent } from '../../../common/component-registry-types'; import { GetCustomerGroupsQuery } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; /** * @description * Allows the selection of a Customer via an autocomplete select input. * Should be used with `ID` type fields which represent Customer IDs. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-customer-group-form-input', templateUrl: './customer-group-form-input.component.html', styleUrls: ['./customer-group-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerGroupFormInputComponent implements FormInputComponent, OnInit { static readonly id: DefaultFormComponentId = 'customer-group-form-input'; @Input() readonly: boolean; formControl: FormControl<string | { id: string }>; customerGroups$: Observable<GetCustomerGroupsQuery['customerGroups']['items']>; config: DefaultFormComponentConfig<'customer-group-form-input'>; constructor(private dataService: DataService) {} ngOnInit() { this.customerGroups$ = this.dataService.customer .getCustomerGroupList({ take: 1000, }) .mapSingle(res => res.customerGroups.items) .pipe(startWith([])); } selectGroup(group: ItemOf<GetCustomerGroupsQuery, 'customerGroups'>) { this.formControl.setValue(group?.id ?? undefined); } compareWith<T extends ItemOf<GetCustomerGroupsQuery, 'customerGroups'> | string>(o1: T, o2: T) { const id1 = typeof o1 === 'string' ? o1 : o1.id; const id2 = typeof o2 === 'string' ? o2 : o2.id; return id1 === id2; } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent } from '../../../common/component-registry-types'; /** * @description * Allows selection of a datetime. Default input for `datetime` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-date-form-input', templateUrl: './date-form-input.component.html', styleUrls: ['./date-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DateFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'date-form-input'; @Input() readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'date-form-input'>; get min() { return this.config.ui?.min || this.config.min; } get max() { return this.config.ui?.max || this.config.max; } get yearRange() { return this.config.ui?.yearRange || this.config.yearRange; } }
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentRef, Injector, Input, OnChanges, OnDestroy, OnInit, Provider, QueryList, SimpleChanges, Type, ViewChild, ViewChildren, ViewContainerRef, } from '@angular/core'; import { ControlValueAccessor, FormArray, FormControl, NG_VALUE_ACCESSOR, UntypedFormArray, UntypedFormControl, } from '@angular/forms'; import { StringCustomFieldConfig } from '@vendure/common/lib/generated-types'; import { ConfigArgType, CustomFieldType, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { assertNever, notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { simpleDeepClone } from '@vendure/common/lib/simple-deep-clone'; import { Subject, Subscription } from 'rxjs'; import { switchMap, take, takeUntil } from 'rxjs/operators'; import { FormInputComponent } from '../../../common/component-registry-types'; import { ConfigArgDefinition, CustomFieldConfig } from '../../../common/generated-types'; import { getConfigArgValue } from '../../../common/utilities/configurable-operation-utils'; import { ComponentRegistryService } from '../../../providers/component-registry/component-registry.service'; type InputListItem = { id: number; componentRef?: ComponentRef<FormInputComponent>; control: UntypedFormControl; }; /** * A host component which delegates to an instance or list of FormInputComponent components. */ @Component({ selector: 'vdr-dynamic-form-input', templateUrl: './dynamic-form-input.component.html', styleUrls: ['./dynamic-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: DynamicFormInputComponent, multi: true, }, ], }) export class DynamicFormInputComponent implements OnInit, OnChanges, AfterViewInit, OnDestroy, ControlValueAccessor { @Input() def: ConfigArgDefinition | CustomFieldConfig; @Input() readonly: boolean; @Input() control: UntypedFormControl; @ViewChild('single', { read: ViewContainerRef }) singleViewContainer: ViewContainerRef; @ViewChildren('listItem', { read: ViewContainerRef }) listItemContainers: QueryList<ViewContainerRef>; renderAsList = false; listItems: InputListItem[] = []; private singleComponentRef: ComponentRef<FormInputComponent>; private listId = 1; private listFormArray = new FormArray([] as Array<FormControl<any>>); private componentType: Type<FormInputComponent>; private componentProviders: Provider[] = []; private onChange: (val: any) => void; private onTouch: () => void; private renderList$ = new Subject<void>(); private destroy$ = new Subject<void>(); constructor( private componentRegistryService: ComponentRegistryService, private changeDetectorRef: ChangeDetectorRef, private injector: Injector, ) {} ngOnInit() { const componentId = this.getInputComponentConfig(this.def).component; const component = this.componentRegistryService.getInputComponent(componentId); if (component) { this.componentType = component.type; this.componentProviders = component.providers; } else { // eslint-disable-next-line no-console console.error( `No form input component registered with the id "${componentId}". Using the default input instead.`, ); const defaultComponentType = this.componentRegistryService.getInputComponent( this.getInputComponentConfig({ ...this.def, ui: undefined } as any).component, ); if (defaultComponentType) { this.componentType = defaultComponentType.type; } } } ngAfterViewInit() { if (this.componentType) { const injector = Injector.create({ providers: this.componentProviders, parent: this.injector, }); // create a temp instance to check the value of `isListInput` const cmpRef = this.singleViewContainer.createComponent(this.componentType, { injector }); const isListInputComponent = cmpRef.instance.isListInput ?? false; cmpRef.destroy(); if (this.def.list === false && isListInputComponent) { throw new Error( `The ${this.componentType.name} component is a list input, but the definition for ${this.def.name} does not expect a list`, ); } this.renderAsList = this.def.list && !isListInputComponent; if (!this.renderAsList) { this.singleComponentRef = this.renderInputComponent( injector, this.singleViewContainer, this.control, ); } else { let formArraySub: Subscription | undefined; const renderListInputs = (viewContainerRefs: QueryList<ViewContainerRef>) => { if (viewContainerRefs.length) { if (formArraySub) { formArraySub.unsubscribe(); } this.listFormArray = new UntypedFormArray([]); this.listItems.forEach(i => i.componentRef?.destroy()); viewContainerRefs.forEach((ref, i) => { const listItem = this.listItems?.[i]; if (listItem) { this.listFormArray.push(listItem.control); listItem.componentRef = this.renderInputComponent( injector, ref, listItem.control, ); } }); formArraySub = this.listFormArray.valueChanges .pipe(takeUntil(this.destroy$)) .subscribe(val => { this.control.markAsTouched(); this.control.markAsDirty(); const truthyValues = val.filter(notNullOrUndefined); this.onChange(truthyValues); this.control.patchValue(truthyValues, { emitEvent: false }); }); setTimeout(() => this.changeDetectorRef.markForCheck()); } }; // initial render this.listItemContainers.changes .pipe(take(1)) .subscribe(val => renderListInputs(this.listItemContainers)); // render on changes to the list this.renderList$ .pipe( switchMap(() => this.listItemContainers.changes.pipe(take(1))), takeUntil(this.destroy$), ) .subscribe(() => { renderListInputs(this.listItemContainers); }); } } setTimeout(() => this.changeDetectorRef.markForCheck()); } ngOnChanges(changes: SimpleChanges) { if (this.listItems) { for (const item of this.listItems) { if (item.componentRef) { this.updateBindings(changes, item.componentRef); } } } if (this.singleComponentRef) { this.updateBindings(changes, this.singleComponentRef); } } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } private updateBindings(changes: SimpleChanges, componentRef: ComponentRef<FormInputComponent>) { if ('def' in changes) { componentRef.instance.config = simpleDeepClone(this.def); } if ('readonly' in changes) { componentRef.instance.readonly = this.readonly; } componentRef.injector.get(ChangeDetectorRef).markForCheck(); } trackById(index: number, item: { id: number }) { return item.id; } addListItem() { if (!this.listItems) { this.listItems = []; } this.listItems.push({ id: this.listId++, control: new UntypedFormControl((this.def as ConfigArgDefinition).defaultValue ?? null), }); this.renderList$.next(); } moveListItem(event: CdkDragDrop<InputListItem>) { if (this.listItems) { moveItemInArray(this.listItems, event.previousIndex, event.currentIndex); this.listFormArray.removeAt(event.previousIndex); this.listFormArray.insert(event.currentIndex, event.item.data.control); this.renderList$.next(); } } removeListItem(item: InputListItem) { if (this.listItems) { const index = this.listItems.findIndex(i => i === item); item.componentRef?.destroy(); this.listFormArray.removeAt(index); this.listItems = this.listItems.filter(i => i !== item); this.renderList$.next(); } } private renderInputComponent( injector: Injector, viewContainerRef: ViewContainerRef, formControl: UntypedFormControl, ) { const componentRef = viewContainerRef.createComponent(this.componentType, { injector }); const { instance } = componentRef; instance.config = simpleDeepClone(this.def); instance.formControl = formControl; instance.readonly = this.readonly; componentRef.injector.get(ChangeDetectorRef).markForCheck(); return componentRef; } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouch = fn; } writeValue(obj: any): void { if (Array.isArray(obj)) { if (obj.length === this.listItems.length) { obj.forEach((value, index) => { const control = this.listItems[index]?.control; control.patchValue(getConfigArgValue(value), { emitEvent: false }); }); } else { this.listItems = obj.map( value => ({ id: this.listId++, control: new UntypedFormControl(getConfigArgValue(value)), } as InputListItem), ); this.renderList$.next(); } } else { this.listItems = []; this.renderList$.next(); } this.changeDetectorRef.markForCheck(); } private getInputComponentConfig(argDef: ConfigArgDefinition | CustomFieldConfig): { component: DefaultFormComponentId; } { if (this.hasUiConfig(argDef) && argDef.ui.component) { return argDef.ui; } const type = argDef?.type as ConfigArgType | CustomFieldType; switch (type) { case 'string': case 'localeString': { const hasOptions = !!(this.isConfigArgDef(argDef) && argDef.ui?.options) || !!(argDef as StringCustomFieldConfig).options; if (hasOptions) { return { component: 'select-form-input' }; } else { return { component: 'text-form-input' }; } } case 'text': case 'localeText': { return { component: 'textarea-form-input' }; } case 'int': case 'float': return { component: 'number-form-input' }; case 'boolean': return { component: 'boolean-form-input' }; case 'datetime': return { component: 'date-form-input' }; case 'ID': return { component: 'text-form-input' }; case 'relation': return { component: 'relation-form-input' }; default: assertNever(type); } } private isConfigArgDef(def: ConfigArgDefinition | CustomFieldConfig): def is ConfigArgDefinition { return (def as ConfigArgDefinition)?.__typename === 'ConfigArgDefinition'; } private hasUiConfig(def: unknown): def is { ui: { component: string } } { return typeof def === 'object' && typeof (def as any)?.ui?.component === 'string'; } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent, InputComponentConfig } from '../../../common/component-registry-types'; import { FacetValueFragment } from '../../../common/generated-types'; /** * @description * Allows the selection of multiple FacetValues via an autocomplete select input. * Should be used with `ID` type **list** fields which represent FacetValue IDs. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-facet-value-form-input', templateUrl: './facet-value-form-input.component.html', styleUrls: ['./facet-value-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FacetValueFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'facet-value-form-input'; readonly isListInput = true; readonly: boolean; formControl: UntypedFormControl; config: InputComponentConfig; valueTransformFn = (values: FacetValueFragment[]) => { const isUsedInConfigArg = this.config.__typename === 'ConfigArgDefinition'; if (isUsedInConfigArg) { return JSON.stringify(values.map(s => s.id)); } else { return values; } }; }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent } from '../../../common/component-registry-types'; /** * @description * Displays a number input. Default input for `int` and `float` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-number-form-input', templateUrl: './number-form-input.component.html', styleUrls: ['./number-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class NumberFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'number-form-input'; @Input() readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'number-form-input'>; get prefix() { return this.config.ui?.prefix || this.config.prefix; } get suffix() { return this.config.ui?.suffix || this.config.suffix; } get min() { return this.config.ui?.min || this.config.min; } get max() { return this.config.ui?.max || this.config.max; } get step() { return this.config.ui?.step || this.config.step; } }
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent, InputComponentConfig } from '../../../common/component-registry-types'; /** * @description * Displays a password text input. Should be used with `string` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-password-form-input', templateUrl: './password-form-input.component.html', styleUrls: ['./password-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PasswordFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'password-form-input'; readonly: boolean; formControl: UntypedFormControl; config: InputComponentConfig; }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnInit } from '@angular/core'; import { FormControl, UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent } from '../../../common/component-registry-types'; import { DataService } from '../../../data/providers/data.service'; import { ModalService } from '../../../providers/modal/modal.service'; import { ProductMultiSelectorDialogComponent } from '../../components/product-multi-selector-dialog/product-multi-selector-dialog.component'; @Component({ selector: 'vdr-product-multi-selector-form-input', templateUrl: './product-multi-selector-form-input.component.html', styleUrls: ['./product-multi-selector-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ProductMultiSelectorFormInputComponent implements OnInit, FormInputComponent { @Input() config: DefaultFormComponentConfig<'product-multi-form-input'>; @Input() formControl: FormControl<string[] | Array<{ id: string }>>; @Input() readonly: boolean; mode: 'product' | 'variant' = 'product'; readonly isListInput = true; static readonly id: DefaultFormComponentId = 'product-multi-form-input'; constructor( private modalService: ModalService, private dataService: DataService, private changeDetector: ChangeDetectorRef, ) {} ngOnInit() { this.mode = this.config.ui?.selectionMode ?? 'product'; } select() { this.modalService .fromComponent(ProductMultiSelectorDialogComponent, { size: 'xl', locals: { mode: this.mode, initialSelectionIds: this.formControl.value.map(item => typeof item === 'string' ? item : item.id, ), }, }) .subscribe(selection => { if (selection) { this.formControl.setValue( selection.map(item => this.mode === 'product' ? item.productId : item.productVariantId, ), ); this.formControl.markAsDirty(); this.changeDetector.markForCheck(); } }); } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { DefaultFormComponentId, DefaultFormComponentUiConfig } from '@vendure/common/lib/shared-types'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { forkJoin, Observable, of } from 'rxjs'; import { map, startWith, switchMap } from 'rxjs/operators'; import { FormInputComponent } from '../../../common/component-registry-types'; import { GetProductVariantQuery, ProductSelectorSearchQuery } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; /** * @description * Allows the selection of multiple ProductVariants via an autocomplete select input. * Should be used with `ID` type **list** fields which represent ProductVariant IDs. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-product-selector-form-input', templateUrl: './product-selector-form-input.component.html', styleUrls: ['./product-selector-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ProductSelectorFormInputComponent implements FormInputComponent, OnInit { static readonly id: DefaultFormComponentId = 'product-selector-form-input'; readonly isListInput = true; readonly: boolean; formControl: FormControl<Array<string | { id: string }>>; config: DefaultFormComponentUiConfig<'product-selector-form-input'>; selection$: Observable<Array<GetProductVariantQuery['productVariant']>>; constructor(private dataService: DataService) {} ngOnInit() { this.formControl.setValidators([ control => { if (!control.value || !control.value.length) { return { atLeastOne: { length: control.value.length }, }; } return null; }, ]); this.selection$ = this.formControl.valueChanges.pipe( startWith(this.formControl.value), switchMap(value => { if (Array.isArray(value) && 0 < value.length) { return forkJoin( value.map(id => this.dataService.product .getProductVariant(this.getId(id)) .mapSingle(data => data.productVariant), ), ); } return of([]); }), map(variants => variants.filter(notNullOrUndefined)), ); } addProductVariant(product: ProductSelectorSearchQuery['search']['items'][number]) { const value = this.formControl.value as string[]; this.formControl.setValue([...new Set([...value, product.productVariantId])]); this.formControl.markAsDirty(); } removeProductVariant(id: string) { const value = this.formControl.value; this.formControl.setValue(value.map(this.getId).filter(_id => _id !== id)); this.formControl.markAsDirty(); } private getId(value: (typeof this.formControl.value)[number]) { return typeof value === 'string' ? value : value.id; } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent } from '../../../common/component-registry-types'; import { RelationCustomFieldConfig } from '../../../common/generated-types'; /** * @description * The default input component for `relation` type custom fields. Allows the selection * of a ProductVariant, Product, Customer or Asset. For other entity types, a custom * implementation will need to be defined. See {@link registerFormInputComponent}. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-relation-form-input', templateUrl: './relation-form-input.component.html', styleUrls: ['./relation-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RelationFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'relation-form-input'; @Input() readonly: boolean; formControl: UntypedFormControl; config: RelationCustomFieldConfig; }
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { gql } from 'apollo-angular'; import { Observable, of } from 'rxjs'; import { distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators'; import { GetAssetQuery, RelationCustomFieldConfig } from '../../../../common/generated-types'; import { ASSET_FRAGMENT, TAG_FRAGMENT } from '../../../../data/definitions/product-definitions'; import { DataService } from '../../../../data/providers/data.service'; import { ModalService } from '../../../../providers/modal/modal.service'; import { AssetPickerDialogComponent } from '../../../components/asset-picker-dialog/asset-picker-dialog.component'; import { AssetPreviewDialogComponent } from '../../../components/asset-preview-dialog/asset-preview-dialog.component'; export const RELATION_ASSET_INPUT_QUERY = gql` query RelationAssetInputQuery($id: ID!) { asset(id: $id) { ...Asset tags { ...Tag } } } ${ASSET_FRAGMENT} ${TAG_FRAGMENT} `; @Component({ selector: 'vdr-relation-asset-input', templateUrl: './relation-asset-input.component.html', styleUrls: ['./relation-asset-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RelationAssetInputComponent implements OnInit { @Input() readonly: boolean; @Input('parentFormControl') formControl: UntypedFormControl; @Input() config: RelationCustomFieldConfig; asset$: Observable<GetAssetQuery['asset'] | undefined>; constructor(private modalService: ModalService, private dataService: DataService) {} ngOnInit() { this.asset$ = this.formControl.valueChanges.pipe( startWith(this.formControl.value), map(asset => asset?.id), distinctUntilChanged(), switchMap(id => { if (id) { return this.dataService.product.getAsset(id).mapStream(data => data.asset || undefined); } else { return of(undefined); } }), ); } selectAsset() { this.modalService .fromComponent(AssetPickerDialogComponent, { size: 'xl', locals: { multiSelect: false, }, }) .subscribe(result => { if (result && result.length) { this.formControl.setValue(result[0]); this.formControl.markAsDirty(); } }); } remove() { this.formControl.setValue(null); this.formControl.markAsDirty(); } previewAsset(asset: NonNullable<GetAssetQuery['asset']>) { this.modalService .fromComponent(AssetPreviewDialogComponent, { size: 'xl', closable: true, locals: { asset }, }) .subscribe(); } }
import { ChangeDetectionStrategy, Component, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { Observable, Subject } from 'rxjs'; import { debounceTime, switchMap } from 'rxjs/operators'; import * as Codegen from '../../../../common/generated-types'; import { CustomerFragment, RelationCustomFieldConfig } from '../../../../common/generated-types'; import { DataService } from '../../../../data/providers/data.service'; import { ModalService } from '../../../../providers/modal/modal.service'; import { RelationSelectorDialogComponent } from '../relation-selector-dialog/relation-selector-dialog.component'; @Component({ selector: 'vdr-relation-customer-input', templateUrl: './relation-customer-input.component.html', styleUrls: ['./relation-customer-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RelationCustomerInputComponent implements OnInit { @Input() readonly: boolean; @Input() parentFormControl: UntypedFormControl; @Input() config: RelationCustomFieldConfig; @ViewChild('selector') template: TemplateRef<any>; searchTerm$ = new Subject<string>(); results$: Observable<Codegen.GetCustomerListQuery['customers']['items']>; get customer(): CustomerFragment | undefined { return this.parentFormControl.value; } constructor(private modalService: ModalService, private dataService: DataService) {} ngOnInit() { this.results$ = this.searchTerm$.pipe( debounceTime(200), switchMap(term => this.dataService.customer .getCustomerList(10, 0, term) .mapSingle(data => data.customers.items), ), ); } selectCustomer() { this.modalService .fromComponent(RelationSelectorDialogComponent, { size: 'md', closable: true, locals: { title: _('customer.select-customer'), selectorTemplate: this.template, }, }) .subscribe(result => { if (result) { this.parentFormControl.setValue(result); this.parentFormControl.markAsDirty(); } }); } remove() { this.parentFormControl.setValue(null); this.parentFormControl.markAsDirty(); } }
import { ChangeDetectionStrategy, Component, Input, TemplateRef, ViewChild } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { RelationCustomFieldConfig } from '../../../../common/generated-types'; import { ModalService } from '../../../../providers/modal/modal.service'; import { RelationSelectorDialogComponent } from '../relation-selector-dialog/relation-selector-dialog.component'; @Component({ selector: 'vdr-relation-generic-input', templateUrl: './relation-generic-input.component.html', styleUrls: ['./relation-generic-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RelationGenericInputComponent { @Input() readonly: boolean; @Input() parentFormControl: UntypedFormControl; @Input() config: RelationCustomFieldConfig; relationId: string; @ViewChild('selector') template: TemplateRef<any>; constructor(private modalService: ModalService) {} selectRelationId() { this.modalService .fromComponent(RelationSelectorDialogComponent, { size: 'md', closable: true, locals: { title: _('common.select-relation-id'), selectorTemplate: this.template, }, }) .subscribe(result => { if (result) { this.parentFormControl.setValue({ id: result }); this.parentFormControl.markAsDirty(); } }); } remove() { this.parentFormControl.setValue(null); this.parentFormControl.markAsDirty(); } }
import { ChangeDetectionStrategy, Component, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { Observable, of, Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators'; import * as Codegen from '../../../../common/generated-types'; import { RelationCustomFieldConfig } from '../../../../common/generated-types'; import { DataService } from '../../../../data/providers/data.service'; import { ModalService } from '../../../../providers/modal/modal.service'; import { RelationSelectorDialogComponent } from '../relation-selector-dialog/relation-selector-dialog.component'; @Component({ selector: 'vdr-relation-product-variant-input', templateUrl: './relation-product-variant-input.component.html', styleUrls: ['./relation-product-variant-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RelationProductVariantInputComponent implements OnInit { @Input() readonly: boolean; @Input() parentFormControl: UntypedFormControl; @Input() config: RelationCustomFieldConfig; @ViewChild('selector') template: TemplateRef<any>; searchControl = new UntypedFormControl(''); searchTerm$ = new Subject<string>(); results$: Observable<Codegen.GetProductVariantListSimpleQuery['productVariants']['items']>; productVariant$: Observable<Codegen.GetProductVariantQuery['productVariant'] | undefined>; constructor(private modalService: ModalService, private dataService: DataService) {} ngOnInit() { this.productVariant$ = this.parentFormControl.valueChanges.pipe( startWith(this.parentFormControl.value), map(variant => variant?.id), distinctUntilChanged(), switchMap(id => { if (id) { return this.dataService.product .getProductVariant(id) .mapStream(data => data.productVariant || undefined); } else { return of(undefined); } }), ); this.results$ = this.searchTerm$.pipe( debounceTime(200), switchMap(term => this.dataService.product .getProductVariantsSimple({ ...(term ? { filter: { name: { contains: term, }, }, } : {}), take: 10, }) .mapSingle(data => data.productVariants.items), ), ); } selectProductVariant() { this.modalService .fromComponent(RelationSelectorDialogComponent, { size: 'md', closable: true, locals: { title: _('catalog.select-product-variant'), selectorTemplate: this.template, }, }) .subscribe(result => { if (result) { this.parentFormControl.setValue(result); this.parentFormControl.markAsDirty(); } }); } remove() { this.parentFormControl.setValue(null); this.parentFormControl.markAsDirty(); } }
import { ChangeDetectionStrategy, Component, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { Observable, of, Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators'; import * as Codegen from '../../../../common/generated-types'; import { RelationCustomFieldConfig } from '../../../../common/generated-types'; import { DataService } from '../../../../data/providers/data.service'; import { ModalService } from '../../../../providers/modal/modal.service'; import { RelationSelectorDialogComponent } from '../relation-selector-dialog/relation-selector-dialog.component'; @Component({ selector: 'vdr-relation-product-input', templateUrl: './relation-product-input.component.html', styleUrls: ['./relation-product-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RelationProductInputComponent implements OnInit { @Input() readonly: boolean; @Input() parentFormControl: UntypedFormControl; @Input() config: RelationCustomFieldConfig; @ViewChild('selector') template: TemplateRef<any>; searchControl = new UntypedFormControl(''); searchTerm$ = new Subject<string>(); results$: Observable<Codegen.GetProductListQuery['products']['items']>; product$: Observable<Codegen.GetProductSimpleQuery['product'] | undefined>; constructor(private modalService: ModalService, private dataService: DataService) {} ngOnInit() { this.product$ = this.parentFormControl.valueChanges.pipe( startWith(this.parentFormControl.value), map(product => product?.id), distinctUntilChanged(), switchMap(id => { if (id) { return this.dataService.product .getProductSimple(id) .mapStream(data => data.product || undefined); } else { return of(undefined); } }), ); this.results$ = this.searchTerm$.pipe( debounceTime(200), switchMap(term => this.dataService.product .getProducts({ ...(term ? { filter: { name: { contains: term, }, }, } : {}), take: 10, }) .mapSingle(data => data.products.items), ), ); } selectProduct() { this.modalService .fromComponent(RelationSelectorDialogComponent, { size: 'md', closable: true, locals: { title: _('catalog.select-product'), selectorTemplate: this.template, }, }) .subscribe(result => { if (result) { this.parentFormControl.setValue(result); this.parentFormControl.markAsDirty(); } }); } remove() { this.parentFormControl.setValue(null); this.parentFormControl.markAsDirty(); } }
import { EventEmitter, ChangeDetectionStrategy, Component, ContentChild, Directive, Input, Output, TemplateRef, } from '@angular/core'; @Directive({ selector: '[vdrRelationCardPreview]', }) export class RelationCardPreviewDirective {} @Directive({ selector: '[vdrRelationCardDetail]', }) export class RelationCardDetailDirective {} @Component({ selector: 'vdr-relation-card', templateUrl: './relation-card.component.html', styleUrls: ['./relation-card.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RelationCardComponent { @Input() entity: any; @Input() placeholderIcon: string; @Input() selectLabel: string; @Input() readonly: boolean; @Input() removable = true; // eslint-disable-next-line @angular-eslint/no-output-native @Output() select = new EventEmitter(); @Output() remove = new EventEmitter(); @ContentChild(RelationCardPreviewDirective, { read: TemplateRef }) previewTemplate: TemplateRef<any>; @ContentChild(RelationCardDetailDirective, { read: TemplateRef }) detailTemplate: TemplateRef<any>; }
import { ChangeDetectionStrategy, Component, TemplateRef } from '@angular/core'; import { Dialog } from '../../../../providers/modal/modal.types'; @Component({ selector: 'vdr-relation-selector-dialog', templateUrl: './relation-selector-dialog.component.html', styleUrls: ['./relation-selector-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RelationSelectorDialogComponent implements Dialog<string[]> { resolveWith: (result?: string[]) => void; title: string; selectorTemplate: TemplateRef<any>; }
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent, InputComponentConfig } from '../../../common/component-registry-types'; /** * @description * Uses the {@link RichTextEditorComponent} as in input for `text` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-rich-text-form-input', templateUrl: './rich-text-form-input.component.html', styleUrls: ['./rich-text-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RichTextFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'rich-text-form-input'; readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'rich-text-form-input'>; }
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { Observable } from 'rxjs'; import { FormInputComponent } from '../../../common/component-registry-types'; import { CustomFieldConfigFragment, LanguageCode } from '../../../common/generated-types'; import { DataService } from '../../../data/providers/data.service'; /** * @description * Uses a select input to allow the selection of a string value. Should be used with * `string` type fields with options. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-select-form-input', templateUrl: './select-form-input.component.html', styleUrls: ['./select-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SelectFormInputComponent implements FormInputComponent, OnInit { static readonly id: DefaultFormComponentId = 'select-form-input'; @Input() readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'select-form-input'> & CustomFieldConfigFragment; uiLanguage$: Observable<LanguageCode>; get options() { return this.config.ui?.options || this.config.options; } constructor(private dataService: DataService) {} ngOnInit() { this.uiLanguage$ = this.dataService.client.uiState().mapStream(({ uiState }) => uiState.language); } trackByFn(index: number, item: any) { return item.value; } }
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent, InputComponentConfig } from '../../../common/component-registry-types'; /** * @description * Uses a regular text form input. This is the default input for `string` and `localeString` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-text-form-input', templateUrl: './text-form-input.component.html', styleUrls: ['./text-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TextFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'text-form-input'; readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'text-form-input'>; get prefix() { return this.config.ui?.prefix || this.config.prefix; } get suffix() { return this.config.ui?.suffix || this.config.suffix; } }
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DefaultFormComponentConfig, DefaultFormComponentId } from '@vendure/common/lib/shared-types'; import { FormInputComponent, InputComponentConfig } from '../../../common/component-registry-types'; /** * @description * Uses textarea form input. This is the default input for `text` type fields. * * @docsCategory custom-input-components * @docsPage default-inputs */ @Component({ selector: 'vdr-textarea-form-input', templateUrl: './textarea-form-input.component.html', styleUrls: ['./textarea-form-input.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TextareaFormInputComponent implements FormInputComponent { static readonly id: DefaultFormComponentId = 'textarea-form-input'; readonly: boolean; formControl: UntypedFormControl; config: DefaultFormComponentConfig<'textarea-form-input'>; get spellcheck(): boolean { return this.config.spellcheck === true; } }
import { Pipe, PipeTransform } from '@angular/core'; import { AssetFragment } from '../../common/generated-types'; /** * @description * Given an Asset object (an object with `preview` and optionally `focalPoint` properties), this pipe * returns a string with query parameters designed to work with the image resize capabilities of the * AssetServerPlugin. * * @example * ```HTML * <img [src]="asset | assetPreview:'tiny'" /> * <img [src]="asset | assetPreview:150" /> * ``` * * @docsCategory pipes */ @Pipe({ name: 'assetPreview', }) export class AssetPreviewPipe implements PipeTransform { transform(asset?: AssetFragment, preset: string | number = 'thumb'): string { if (!asset) { return ''; } if (asset.preview == null || typeof asset.preview !== 'string') { throw new Error(`Expected an Asset, got ${JSON.stringify(asset)}`); } const fp = asset.focalPoint ? `&fpx=${asset.focalPoint.x}&fpy=${asset.focalPoint.y}` : ''; if (Number.isNaN(Number(preset))) { return `${asset.preview}?preset=${preset}${fp}`; } else { return `${asset.preview}?w=${preset}&h=${preset}${fp}`; } } }
import { Pipe, PipeTransform } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; @Pipe({ name: 'channelCodeToLabel', }) export class ChannelLabelPipe implements PipeTransform { transform(value: any, ...args: any[]): any { if (value === DEFAULT_CHANNEL_CODE) { return _('common.default-channel'); } else { return value; } } }
import { Pipe, PipeTransform } from '@angular/core'; import { CustomFieldConfig, LanguageCode, StringFieldOption } from '../../common/generated-types'; /** * Displays a localized description for a CustomField */ @Pipe({ name: 'customFieldDescription', pure: true, }) export class CustomFieldDescriptionPipe implements PipeTransform { transform(value: CustomFieldConfig, uiLanguageCode: LanguageCode | null): string { if (!value) { return value; } const { description } = value; if (description) { const match = description.find(l => l.languageCode === uiLanguageCode); return match ? match.value : description[0].value; } else { return ''; } } }
import { Pipe, PipeTransform } from '@angular/core'; import { CustomFieldConfig, LanguageCode, LocalizedString, StringFieldOption, } from '../../common/generated-types'; /** * Displays a localized label for a CustomField or StringFieldOption, falling back to the * name/value if none are defined. */ @Pipe({ name: 'customFieldLabel', pure: true, }) export class CustomFieldLabelPipe implements PipeTransform { transform( value: CustomFieldConfig | StringFieldOption | LocalizedString[], uiLanguageCode: LanguageCode | null, ): string { if (!value) { return value; } if (Array.isArray(value)) { const match = value.find(l => l.languageCode === uiLanguageCode); return match ? match.value : value[0].value; } const { label } = value; const name = this.isCustomFieldConfig(value) ? value.name : value.value; if (label) { const match = label.find(l => l.languageCode === uiLanguageCode); return match ? match.value : label[0].value; } else { return name; } } private isCustomFieldConfig(input: any): input is CustomFieldConfig { return input.hasOwnProperty('name'); } }
import { DurationPipe } from './duration.pipe'; describe('DurationPipe', () => { let mockI18nService: any; beforeEach(() => { mockI18nService = { translate: jasmine.createSpy('translate'), }; }); it('ms', () => { const pipe = new DurationPipe(mockI18nService); pipe.transform(1); expect(mockI18nService.translate.calls.argsFor(0)).toEqual([ 'datetime.duration-milliseconds', { ms: 1 }, ]); pipe.transform(999); expect(mockI18nService.translate.calls.argsFor(1)).toEqual([ 'datetime.duration-milliseconds', { ms: 999 }, ]); }); it('s', () => { const pipe = new DurationPipe(mockI18nService); pipe.transform(1000); expect(mockI18nService.translate.calls.argsFor(0)).toEqual(['datetime.duration-seconds', { s: 1.0 }]); pipe.transform(2567); expect(mockI18nService.translate.calls.argsFor(1)).toEqual(['datetime.duration-seconds', { s: 2.6 }]); pipe.transform(59.3 * 1000); expect(mockI18nService.translate.calls.argsFor(2)).toEqual([ 'datetime.duration-seconds', { s: 59.3 }, ]); }); it('m:s', () => { const pipe = new DurationPipe(mockI18nService); pipe.transform(60 * 1000); expect(mockI18nService.translate.calls.argsFor(0)).toEqual([ 'datetime.duration-minutes:seconds', { m: 1, s: '00' }, ]); pipe.transform(125.23 * 1000); expect(mockI18nService.translate.calls.argsFor(1)).toEqual([ 'datetime.duration-minutes:seconds', { m: 2, s: '05' }, ]); }); });
import { Pipe, PipeTransform } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { I18nService } from '../../providers/i18n/i18n.service'; /** * @description * Displays a number of milliseconds in a more human-readable format, * e.g. "12ms", "33s", "2:03m" * * @example * ```ts * {{ timeInMs | duration }} * ``` * * @docsCategory pipes */ @Pipe({ name: 'duration', }) export class DurationPipe implements PipeTransform { constructor(private i18nService: I18nService) {} transform(value: number): string { if (value < 1000) { return this.i18nService.translate(_('datetime.duration-milliseconds'), { ms: value }); } else if (value < 1000 * 60) { const seconds1dp = +(value / 1000).toFixed(1); return this.i18nService.translate(_('datetime.duration-seconds'), { s: seconds1dp }); } else { const minutes = Math.floor(value / (1000 * 60)); const seconds = Math.round((value % (1000 * 60)) / 1000) .toString() .padStart(2, '0'); return this.i18nService.translate(_('datetime.duration-minutes:seconds'), { m: minutes, s: seconds, }); } } }
import { FileSizePipe } from './file-size.pipe'; describe('FileSizePipe:', () => { let fileSizePipe: FileSizePipe; beforeEach(() => (fileSizePipe = new FileSizePipe())); it('should handle bytes', () => { expect(fileSizePipe.transform(123)).toBe('123 B'); }); it('should handle kilobytes', () => { expect(fileSizePipe.transform(12340)).toBe('12.3 kB'); }); it('should handle megabytes', () => { expect(fileSizePipe.transform(1234500)).toBe('1.2 MB'); }); it('should handle gigabytes', () => { expect(fileSizePipe.transform(1234500000)).toBe('1.2 GB'); }); it('should handle kibibytes', () => { expect(fileSizePipe.transform(12340, false)).toBe('12.1 KiB'); }); it('should handle mebibytes', () => { expect(fileSizePipe.transform(13434500, false)).toBe('12.8 MiB'); }); describe('exceptional input', () => { it('should handle a string', () => { expect(fileSizePipe.transform('1230' as any)).toBe('1.2 kB'); }); it('should handle null', () => { expect(fileSizePipe.transform(null as any)).toBeNull(); }); it('should handle undefined', () => { expect(fileSizePipe.transform(undefined as any)).toBeUndefined(); }); it('should handle an object', () => { const obj = {}; expect(fileSizePipe.transform(obj as any)).toBe(obj); }); it('should handle a function', () => { const fn = () => { /* */ }; expect(fileSizePipe.transform(fn as any)).toBe(fn); }); }); });
import { Pipe, PipeTransform } from '@angular/core'; /** * @description * Formats a number into a human-readable file size string. * * @example * ```ts * {{ fileSizeInBytes | filesize }} * ``` * * @docsCategory pipes */ @Pipe({ name: 'filesize' }) export class FileSizePipe implements PipeTransform { transform(value: number, useSiUnits = true): any { if (typeof value !== 'number' && typeof value !== 'string') { return value; } return humanFileSize(value, useSiUnits === true); } } /** * Convert a number into a human-readable file size string. * Adapted from http://stackoverflow.com/a/14919494/772859 */ function humanFileSize(bytes: number, si: boolean): string { const thresh = si ? 1000 : 1024; if (Math.abs(bytes) < thresh) { return bytes + ' B'; } const units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; let u = -1; do { bytes /= thresh; ++u; } while (Math.abs(bytes) >= thresh && u < units.length - 1); return bytes.toFixed(1) + ' ' + units[u]; }
import { ChangeDetectorRef, OnDestroy, Pipe, PipeTransform } from '@angular/core'; import { Subscription } from 'rxjs'; import { PermissionsService } from '../../providers/permissions/permissions.service'; /** * @description * A pipe which checks the provided permission against all the permissions of the current user. * Returns `true` if the current user has that permission. * * @example * ```HTML * <button [disabled]="!('UpdateCatalog' | hasPermission)">Save Changes</button> * ``` * @docsCategory pipes */ @Pipe({ name: 'hasPermission', pure: false, }) export class HasPermissionPipe implements PipeTransform, OnDestroy { private hasPermission = false; private lastPermissions: string | null = null; private subscription: Subscription; constructor( private permissionsService: PermissionsService, private changeDetectorRef: ChangeDetectorRef, ) {} transform(input: string | string[]): any { const requiredPermissions = Array.isArray(input) ? input : [input]; const requiredPermissionsString = requiredPermissions.join(','); if (this.lastPermissions !== requiredPermissionsString) { this.lastPermissions = requiredPermissionsString; this.hasPermission = false; this.dispose(); this.subscription = this.permissionsService.currentUserPermissions$.subscribe(() => { this.hasPermission = this.permissionsService.userHasPermissions(requiredPermissions); this.changeDetectorRef.markForCheck(); }); } return this.hasPermission; } ngOnDestroy() { this.dispose(); } private dispose() { if (this.subscription) { this.subscription.unsubscribe(); } } }
import { ChangeDetectorRef, Injectable, OnDestroy, PipeTransform } from '@angular/core'; import { Subscription } from 'rxjs'; import { DataService } from '../../data/providers/data.service'; /** * Used by locale-aware pipes to handle the task of getting the active languageCode * of the UI and cleaning up. */ @Injectable() export abstract class LocaleBasePipe implements OnDestroy, PipeTransform { protected locale: string; private readonly subscription: Subscription; protected 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(); }); } } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } /** * Returns the active locale after attempting to ensure that the locale string * is valid for the Intl API. */ protected getActiveLocale(localeOverride?: unknown): string { const locale = typeof localeOverride === 'string' ? localeOverride : this.locale ?? 'en'; const hyphenated = locale?.replace(/_/g, '-'); // Check for a double-region string, containing 2 region codes like // pt-BR-BR, which is invalid. In this case, the second region is used // and the first region discarded. This would only ever be an issue for // those languages where the translation file itself encodes the region, // as in pt_BR & pt_PT. const matches = hyphenated?.match(/^([a-zA-Z_-]+)(-[A-Z][A-Z])(-[A-Z][A-z])$/); if (matches?.length) { const overriddenLocale = matches[1] + matches[3]; return overriddenLocale; } else { return hyphenated; } } abstract transform(value: any, ...args): any; }
import { LocaleCurrencyNamePipe } from './locale-currency-name.pipe'; describe('LocaleCurrencyNamePipe', () => { const pipe = new LocaleCurrencyNamePipe(); it('full output', () => { expect(pipe.transform('usd')).toBe('US Dollar ($)'); expect(pipe.transform('gbp')).toBe('British Pound (£)'); expect(pipe.transform('CNY')).toBe('Chinese Yuan (CN¥)'); }); it('name output', () => { expect(pipe.transform('usd', 'name')).toBe('US Dollar'); expect(pipe.transform('gbp', 'name')).toBe('British Pound'); expect(pipe.transform('CNY', 'name')).toBe('Chinese Yuan'); }); it('symbol output', () => { expect(pipe.transform('usd', 'symbol')).toBe('$'); expect(pipe.transform('gbp', 'symbol')).toBe('£'); expect(pipe.transform('CNY', 'symbol')).toBe('CN¥'); }); it('uses locale', () => { expect(pipe.transform('usd', 'symbol', 'fr')).toBe('$US'); expect(pipe.transform('usd', 'name', 'de')).toBe('US-Dollar'); }); it('returns code for unknown codes', () => { expect(pipe.transform('zzz')).toBe('zzz (ZZZ)'); }); it('returns empty string for empty input', () => { expect(pipe.transform('')).toBe(''); expect(pipe.transform(null)).toBe(''); expect(pipe.transform(undefined)).toBe(''); }); it('returns warning for invalid input', () => { expect(pipe.transform({} as any)).toBe('Invalid currencyCode "[object Object]"'); expect(pipe.transform(false as any)).toBe('Invalid currencyCode "false"'); }); });
import { ChangeDetectorRef, Optional, Pipe, PipeTransform } from '@angular/core'; import { DataService } from '../../data/providers/data.service'; import { LocaleBasePipe } from './locale-base.pipe'; /** * @description * Displays a human-readable name for a given ISO 4217 currency code. * * @example * ```HTML * {{ order.currencyCode | localeCurrencyName }} * ``` * * @docsCategory pipes */ @Pipe({ name: 'localeCurrencyName', pure: false, }) export class LocaleCurrencyNamePipe extends LocaleBasePipe implements PipeTransform { constructor(@Optional() dataService?: DataService, @Optional() changeDetectorRef?: ChangeDetectorRef) { super(dataService, changeDetectorRef); } transform(value: any, display: 'full' | 'symbol' | 'name' = 'full', locale?: unknown): any { if (value == null || value === '') { return ''; } if (typeof value !== 'string') { return `Invalid currencyCode "${value as any}"`; } let name = ''; let symbol = ''; const activeLocale = this.getActiveLocale(locale); if (display === 'full' || display === 'name') { name = new Intl.DisplayNames([activeLocale], { type: 'currency', }).of(value) ?? ''; } if (display === 'full' || display === 'symbol') { const parts = ( new Intl.NumberFormat(activeLocale, { style: 'currency', currency: value, currencyDisplay: 'symbol', }) as any ).formatToParts(); symbol = parts.find(p => p.type === 'currency')?.value || value; } return display === 'full' ? `${name} (${symbol})` : display === 'name' ? name : symbol; } }
import { Injectable } from '@angular/core'; import { CurrencyService } from '@vendure/admin-ui/core'; import { CurrencyCode, LanguageCode } from '../../common/generated-types'; import { LocaleCurrencyPipe } from './locale-currency.pipe'; class MockCurrencyService extends CurrencyService { constructor(precision = 2) { super({ serverConfig: { moneyStrategyPrecision: precision, }, } as any); } } describe('LocaleCurrencyPipe', () => { it('GBP in English', () => { const pipe = new LocaleCurrencyPipe(new MockCurrencyService()); expect(pipe.transform(1, CurrencyCode.GBP, LanguageCode.en)).toBe('£0.01'); expect(pipe.transform(123, CurrencyCode.GBP, LanguageCode.en)).toBe('£1.23'); expect(pipe.transform(4200000, CurrencyCode.GBP, LanguageCode.en)).toBe('£42,000.00'); }); it('EUR in German', () => { const pipe = new LocaleCurrencyPipe(new MockCurrencyService()); expect(pipe.transform(1, CurrencyCode.EUR, LanguageCode.de)).toBe('0,01 €'); expect(pipe.transform(123, CurrencyCode.EUR, LanguageCode.de)).toBe('1,23 €'); expect(pipe.transform(4200000, CurrencyCode.EUR, LanguageCode.de)).toBe('42.000,00 €'); }); // https://github.com/vendure-ecommerce/vendure/issues/1768 it('Custom currency code in English', () => { const pipe = new LocaleCurrencyPipe(new MockCurrencyService()); const customCurrencyCode = 'FLTH'; expect(pipe.transform(1, customCurrencyCode, LanguageCode.en)).toBe('0.01'); expect(pipe.transform(123, customCurrencyCode, LanguageCode.en)).toBe('1.23'); expect(pipe.transform(4200000, customCurrencyCode, LanguageCode.en)).toBe('42000.00'); }); it('with precision 3', async () => { const pipe = new LocaleCurrencyPipe(new MockCurrencyService(3)); expect(pipe.transform(1, CurrencyCode.GBP, LanguageCode.en)).toBe('£0.001'); expect(pipe.transform(123, CurrencyCode.GBP, LanguageCode.en)).toBe('£0.123'); expect(pipe.transform(4200000, CurrencyCode.GBP, LanguageCode.en)).toBe('£4,200.000'); }); });
import { ChangeDetectorRef, Optional, Pipe, PipeTransform } from '@angular/core'; import { DataService } from '../../data/providers/data.service'; import { CurrencyService } from '../../providers/currency/currency.service'; import { LocaleBasePipe } from './locale-base.pipe'; /** * @description * Formats a Vendure monetary value (in cents) into the correct format for the configured currency and display * locale. * * @example * ```HTML * {{ variant.priceWithTax | localeCurrency }} * ``` * * @docsCategory pipes */ @Pipe({ name: 'localeCurrency', pure: false, }) export class LocaleCurrencyPipe extends LocaleBasePipe implements PipeTransform { readonly precisionFactor: number; constructor( private currencyService: CurrencyService, @Optional() dataService?: DataService, @Optional() changeDetectorRef?: ChangeDetectorRef, ) { super(dataService, changeDetectorRef); } transform(value: unknown, ...args: unknown[]): string | unknown { const [currencyCode, locale] = args; if (typeof value === 'number') { const activeLocale = this.getActiveLocale(locale); const majorUnits = this.currencyService.toMajorUnits(value); try { return new Intl.NumberFormat(activeLocale, { style: 'currency', currency: currencyCode as any, minimumFractionDigits: this.currencyService.precision, maximumFractionDigits: this.currencyService.precision, }).format(majorUnits); } catch (e: any) { return majorUnits.toFixed(this.currencyService.precision); } } return value; } }
import { LanguageCode } from '../../common/generated-types'; import { LocaleDatePipe } from './locale-date.pipe'; describe('LocaleDatePipe', () => { const testDate = new Date('2021-01-12T09:12:42'); it('medium format', () => { const pipe = new LocaleDatePipe(); expect(pipe.transform(testDate, 'medium', LanguageCode.en)).toBe('Jan 12, 2021, 9:12:42 AM'); }); it('mediumTime format', () => { const pipe = new LocaleDatePipe(); expect(pipe.transform(testDate, 'mediumTime', LanguageCode.en)).toBe('9:12:42 AM'); }); it('short format', () => { const pipe = new LocaleDatePipe(); expect(pipe.transform(testDate, 'short', LanguageCode.en)).toBe('1/12/21, 9:12 AM'); }); it('longDate format', () => { const pipe = new LocaleDatePipe(); expect(pipe.transform(testDate, 'longDate', LanguageCode.en)).toBe('January 12, 2021'); }); it('medium format German', () => { const pipe = new LocaleDatePipe(); expect(pipe.transform(testDate, 'medium', LanguageCode.de)).toBe('12. Jan. 2021, 9:12:42 AM'); }); it('medium format Chinese', () => { const pipe = new LocaleDatePipe(); expect(pipe.transform(testDate, 'medium', LanguageCode.zh)).toBe('2021年1月12日 上午9:12:42'); }); });
import { ChangeDetectorRef, Optional, Pipe, PipeTransform } from '@angular/core'; import { DataService } from '../../data/providers/data.service'; import { LocaleBasePipe } from './locale-base.pipe'; /** * @description * A replacement of the Angular DatePipe which makes use of the Intl API * to format dates according to the selected UI language. * * @example * ```HTML * {{ order.orderPlacedAt | localeDate }} * ``` * * @docsCategory pipes */ @Pipe({ name: 'localeDate', pure: false, }) export class LocaleDatePipe extends LocaleBasePipe implements PipeTransform { constructor(@Optional() dataService?: DataService, @Optional() changeDetectorRef?: ChangeDetectorRef) { super(dataService, changeDetectorRef); } transform(value: unknown, ...args: unknown[]): unknown { const [format, locale] = args; if (this.locale || typeof locale === 'string') { const activeLocale = this.getActiveLocale(locale); const date = value instanceof Date ? value : typeof value === 'string' ? new Date(value) : undefined; if (date) { const options = this.getOptionsForFormat(typeof format === 'string' ? format : 'medium'); return new Intl.DateTimeFormat(activeLocale, options).format(date); } } } private getOptionsForFormat(dateFormat: string): Intl.DateTimeFormatOptions | undefined { switch (dateFormat) { case 'medium': return { month: 'short', year: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true, }; case 'mediumTime': return { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true, }; case 'longDate': return { year: 'numeric', month: 'long', day: 'numeric', }; case 'shortDate': return { day: 'numeric', month: 'numeric', year: '2-digit', }; case 'short': return { day: 'numeric', month: 'numeric', year: '2-digit', hour: 'numeric', minute: 'numeric', hour12: true, }; default: return; } } }
import { LocaleLanguageNamePipe } from './locale-language-name.pipe'; describe('LocaleLanguageNamePipe', () => { const pipe = new LocaleLanguageNamePipe(); it('returns correct language names for various locales', () => { expect(pipe.transform('en', 'en')).toBe('English'); expect(pipe.transform('de', 'en')).toBe('German'); expect(pipe.transform('de', 'de')).toBe('Deutsch'); expect(pipe.transform('is', 'fr')).toBe('islandais'); expect(pipe.transform('es', 'zh_Hans')).toBe('西班牙语'); expect(pipe.transform('bs', 'zh_Hant')).toBe('波士尼亞文'); expect(pipe.transform('da', 'pt_BR')).toBe('dinamarquês'); expect(pipe.transform('zh_Hant', 'en')).toBe('Traditional Chinese'); }); it('return correct names for language plus region', () => { expect(pipe.transform('en-MY', 'en')).toBe('English (Malaysia)'); expect(pipe.transform('de-AT', 'de')).toBe('Österreichisches Deutsch'); expect(pipe.transform('zh_Hant-CN', 'en')).toBe('Traditional Chinese (China)'); }); it('returns code for unknown codes', () => { expect(pipe.transform('xx')).toBe('xx'); }); it('returns empty string for empty input', () => { expect(pipe.transform('')).toBe(''); expect(pipe.transform(null)).toBe(''); expect(pipe.transform(undefined)).toBe(''); }); it('returns warning for invalid input', () => { expect(pipe.transform({} as any)).toBe('Invalid language code "[object Object]"'); expect(pipe.transform(false as any)).toBe('Invalid language code "false"'); }); it('returns input value for invalid string input', () => { expect(pipe.transform('foo.bar')).toBe('foo.bar'); }); });
import { ChangeDetectorRef, Optional, Pipe, PipeTransform } from '@angular/core'; import { DataService } from '../../data/providers/data.service'; import { LocaleBasePipe } from './locale-base.pipe'; /** * @description * Displays a human-readable name for a given ISO 639-1 language code. * * @example * ```HTML * {{ 'zh_Hant' | localeLanguageName }} * ``` * * @docsCategory pipes */ @Pipe({ name: 'localeLanguageName', pure: false, }) export class LocaleLanguageNamePipe extends LocaleBasePipe implements PipeTransform { constructor(@Optional() dataService?: DataService, @Optional() changeDetectorRef?: ChangeDetectorRef) { super(dataService, changeDetectorRef); } transform(value: any, locale?: unknown): string { if (value == null || value === '') { return ''; } if (typeof value !== 'string') { return `Invalid language code "${value as any}"`; } const activeLocale = this.getActiveLocale(locale); // Awaiting TS types for this API: https://github.com/microsoft/TypeScript/pull/44022/files const DisplayNames = (Intl as any).DisplayNames; try { return new DisplayNames([activeLocale.replace('_', '-')], { type: 'language' }).of( value.replace('_', '-'), ); } catch (e: any) { return value; } } }
import { LocaleRegionNamePipe } from './locale-region-name.pipe'; describe('LocaleRegionNamePipe', () => { const pipe = new LocaleRegionNamePipe(); it('returns correct region names for various locales', () => { expect(pipe.transform('GB', 'en')).toBe('United Kingdom'); expect(pipe.transform('AT', 'en')).toBe('Austria'); expect(pipe.transform('AT', 'de')).toBe('Österreich'); expect(pipe.transform('CN', 'zh')).toBe('中国'); }); it('returns region for unknown codes', () => { expect(pipe.transform('xx')).toBe('xx'); }); it('returns empty string for empty input', () => { expect(pipe.transform('')).toBe(''); expect(pipe.transform(null)).toBe(''); expect(pipe.transform(undefined)).toBe(''); }); it('returns warning for invalid input', () => { expect(pipe.transform({} as any)).toBe('Invalid region code "[object Object]"'); expect(pipe.transform(false as any)).toBe('Invalid region code "false"'); }); it('returns input value for invalid string input', () => { expect(pipe.transform('foo.bar')).toBe('foo.bar'); }); });
import { ChangeDetectorRef, Optional, Pipe, PipeTransform } from '@angular/core'; import { DataService } from '../../data/providers/data.service'; import { LocaleBasePipe } from './locale-base.pipe'; /** * @description * Displays a human-readable name for a given region. * * @example * ```HTML * {{ 'GB' | localeRegionName }} * ``` * * @docsCategory pipes */ @Pipe({ name: 'localeRegionName', pure: false, }) export class LocaleRegionNamePipe extends LocaleBasePipe implements PipeTransform { constructor(@Optional() dataService?: DataService, @Optional() changeDetectorRef?: ChangeDetectorRef) { super(dataService, changeDetectorRef); } transform(value: any, locale?: unknown): string { if (value == null || value === '') { return ''; } if (typeof value !== 'string') { return `Invalid region code "${value as any}"`; } const activeLocale = this.getActiveLocale(locale); // Awaiting TS types for this API: https://github.com/microsoft/TypeScript/pull/44022/files const DisplayNames = (Intl as any).DisplayNames; try { return new DisplayNames([activeLocale.replace('_', '-')], { type: 'region' }).of( value.replace('_', '-'), ); } catch (e: any) { return value; } } }