repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
BirMa/components
projects/components/utils/public_api.ts
<reponame>BirMa/components<gh_stars>0 export { objectToKeyValueArray } from './src/object'; export { isInViewport } from './src/dom'; export { replaceAll } from './src/string'; export { AutoFormArray } from './src/auto-form-array';
BirMa/components
projects/components/select/src/defaults/default-select-service.spec.ts
<reponame>BirMa/components import { fakeAsync } from '@angular/core/testing'; import { Observable, of } from 'rxjs'; import { PsSelectItem } from '../models'; import { PsSelectDataSource } from '../select-data-source'; import { PsSelectLoadTrigger } from './default-select-data-source'; import { DefaultPsSelectService } from './default-select-service'; describe('DefaultPsSelectService', () => { it('should work with custom DataSource', fakeAsync(() => { class TestDataSource implements PsSelectDataSource { public loading: boolean; public error: any; public compareWith: () => true; public connect(): Observable<PsSelectItem<any>[]> { return of<PsSelectItem<any>[]>([ { label: 'test', value: 42, hidden: true, }, ]); } public disconnect(): void {} public panelOpenChanged(_: boolean): void {} public searchTextChanged(_: string): void {} public selectedValuesChanged(_: any): void {} public getItemsForValues(_: any[]): PsSelectItem<any>[] { return []; } } const service = new DefaultPsSelectService(); const inDataSource = new TestDataSource(); const dataSource = service.createDataSource(inDataSource, null); expect(dataSource).toBe(inDataSource); const renderOptions = getRenderData(dataSource); expect(renderOptions).toEqual([{ value: 42, label: 'test', hidden: true }]); })); it('should work with data object in entity mode', fakeAsync(() => { const service = new DefaultPsSelectService(); const item = { a: 1, b: 'item 1' }; const dataSource = service.createDataSource({ mode: 'entity', idKey: 'a', labelKey: 'b', items: [item] }, null); expectDataSourceOptions(dataSource, PsSelectLoadTrigger.initial, 300); expectEntityEqualComparer(dataSource, 'a'); expectEntityGetItemsForValues(dataSource, 'a', 'b'); const renderOptions = getRenderData(dataSource); expect(renderOptions).toEqual([createOption('item 1', item, item)]); })); it('should work with data object in id mode', fakeAsync(() => { const service = new DefaultPsSelectService(); const item = { a: 1, b: 'item 1' }; const dataSource = service.createDataSource({ mode: 'id', idKey: 'a', labelKey: 'b', items: [item] }, null); expectDataSourceOptions(dataSource, PsSelectLoadTrigger.initial, 300); expectStrictEqualComparer(dataSource); expectIdGetItemsForValues(dataSource); const renderOptions = getRenderData(dataSource); expect(renderOptions).toEqual([createOption('item 1', 1, item)]); })); it('should work with data observable and custom options', fakeAsync(() => { const service = new DefaultPsSelectService(); const item = { x: 1, y: 'item 1' }; const dataSource = service.createDataSource( { mode: 'entity', idKey: 'x', labelKey: 'y', items: of([item]), searchDebounce: 100, loadTrigger: PsSelectLoadTrigger.firstPanelOpen, }, null ); expectDataSourceOptions(dataSource, PsSelectLoadTrigger.firstPanelOpen, 100); expectEntityEqualComparer(dataSource, 'x'); expectEntityGetItemsForValues(dataSource, 'x', 'y'); const renderOptions = getRenderData(dataSource); expect(renderOptions).toEqual([createOption('item 1', item, item)]); })); it('should work with data array', fakeAsync(() => { const service = new DefaultPsSelectService(); const item = { value: 1, label: 'item 1' }; const dataSource = service.createDataSource([item], null); expectDataSourceOptions(dataSource, PsSelectLoadTrigger.initial, 300); expectStrictEqualComparer(dataSource); expectIdGetItemsForValues(dataSource); const renderOptions = getRenderData(dataSource); expect(renderOptions).toEqual([createOption('item 1', 1, item)]); })); it('should work with observable array', fakeAsync(() => { const service = new DefaultPsSelectService(); const item = { value: 1, label: 'item 1' }; const dataSource = service.createDataSource(of([item]), null); expectDataSourceOptions(dataSource, PsSelectLoadTrigger.initial, 300); expectStrictEqualComparer(dataSource); expectIdGetItemsForValues(dataSource); const renderOptions = getRenderData(dataSource); expect(renderOptions).toEqual([createOption('item 1', 1, item)]); })); it('should set disabled to value of item[disabledKey]', fakeAsync(() => { const service = new DefaultPsSelectService(); const item = { a: 1, b: 'item 1', d: true }; const dataSource = service.createDataSource({ mode: 'entity', idKey: 'a', labelKey: 'b', disabledKey: 'd', items: [item] }, null); const renderOptions = getRenderData(dataSource); expect(renderOptions).toEqual([createOption('item 1', item, item, false, true)]); })); }); function getRenderData(dataSource: PsSelectDataSource) { let currentRenderOptions; dataSource.connect().subscribe((options) => { currentRenderOptions = options; }); dataSource.panelOpenChanged(true); // Just in case the loadTrigger is not Initial dataSource.disconnect(); return currentRenderOptions; } function expectStrictEqualComparer(dataSource: PsSelectDataSource) { expect(dataSource.compareWith('item 1', 'item 1')).toBeTruthy(); expect(dataSource.compareWith(1, 1)).toBeTruthy(); const obj = { objectUuid: 1 }; expect(dataSource.compareWith(obj, obj)).toBeTruthy(); expect(dataSource.compareWith('item 1', 'item 2')).toBeFalsy(); expect(dataSource.compareWith(1, 2)).toBeFalsy(); expect(dataSource.compareWith({ objectUuid: 1 }, { objectUuid: 1 })).toBeFalsy(); } function expectEntityEqualComparer(dataSource: PsSelectDataSource, idKey: string) { expect(dataSource.compareWith('item 1', 'item 1')).toBeTruthy(); expect(dataSource.compareWith(1, 1)).toBeTruthy(); expect(dataSource.compareWith({ [idKey]: 1, [idKey + 'label']: 'asdf' }, { [idKey]: 1, [idKey + 'label']: 'ghjk' })).toBeTruthy(); expect(dataSource.compareWith('item 1', 'item 2')).toBeFalsy(); expect(dataSource.compareWith(1, 2)).toBeFalsy(); expect(dataSource.compareWith({ [idKey]: 1 }, { [idKey]: 2 })).toBeFalsy(); expect(dataSource.compareWith({ [idKey]: 1 }, 1)).toBeFalsy(); } function expectIdGetItemsForValues(dataSource: PsSelectDataSource) { // getItemsForValues must set the right value and label must contain at least the id const convertedValues = dataSource.getItemsForValues([42]); expect(convertedValues[0].value).toEqual(42); expect(convertedValues[0].label).toContain('42'); } function expectEntityGetItemsForValues(dataSource: PsSelectDataSource, idKey: string, labelKey: string) { const convertedValues = dataSource.getItemsForValues([{ [idKey]: 2, [labelKey]: 'label 2' }]); expect(convertedValues[0].value).toEqual({ [idKey]: 2, [labelKey]: 'label 2' }); expect(convertedValues[0].label).toContain('label 2'); } function expectDataSourceOptions(dataSource: any, loadTrigger: PsSelectLoadTrigger, debounceTime: number) { expect(dataSource._loadTrigger).toEqual(loadTrigger); expect(dataSource._searchDebounceTime).toEqual(debounceTime); } function createOption(label: string, value: any, entity: any, hidden = false, disabled = false): PsSelectItem { return { label: label, value: value, entity: entity, hidden: hidden, disabled: disabled, }; }
BirMa/components
projects/components/dialog-wrapper/src/dialog-wrapper.component.spec.ts
import { OverlayContainer } from '@angular/cdk/overlay'; import { HarnessLoader } from '@angular/cdk/testing'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { ChangeDetectionStrategy, Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { IPsButton, IPsException } from '@prosoft/components/core'; import { Observable, of, Subject } from 'rxjs'; import { IPsDialogWrapperDataSource } from './dialog-wrapper.models'; import { PsDialogWrapperModule } from './dialog-wrapper.module'; import { PsDialogWrapperHarness } from './testing/dialog-wrapper.harness'; interface ITestDialogWrapperDataSourceOptions { dialogTitle: string; actionFn: () => Observable<any>; cancelFn: () => void; } export class TestDialogWrapperDataSource implements IPsDialogWrapperDataSource { dialogTitle = this.options.dialogTitle; buttons: IPsButton[] = [ { label: 'Ok', type: 'raised', color: 'primary', disabled: () => false, click: () => this.confirm(), }, { label: 'Cancel', type: 'stroked', color: null, disabled: () => false, click: () => this.close(), }, ]; contentVisible: boolean; contentBlocked: boolean; exception: IPsException; public somethingChanged$ = new Subject<void>(); constructor(private options: ITestDialogWrapperDataSourceOptions) {} connect(): Observable<void> { return this.somethingChanged$; } disconnect(): void {} confirm() { return this.options.actionFn(); } close() { this.options.cancelFn(); } } @Component({ selector: 'ps-dialog-wrapper-dialog', template: ` <ps-dialog-wrapper [dataSource]="dataSource"> <span>dialogContent</span> </ps-dialog-wrapper> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class PsDialogWrapperTestDialog { dataSource = new TestDialogWrapperDataSource({ dialogTitle: 'MyDialogTitle', actionFn: () => this.actionFunction(), cancelFn: () => this.cancelFunction(), }); private _cancelFunctionCalled: number; constructor(public dialogRef: MatDialogRef<PsDialogWrapperTestDialog>) {} public actionFunction() { return of(); } public cancelFunction() { this._cancelFunctionCalled = this._cancelFunctionCalled + 1; this.dialogRef.close(); } } @Component({ selector: 'ps-dialog-wrapper-test', // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class PsDialogWrapperTestComponent { constructor(public dialog: MatDialog) {} public openDialog() { return this.dialog.open(PsDialogWrapperTestDialog); } } describe('DialogUnitTestComponent', () => { let component: PsDialogWrapperTestComponent; let fixture: ComponentFixture<PsDialogWrapperTestComponent>; let rootLoader: HarnessLoader; let overlayContainer: OverlayContainer; let dialogRef: MatDialogRef<PsDialogWrapperTestDialog>; let dialogWrapper: PsDialogWrapperHarness; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [BrowserAnimationsModule, MatDialogModule, PsDialogWrapperModule], declarations: [PsDialogWrapperTestDialog, PsDialogWrapperTestComponent], }).compileComponents(); fixture = TestBed.createComponent(PsDialogWrapperTestComponent); component = fixture.componentInstance; fixture.detectChanges(); rootLoader = TestbedHarnessEnvironment.documentRootLoader(fixture); overlayContainer = TestBed.inject(OverlayContainer); dialogRef = component.openDialog(); dialogWrapper = await rootLoader.getHarness(PsDialogWrapperHarness); }); afterEach(async () => { component.dialog.closeAll(); overlayContainer.ngOnDestroy(); }); it('should show the title from its given DataSource', async () => { expect(await dialogWrapper.getDialogTitle()).toEqual('MyDialogTitle'); }); it('should call actionFunction on ok click', async () => { spyOn(dialogRef.componentInstance, 'actionFunction').and.callThrough(); spyOn(dialogRef.componentInstance.dataSource, 'confirm').and.callThrough(); const btns = await dialogWrapper.getActionButtons({ text: 'Ok' }); expect(btns.length).toEqual(1); await btns[0].click(); expect(dialogRef.componentInstance.actionFunction).toHaveBeenCalledTimes(1); expect(dialogRef.componentInstance.dataSource.confirm).toHaveBeenCalledTimes(1); }); it('should call cancelFunction and then close on cancel click', async () => { const cancelSpy = spyOn(dialogRef.componentInstance, 'cancelFunction').and.callThrough(); const closeSpy = spyOn(dialogRef.componentInstance.dataSource, 'close').and.callThrough(); const btns = await dialogWrapper.getActionButtons({ text: 'Cancel' }); expect(btns.length).toEqual(1); await btns[0].click(); expect(cancelSpy).toHaveBeenCalledTimes(1); expect(closeSpy).toHaveBeenCalledTimes(1); expect((await rootLoader.getAllHarnesses(PsDialogWrapperHarness)).length).toEqual(0); }); it('should show errors', async () => { dialogRef.componentInstance.dataSource.exception = { errorObject: 'error 2', }; dialogRef.componentInstance.dataSource.somethingChanged$.next(); expect(await dialogWrapper.getError()).toEqual('error 2'); }); });
BirMa/components
projects/components/select/src/testing/select.harness.ts
/* eslint-disable @typescript-eslint/member-ordering */ import { BaseHarnessFilters, ComponentHarness, HarnessPredicate } from '@angular/cdk/testing'; import { MatCheckboxHarness } from '@angular/material/checkbox/testing'; import { MatOptionHarness, OptionHarnessFilters } from '@angular/material/core/testing'; import { MatFormFieldControlHarness } from '@angular/material/form-field/testing/control'; import { MatProgressSpinnerHarness } from '@angular/material/progress-spinner/testing'; import { MatSelectHarness } from '@angular/material/select/testing'; /** A set of criteria that can be used to filter a list of `MatSelectHarness` instances. */ // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface PsSelectHarnessFilters extends BaseHarnessFilters {} /** Harness for interacting with a standard mat-select in tests. */ export class PsSelectHarness extends MatFormFieldControlHarness { static hostSelector = 'ps-select'; private _matSelect = this.locatorFor(MatSelectHarness); private _documentRootLocator = this.documentRootLocatorFactory(); /** * Gets a `HarnessPredicate` that can be used to search for a `PsSelectHarness` that meets * certain criteria. * * @param options Options for filtering which select instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: PsSelectHarnessFilters = {}): HarnessPredicate<PsSelectHarness> { return new HarnessPredicate(PsSelectHarness, options); } /** Gets a boolean promise indicating if the select is disabled. */ async isDisabled(): Promise<boolean> { return (await this._matSelect()).isDisabled(); } /** Gets a boolean promise indicating if the select is valid. */ async isValid(): Promise<boolean> { return !(await (await this._matSelect()).isValid()); } /** Gets a boolean promise indicating if the select is required. */ async isRequired(): Promise<boolean> { return (await this._matSelect()).isRequired(); } /** Gets a boolean promise indicating if the select is empty (no value is selected). */ async isEmpty(): Promise<boolean> { return (await this._matSelect()).isEmpty(); } /** Gets a boolean promise indicating if the select is in multi-selection mode. */ async isMultiple(): Promise<boolean> { return (await this._matSelect()).isMultiple(); } /** Gets a promise for the select's value text. */ async getValueText(): Promise<string> { return (await this._matSelect()).getValueText(); } /** Focuses the select and returns a void promise that indicates when the action is complete. */ async focus(): Promise<void> { return (await this._matSelect()).focus(); } /** Blurs the select and returns a void promise that indicates when the action is complete. */ async blur(): Promise<void> { return (await this._matSelect()).blur(); } /** Whether the select is focused. */ async isFocused(): Promise<boolean> { return (await this._matSelect()).isFocused(); } /** Gets the options inside the select panel. */ async getOptions(filter: Omit<OptionHarnessFilters, 'ancestor'> = {}): Promise<MatOptionHarness[]> { const options = await (await this._matSelect()).getOptions(filter); const result = []; for (const option of options) { const host = await option.host(); if (await host.hasClass('ps-select__search')) { continue; } result.push(option); } return result; } // OptionGroups are not supported at the moment // /** Gets the groups of options inside the panel. */ // async getOptionGroups(filter: Omit<OptgroupHarnessFilters, 'ancestor'> = {}): Promise<MatOptgroupHarness[]> { // return (await this._matSelect()).getOptionGroups(filter); // } /** Gets whether the select is open. */ async isOpen(): Promise<boolean> { return (await this._matSelect()).isOpen(); } /** Opens the select's panel. */ async open(): Promise<void> { return (await this._matSelect()).open(); } /** * Clicks the options that match the passed-in filter. If the select is in multi-selection * mode all options will be clicked, otherwise the harness will pick the first matching option. */ async clickOptions(filter: OptionHarnessFilters = {}): Promise<void> { await this.open(); const [isMultiple, options] = await Promise.all([this.isMultiple(), this.getOptions(filter)]); if (options.length === 0) { throw Error('Select does not have options matching the specified filter'); } if (isMultiple) { await Promise.all(options.map((option) => option.click())); } else { await options[0].click(); } } /** Closes the select's panel. */ async close(): Promise<void> { return (await this._matSelect()).close(); } /** Gets a boolean promise indicating if the select is in the error state. */ async isErrorState(): Promise<boolean> { return await (await this.host()).hasClass('ps-select-invalid'); } /** Gets the option that clears the selected value. */ async getEmptyOption() { const options = await this.getOptions({ text: '--' }); for (const option of options) { if (await (await option.host()).hasClass('ps-select__empty-option')) { return option; } } return null; } /** Gets the option that shows the error message. */ async getErrorOption() { const options = await this.getOptions(); for (const option of options) { if (await (await option.host()).hasClass('ps-select__error')) { return option; } } return null; } /** Gets the panel header. */ async getPanelHeader() { return this._documentRootLocator.locatorFor( PsSelectPanelHeaderHarness.with({ ancestor: await this._getPanelSelector(), }) )(); } /** Gets the selector that should be used to find this select's panel. */ private async _getPanelSelector(): Promise<string> { const id = await (await (await this._matSelect()).host()).getAttribute('id'); return `#${id}-panel`; } } /** Harness for interacting with a `mat-option` in tests. */ export class PsSelectPanelHeaderHarness extends ComponentHarness { /** Selector used to locate option instances. */ static hostSelector = '.ps-select__search'; private _loadingSpinner = this.locatorForOptional(MatProgressSpinnerHarness); private _filter = this.locatorFor('input.mat-select-search-input.mat-input-element'); /** * Gets a `HarnessPredicate` that can be used to search for a `MatOptionsHarness` that meets * certain criteria. * * @param options Options for filtering which option instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: BaseHarnessFilters = {}) { return new HarnessPredicate(PsSelectPanelHeaderHarness, options); } /** Gets the toggle all checkbox. */ getToggleAll = this.locatorForOptional(MatCheckboxHarness); /** Gets the filter input. */ async setFilter(newValue: string) { const inputEl = await this._filter(); await inputEl.clear(); // We don't want to send keys for the value if the value is an empty // string in order to clear the value. Sending keys with an empty string // still results in unnecessary focus events. if (newValue) { await inputEl.sendKeys(newValue); } // Some input types won't respond to key presses (e.g. `color`) so to be sure that the // value is set, we also set the property after the keyboard sequence. Note that we don't // want to do it before, because it can cause the value to be entered twice. await inputEl.setInputValue(newValue); } /** Gets whether the loading spinner is shown. */ async isLoading() { const spinner = await this._loadingSpinner(); return !!spinner; } }
BirMa/components
projects/components/number-input/src/number-input.component.ts
/* eslint-disable @angular-eslint/no-conflicting-lifecycle */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { getLocaleNumberSymbol, NumberSymbol } from '@angular/common'; import type { ElementRef } from '@angular/core'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DoCheck, EventEmitter, Inject, Input, LOCALE_ID, OnChanges, OnDestroy, OnInit, Optional, Output, Self, ViewChild, ViewEncapsulation, } from '@angular/core'; import { ControlValueAccessor, FormGroupDirective, NgControl, NgForm } from '@angular/forms'; import { CanUpdateErrorState, ErrorStateMatcher, mixinErrorState } from '@angular/material/core'; import { MatFormFieldControl } from '@angular/material/form-field'; import { replaceAll } from '@prosoft/components/utils'; import { Subject } from 'rxjs'; let nextUniqueId = 0; // Boilerplate for applying mixins to PsNumberInput. /** @docs-private */ class PsNumberInputBase { constructor( public _defaultErrorStateMatcher: ErrorStateMatcher, public _parentForm: NgForm, public _parentFormGroup: FormGroupDirective, /** @docs-private */ public ngControl: NgControl ) {} } const psNumberInputMixinBase = mixinErrorState(PsNumberInputBase); /** Directive that allows a native input to work inside a `MatFormField`. */ // eslint-disable-next-line @angular-eslint/no-conflicting-lifecycle @Component({ selector: 'ps-number-input', templateUrl: './number-input.component.html', styleUrls: ['./number-input.component.scss'], // eslint-disable-next-line @angular-eslint/no-host-metadata-property host: { // Native input properties that are overwritten by Angular inputs need to be synced with // the native input element. Otherwise property bindings for those don't work. '[attr.id]': 'id', '[attr.placeholder]': 'placeholder', '[attr.disabled]': 'disabled', '[attr.required]': 'required', '[attr.readonly]': 'readonly || null', '[attr.aria-describedby]': '_ariaDescribedby || null', '[attr.aria-invalid]': 'errorState', '[attr.aria-required]': 'required.toString()', }, providers: [{ provide: MatFormFieldControl, useExisting: PsNumberInputComponent }], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class PsNumberInputComponent extends psNumberInputMixinBase implements ControlValueAccessor, MatFormFieldControl<any>, OnChanges, OnDestroy, OnInit, DoCheck, CanUpdateErrorState { /** Mininum boundary value. */ @Input() min: number; /** Maximum boundary value. */ @Input() max: number; /** Index of the element in tabbing order. */ @Input() tabindex: number; /** Number of allowed decimal places. */ @Input() decimals: number; /** Step factor to increment/decrement the value. */ @Input() get stepSize(): number { return this._stepSize; } set stepSize(val: number) { this._stepSize = val; if (this._stepSize != null) { const tokens = this.stepSize.toString().split(/[,]|[.]/); this._calculatedDecimals = tokens[1] ? tokens[1].length : undefined; } } _stepSize = 1; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ focused = false; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ override readonly stateChanges: Subject<void> = new Subject<void>(); /** * Implemented as part of MatFormFieldControl. * * @docs-private */ controlType = 'ps-number-input'; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ autofilled = false; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ @Input() get disabled(): boolean { if (this.ngControl && this.ngControl.disabled !== null) { return this.ngControl.disabled; } return this._disabled; } set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); this.stateChanges.next(); this.cd.markForCheck(); } protected _disabled = false; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ @Input() get id(): string { return this._id; } set id(value: string) { this._id = value || this._uid; } protected _id: string; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ @Input() placeholder: string; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ @Input() get required(): boolean { return this._required; } set required(value: boolean) { this._required = coerceBooleanProperty(value); this.cd.markForCheck(); } protected _required = false; /** An object used to control when error messages are shown. */ @Input() override errorStateMatcher: ErrorStateMatcher; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ @Input() get value(): number { return this._value; } set value(value: number) { if (value !== this.value) { this._value = value; this._formatValue(); this.stateChanges.next(); } } _value: number = null; @Output() public readonly valueChange = new EventEmitter<number>(); /** Whether the element is readonly. */ @Input() get readonly(): boolean { return this._readonly; } set readonly(value: boolean) { this._readonly = coerceBooleanProperty(value); this.cd.markForCheck(); } private _readonly = false; /** * Implemented as part of MatFormFieldControl. * * @docs-private */ get empty(): boolean { return (this._value === null || this._value === undefined) && !this.autofilled; } /** * Implemented as part of MatFormFieldControl. * * @docs-private */ get shouldLabelFloat(): boolean { return this.focused || !this.empty; } protected _uid = `ps-number-input-${nextUniqueId++}`; /** The aria-describedby attribute on the input for improved a11y. */ _ariaDescribedby: string; _formattedValue: string; _timer: any; _decimalSeparator: string; _thousandSeparator: string; _calculatedDecimals: number; @ViewChild('inputfield', { static: true }) _inputfieldViewChild: ElementRef<HTMLInputElement>; _onModelChange = (_val: any) => {}; _onModelTouched = () => {}; constructor( /** @docs-private */ @Optional() @Self() public override ngControl: NgControl, @Optional() _parentForm: NgForm, @Optional() _parentFormGroup: FormGroupDirective, _defaultErrorStateMatcher: ErrorStateMatcher, private cd: ChangeDetectorRef, @Inject(LOCALE_ID) private localeId: string ) { super(_defaultErrorStateMatcher, _parentForm, _parentFormGroup, ngControl); if (this.ngControl) { this.ngControl.valueAccessor = this; } } ngOnInit() { // Force setter to be called in case id was not specified. this.id = this.id; this._decimalSeparator = getLocaleNumberSymbol(this.localeId, NumberSymbol.Decimal); this._thousandSeparator = getLocaleNumberSymbol(this.localeId, NumberSymbol.Group); } ngOnChanges() { this.stateChanges.next(); } ngOnDestroy() { this._clearTimer(); this.stateChanges.complete(); } ngDoCheck() { if (this.ngControl) { // We need to re-evaluate this on every change detection cycle, because there are some // error triggers that we can't subscribe to (e.g. parent form submissions). This means // that whatever logic is in here has to be super lean or we risk destroying the performance. this.updateErrorState(); } } /** * Implemented as part of MatFormFieldControl. * * @docs-private */ setDescribedByIds(ids: string[]) { this._ariaDescribedby = ids.join(' '); } /** * Implemented as part of MatFormFieldControl. * * @docs-private */ onContainerClick() { if (!this.focused) { this.focus(); } } /** Focuses the input. */ focus(options?: FocusOptions): void { this._inputfieldViewChild.nativeElement.focus(options); } writeValue(value: any): void { this.value = value; } registerOnChange(fn: (val: any) => void): void { this._onModelChange = fn; } registerOnTouched(fn: () => void): void { this._onModelTouched = fn; } setDisabledState(val: boolean): void { this.disabled = val; } _repeat(event: Event, interval: number, dir: number) { const i = interval || 500; this._clearTimer(); this._timer = setTimeout(() => { this._repeat(event, 40, dir); }, i); this._spin(event, dir); } _clearTimer() { if (this._timer) { clearInterval(this._timer); } } _spin(_event: Event, dir: number) { const step = this.stepSize * dir; const newValue = this._fixNumber(this.value + step); this.value = newValue; this._onModelChange(newValue); this.valueChange.emit(newValue); } _parseValue(val: string): number { val = val.trim(); if (val === '') { return null; } val = replaceAll(val, this._thousandSeparator, ''); val = replaceAll(val, this._decimalSeparator, '.'); const value = this._fixNumber(parseFloat(val)); return value; } _formatValue() { const value: any = this.value; if (value == null) { this._formattedValue = null; } else { const decimals = this._getDecimals(); this._formattedValue = value.toLocaleString(this.localeId, { maximumFractionDigits: decimals }); } if (this._inputfieldViewChild && this._inputfieldViewChild.nativeElement) { this._inputfieldViewChild.nativeElement.value = this._formattedValue; } } _getDecimals() { return this.decimals === undefined ? this._calculatedDecimals : this.decimals; } _toFixed(value: number, decimals: number) { const power = Math.pow(10, decimals || 0); return String(Math.round(value * power) / power); } _fixNumber(value: number) { const decimals = this._getDecimals(); if (decimals) { value = parseFloat(this._toFixed(value, decimals)); } else { value = value >= 0 ? Math.floor(value) : Math.ceil(value); } if (isNaN(value)) { return null; } if (this.max !== null && value > this.max) { value = this.max; } if (this.min !== null && value < this.min) { value = this.min; } return value; } _onUpButtonMousedown(event: Event) { if (!this.disabled) { this._inputfieldViewChild.nativeElement.focus(); this._repeat(event, null, 1); event.preventDefault(); } } _onUpButtonMouseup(_event: Event) { if (!this.disabled) { this._clearTimer(); } } _onUpButtonMouseleave(_event: Event) { if (!this.disabled) { this._clearTimer(); } } _onDownButtonMousedown(event: Event) { if (!this.disabled) { this._inputfieldViewChild.nativeElement.focus(); this._repeat(event, null, -1); event.preventDefault(); } } _onDownButtonMouseup(_event: Event) { if (!this.disabled) { this._clearTimer(); } } _onDownButtonMouseleave(_event: Event) { if (!this.disabled) { this._clearTimer(); } } _onInputKeydown(event: KeyboardEvent) { // eslint-disable-next-line import/no-deprecated if (event.which === 38) { this._spin(event, 1); event.preventDefault(); } // eslint-disable-next-line import/no-deprecated else if (event.which === 40) { this._spin(event, -1); event.preventDefault(); } } _onInput(event: Event) { this._value = this._parseValue((<HTMLInputElement>event.target).value); this.stateChanges.next(); this._onModelChange(this.value); this.valueChange.emit(this.value); } /** Callback for the cases where the focused state of the input changes. */ _onFocusChanged(isFocused: boolean) { if (isFocused !== this.focused && (!this.readonly || !isFocused)) { this.focused = isFocused; this.stateChanges.next(); } if (!isFocused) { this._formatValue(); this._onModelTouched(); } } }
BirMa/components
projects/components/utils/src/auto-form-array.ts
import { AbstractControl, AbstractControlOptions, AsyncValidatorFn, FormArray, ValidatorFn } from '@angular/forms'; export class AutoFormArray extends FormArray { /** * Creates a new `FormArray` instance. * * @param controlGenerator A function that generates the control for en entry. * * @param validatorOrOpts A synchronous validator function, or an array of * such functions, or an `AbstractControlOptions` object that contains validation functions * and a validation trigger. * * @param asyncValidator A single async validator or array of async validator functions * */ constructor( private controlGenerator: () => AbstractControl, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null ) { super([], validatorOrOpts, asyncValidator); } public override patchValue( value: unknown[], options?: { onlySelf?: boolean; emitEvent?: boolean; } ): void { this.resizeTo(value ? value.length : 0); return super.patchValue(value, options); } public override reset( value?: { length: number }, options?: { onlySelf?: boolean; emitEvent?: boolean; } ): void { this.resizeTo(value ? value.length : 0); return super.reset(value, options); } public resizeTo(length: number) { while (this.length < length) { const newForm = this.controlGenerator(); if (this.disabled) { newForm.disable(); } this.push(newForm); } while (this.length > length) { this.removeAt(this.length - 1); } } }
BirMa/components
projects/prosoft-components-demo/src/app/form-demo/form-data-source-demo.component.ts
<gh_stars>0 import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core'; import { AbstractControl, FormControl, FormGroup } from '@angular/forms'; import { IPsButton, IPsException } from '@prosoft/components/core'; import { IPsFormDataSource, IPsFormDataSourceConnectOptions } from '@prosoft/components/form'; import { IPsSavebarMode } from '@prosoft/components/savebar'; import { BehaviorSubject, Observable, of, Subject, Subscription } from 'rxjs'; import { delay, map, take, tap } from 'rxjs/operators'; export interface PsFormDataSourceOptions<TParams, TData> { form: FormGroup; loadTrigger$: Observable<TParams>; loadFn: (params: TParams) => Observable<TData>; saveFn: (data: TData, params: TParams) => Observable<void>; } class DemoPsFormDataSource<TParams, TData> implements IPsFormDataSource { public autocomplete: 'off' = 'off'; public get form(): FormGroup { return this.options.form; } public buttons: IPsButton[] = []; public get contentVisible(): boolean { return !this._hasLoadError; } public get contentBlocked(): boolean { return this._loading || this._saving || this._blockView; } public exception: IPsException; public get savebarMode(): IPsSavebarMode { return this._hasLoadError ? 'hide' : 'auto'; } private _originalData: TData = null; private _loading = false; private _hasLoadError = false; private _saving = false; private _blockView = false; private _isEditMode = false; private _errorInView = false; private stateChanges$ = new Subject<void>(); private _loadParams: TParams = null; public _scrollToError: () => void; private buttonDefs = { scrollToError: { type: 'icon', icon: 'error_outline', color: 'warn', click: () => this._scrollToError() } as IPsButton, edit: { label: 'bearbeiten', type: 'raised', color: 'primary', disabled: () => this.contentBlocked, click: () => this.edit(), } as IPsButton, save: { label: 'speichern', type: 'raised', color: 'primary', disabled: () => this.contentBlocked || !this.form.valid, click: () => this.save(), } as IPsButton, cancel: { label: 'cancel', type: 'stroked', color: null, disabled: () => false, click: () => this.reset() } as IPsButton, }; private _loadingSub = Subscription.EMPTY; private _connectSub = Subscription.EMPTY; private _errorInViewSub = Subscription.EMPTY; constructor(private options: PsFormDataSourceOptions<TParams, TData>) {} public connect(options: IPsFormDataSourceConnectOptions): Observable<void> { this._scrollToError = () => setTimeout(() => options.scrollToError(), 0); // Warten bis der error gerendert ist this._errorInViewSub = options.errorInView$.subscribe((value) => { this._errorInView = value; this.updateButtons(); this.stateChanges$.next(); }); this._connectSub = this.options.loadTrigger$.subscribe((params) => { this._loadParams = params; this.loadData(params); }); return this.stateChanges$; } public disconnect(): void { this._connectSub.unsubscribe(); this._errorInViewSub.unsubscribe(); this._loadingSub.unsubscribe(); } public setViewBlocked(value: boolean) { this._blockView = value; this.stateChanges$.next(); } public edit(): void { this.setEditMode(true); } public save(): void { this._saving = true; this.exception = null; this.stateChanges$.next(); const formValue: TData = this.form.getRawValue(); this.options .saveFn(formValue, this._loadParams) .pipe(take(1)) .subscribe({ next: (_data) => { this.markDataSaved(); this.setEditMode(false); this._saving = false; this.stateChanges$.next(); }, error: (err) => { this._saving = false; this.exception = { errorObject: err, }; if (!this._errorInView) { this._scrollToError(); } this.updateButtons(); this.stateChanges$.next(); }, }); } public reset(): void { this.resetData(); this.setEditMode(false); this.stateChanges$.next(); } private loadData(params: TParams) { this._loadingSub.unsubscribe(); this._loading = true; this._hasLoadError = false; this.exception = null; this.initializeData(null); this.setEditMode(false); this.stateChanges$.next(); this._loadingSub = this.options .loadFn(params) .pipe(take(1)) .subscribe({ next: (data) => { this.initializeData(data); this._loading = false; this.stateChanges$.next(); }, error: (err) => { this._loading = false; this._hasLoadError = true; this.exception = { errorObject: err, alignCenter: true, icon: 'sentiment_very_dissatisfied', }; this.stateChanges$.next(); }, }); } private initializeData(data: TData) { if (data == null) { this.form.reset(); } else { this.form.patchValue(data); } this.markDataSaved(); } private markDataSaved() { this._originalData = this.form.getRawValue(); this.form.markAsPristine(); this.form.markAsUntouched(); } private resetData() { this.form.patchValue(this._originalData); this.form.markAsPristine(); this.form.markAsUntouched(); } private setEditMode(value: boolean) { this._isEditMode = value; if (value) { this.form.enable(); } else { this.form.disable(); } this.updateButtons(); } private updateButtons() { this.buttons = []; if (this.contentVisible) { if (!this._isEditMode) { this.buttons.push(this.buttonDefs.edit); } else { if (this.exception && !this._errorInView) { this.buttons.push(this.buttonDefs.scrollToError); } this.buttons.push(this.buttonDefs.save); this.buttons.push(this.buttonDefs.cancel); } } } } @Component({ selector: 'app-form-data-source-demo', template: ` <mat-card class="app-form-data-source-demo__settings"> <mat-checkbox [(ngModel)]="loadError">load error</mat-checkbox> <mat-checkbox [(ngModel)]="saveError">save error</mat-checkbox> <button mat-flat-button type="button" color="accent" (click)="reload()">reload</button> </mat-card> <div class="app-form-data-source-demo__grid"> <ps-form [dataSource]="dataSource"> <mat-card> <form [formGroup]="form"> <mat-form-field> <mat-label>Input 1</mat-label> <input type="text" matInput formControlName="input1" /> </mat-form-field> <mat-form-field> <mat-label>Input 2</mat-label> <input type="text" matInput formControlName="input2" /> </mat-form-field> </form> </mat-card> <mat-card style="height: 500px; margin-top: 1em;">dummy card</mat-card> <ng-container psFormSavebarButtons> <button mat-stroked-button type="button">dummy button 1</button> <button mat-stroked-button type="button">dummy button 2</button> </ng-container> </ps-form> <mat-card class="app-form-data-source-demo__logs"> <div *ngFor="let log of logs" class="app-form-data-source-demo__log-item">{{ log | json }}</div> </mat-card> </div> `, styles: [ ` .app-form-data-source-demo__settings { margin-bottom: 1em; } .app-form-data-source-demo__settings mat-checkbox { margin: 1em; } .app-form-data-source-demo__grid { display: grid; grid-template-columns: 2fr 1fr; grid-gap: 1em; } .app-form-data-source-demo__log-item { margin-bottom: 0.25em; padding-bottom: 0.25em; border-bottom: 1px solid #ccc; font-size: 0.95em; } app-form-demo .mat-form-field { display: block; } `, ], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class FormDataSourceDemoComponent { public loadError = false; public saveError = false; public form = new FormGroup( { input1: new FormControl('a'), input2: new FormControl('b'), }, [ (formGroup: AbstractControl) => formGroup.value.input1 === formGroup.value.input2 ? null : { equal: 'input1 and input2 must be equal' }, ] ); public counter = 0; public loadTrigger$ = new BehaviorSubject(this.counter); public logs: any[] = []; public dataSource = new DemoPsFormDataSource({ form: this.form, loadTrigger$: this.loadTrigger$, // could be route params in a real application loadFn: (count) => { this.logs.push({ type: 'load', params: count }); return of({ input1: 'input 1 load count ' + count, input2: 'input 2 load count ' + count, }).pipe( delay(1000), map((x) => { if (this.loadError) { throw new Error('this is the server error (loading)'); } return x; }) ); }, saveFn: (data, count) => { this.logs.push({ type: 'save', data: data, params: count }); return of(null).pipe( delay(1000), tap((x) => { if (this.saveError) { throw new Error('this is the server error (saving)'); } return x; }) ); }, }); public reload() { this.loadTrigger$.next(++this.counter); } }
BirMa/components
projects/components/table/src/models.ts
<reponame>BirMa/components<gh_stars>0 export interface IPsTableSortDefinition { prop: string; displayName: string; } export interface IPsTableUpdateDataInfo { currentPage: number | null; pageSize: number | null; searchText: string | null; sortDirection: 'asc' | 'desc' | null; sortColumn: string | null; } export interface IExtendedPsTableUpdateDataInfo<TTrigger> extends IPsTableUpdateDataInfo { currentPage: number; pageSize: number; triggerData: TTrigger; } export const enum PsTableActionScope { row = 1, list = 2, // eslint-disable-next-line no-bitwise all = row | list, } export interface IPsTableAction<T> { label: string; icon: string; isSvgIcon?: boolean; iconColor?: string; children?: IPsTableAction<T>[]; scope: PsTableActionScope; isDisabledFn?: (items: T[]) => boolean; isHiddenFn?: (items: T[]) => boolean; actionFn?: (items: T[]) => void; routerLink?: (item: T[]) => IPsTableActionRouterLink; } export interface IPsTableActionRouterLink { path: string[]; queryParams?: { [key: string]: any }; }
BirMa/components
projects/components/select/src/select.component.spec.ts
<gh_stars>0 import { HarnessLoader } from '@angular/cdk/testing'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Injectable, OnDestroy, QueryList, Type, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { AbstractControl, FormControl, FormGroup, FormGroupDirective, FormsModule, NgForm, ReactiveFormsModule, Validators, } from '@angular/forms'; import { ErrorStateMatcher } from '@angular/material/core'; import { MatOptionHarness, OptionHarnessFilters } from '@angular/material/core/testing'; import { MatFormFieldHarness } from '@angular/material/form-field/testing'; import { MatSelect } from '@angular/material/select'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { PsFormBaseModule } from '@prosoft/components/form-base'; import { PsFormFieldModule } from '@prosoft/components/form-field'; import { DemoPsFormsService } from 'projects/prosoft-components-demo/src/app/common/demo-ps-form-service'; import { Observable, of, ReplaySubject, Subject, Subscription, throwError } from 'rxjs'; import { DefaultPsSelectDataSource } from './defaults/default-select-data-source'; import { DefaultPsSelectService, PsSelectData } from './defaults/default-select-service'; import { PsSelectItem } from './models'; import { PsSelectDataSource } from './select-data-source'; import { PsSelectComponent } from './select.component'; import { PsSelectModule } from './select.module'; import { PsSelectService } from './select.service'; import { PsSelectHarness } from './testing/select.harness'; function createFakeMatSelect(): MatSelect { const matSelect = <any>{ value: null, stateChanges: new Subject<void>(), openedChange: new Subject<void>(), close: () => {}, _onChange: () => {}, _onTouched: null, ngControl: new FormControl(), options: new QueryList(), writeValue: () => {}, setDisabledState: () => {}, }; matSelect.writeValue = (val: any) => { matSelect.value = val; }; matSelect.registerOnChange = (val: any) => { matSelect._onChange = val; }; matSelect.registerOnTouched = (val: any) => { matSelect._onTouched = val; }; return matSelect; } function createFakeSelectService(): PsSelectService { const service = <PsSelectService>{ createDataSource: (ds: any) => ds, }; return service; } function createFakeDataSource(items: PsSelectItem[] = []): PsSelectDataSource { const dataSource = <PsSelectDataSource>{ connect: () => of<PsSelectItem[]>(items), disconnect: () => {}, selectedValuesChanged: (_: any | any[]) => {}, panelOpenChanged: (_: boolean) => {}, searchTextChanged: (_: string) => {}, }; return dataSource; } function createPsSelect(options?: { dataSource?: PsSelectDataSource; service: PsSelectService }) { const matSelect = createFakeMatSelect(); const dataSource = options?.dataSource ?? createFakeDataSource(); const service = options?.service ?? createFakeSelectService(); const component = new PsSelectComponent({ nativeElement: {} }, null, service, <any>{ markForCheck: () => {} }, null, null, <any>{ control: null, }); component.setMatSelect = matSelect; component.dataSource = dataSource; return { component: component, matSelect: matSelect, service: service, dataSource: dataSource }; } @Component({ selector: 'ps-test-component', template: ` <div [formGroup]="form"> <ps-select formControlName="select" [dataSource]="dataSource" [errorStateMatcher]="errorStateMatcher" [panelClass]="panelClass" [clearable]="clearable" ></ps-select> </div> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestComponent implements OnDestroy { dataSource: any = [ITEMS.red, ITEMS.green, ITEMS.blue]; control = new FormControl(null, [Validators.required]); form = new FormGroup({ select: this.control, }); emittedValues: any[] = []; errorStateMatcher: ErrorStateMatcher = null; panelClass: { [key: string]: boolean } = {}; clearable = true; @ViewChild(PsSelectComponent, { static: true }) select: PsSelectComponent; private valuesSubscription: Subscription; constructor() { this.valuesSubscription = this.form.get('select').valueChanges.subscribe((value) => { this.emittedValues.push(value); }); } ngOnDestroy() { this.valuesSubscription.unsubscribe(); } } const ITEMS = { red: { value: 'red', label: 'Red' }, green: { value: 'green', label: 'Green' }, blue: { value: 'blue', label: 'Blue' }, }; @Component({ selector: 'ps-test-multiple-component', template: ` <ps-select [(ngModel)]="value" [dataSource]="dataSource" [multiple]="true" [showToggleAll]="showToggleAll"></ps-select> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestMultipleComponent { showToggleAll = true; dataSource: any = [ITEMS.red, ITEMS.green, ITEMS.blue]; value: any = null; @ViewChild(PsSelectComponent, { static: true }) select: PsSelectComponent; constructor(public cd: ChangeDetectorRef) {} } @Component({ selector: 'ps-test-value', template: `<ps-select [(value)]="value" [dataSource]="items"></ps-select>`, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestValueComponent { public items = [ITEMS.red, ITEMS.green, ITEMS.blue]; public value: any = null; } @Component({ selector: 'ps-test-custom-template', template: ` <ps-select [(value)]="value" [dataSource]="items"> <ng-container *psSelectTriggerTemplate="let item"> trigger:{{ item.value }}:<span [style.color]="item.value">{{ item.viewValue }}</span> </ng-container> <ng-container *psSelectOptionTemplate="let item"> <div>color:</div> <div>{{ item.value }}:</div> <div [style.color]="item.value">{{ item.label }}</div> </ng-container> </ps-select> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestCustomTemplateComponent { public items = [ITEMS.red, ITEMS.green, ITEMS.blue]; public value: any = null; } @Component({ selector: 'ps-test-with-form-field', template: ` <ps-form-field> <mat-label>My Select</mat-label> <ps-select [(ngModel)]="value" [dataSource]="dataSource" [clearable]="clearable"></ps-select> </ps-form-field> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestWithFormFieldComponent { public dataSource: any = [ITEMS.red, ITEMS.green, ITEMS.blue]; public value: any = null; public clearable = false; } @Injectable() export class TestPsSelectService extends DefaultPsSelectService { static calledwith: { dataSource: any; control: AbstractControl }[] = []; public override createDataSource<T>(dataSource: PsSelectData<T>, control: AbstractControl | null): PsSelectDataSource<T> { TestPsSelectService.calledwith.push({ dataSource: dataSource, control: control }); return super.createDataSource(dataSource, control); } } async function initTest<T>( type: Type<T>, additionalImports: any[] = [], additionalDeclarations: any[] = [] ): Promise<{ fixture: ComponentFixture<T>; component: T; loader: HarnessLoader; psSelect: PsSelectHarness }> { TestPsSelectService.calledwith = []; await TestBed.configureTestingModule({ imports: [NoopAnimationsModule, PsSelectModule.forRoot(TestPsSelectService), FormsModule, ReactiveFormsModule, ...additionalImports], declarations: [TestComponent, TestMultipleComponent, TestCustomTemplateComponent, TestValueComponent, ...additionalDeclarations], }); const fixture = TestBed.createComponent(type); const component = fixture.componentInstance; expect(component).toBeDefined(); const loader = TestbedHarnessEnvironment.loader(fixture); return { fixture: fixture, component: component, loader: loader, psSelect: await loader.getHarness(PsSelectHarness), }; } describe('PsSelectComponent', () => { it('should use right default values', () => { const { component } = createPsSelect(); expect(component.clearable).toBe(true); expect(component.showToggleAll).toBe(true); expect(component.multiple).toBe(false); expect(component.errorStateMatcher).toBe(null); expect(component.panelClass).toBe(null); expect(component.placeholder).toBe(null); expect(component.required).toBe(false); expect(component.disabled).toBe(false); }); it('should determine empty value correctly', () => { const { component } = createPsSelect(); component.multiple = true; const items = [ { value: 1, label: 'i1', hidden: false }, { value: 2, label: 'i2', hidden: false }, ]; component.dataSource = createFakeDataSource(items); component.value = null; expect(component.empty).toBe(true); component.value = []; expect(component.empty).toBe(true); component.value = [items[0]]; expect(component.empty).toBe(false); component.value = items; expect(component.empty).toBe(false); component.multiple = false; component.value = null; expect(component.empty).toBe(true); component.value = {}; expect(component.empty).toBe(false); component.value = ''; expect(component.empty).toBe(true); component.value = 'some value'; expect(component.empty).toBe(false); }); it('should update floating label state', async () => { const { component, psSelect, loader } = await initTest( TestWithFormFieldComponent, [PsFormFieldModule, PsFormBaseModule.forRoot(DemoPsFormsService)], [TestWithFormFieldComponent] ); const matFormField = await loader.getHarness(MatFormFieldHarness); component.value = ITEMS.red; component.clearable = true; await psSelect.open(); expect(await psSelect.isEmpty()).toBe(false); expect(await matFormField.isLabelFloating()).toBe(true); await psSelect.close(); expect(await psSelect.isEmpty()).toBe(false); expect(await matFormField.isLabelFloating()).toBe(true); await psSelect.open(); await (await psSelect.getEmptyOption()).click(); expect(await psSelect.isEmpty()).toBe(true); expect(await matFormField.isLabelFloating()).toBe(false); await psSelect.open(); await psSelect.close(); // see https://github.com/prosoft-edv/components/issues/139 expect(await matFormField.isLabelFloating()).toBe(false); }); it('should fix MatSelect.close() not emitting stateChanges', fakeAsync(() => { const matSelect = createFakeMatSelect(); const { component } = createPsSelect(); component.setMatSelect = matSelect; spyOn(matSelect.stateChanges, 'next'); matSelect.close(); expect(matSelect.stateChanges.next).toHaveBeenCalled(); })); it('should update disabled property when calling setDisabledState', () => { const { component } = createPsSelect(); component.disabled = true; component.setDisabledState(false); expect(component.disabled).toBe(false); component.setDisabledState(true); expect(component.disabled).toBe(true); }); it("should not switch dataSource when dataSource input doesn't change", async () => { const { component, service } = createPsSelect(); const items = [{ value: 1, label: 'i1', hidden: false }]; const ds = createFakeDataSource(items); spyOn(service, 'createDataSource').and.returnValue(ds); component.dataSource = 'a'; component.ngOnInit(); expect(service.createDataSource).toHaveBeenCalledTimes(1); component.dataSource = 'lookup'; expect(service.createDataSource).toHaveBeenCalledTimes(2); component.dataSource = 'lookup'; expect(service.createDataSource).toHaveBeenCalledTimes(2); expect(component.items).toEqual(items); expect(component.dataSource).toBe(ds); }); it('should work with ngModel', async () => { const { component, psSelect } = await initTest(TestMultipleComponent); await psSelect.clickOptions({ text: ITEMS.green.label }); expect(component.value).toEqual([ITEMS.green.value]); }); it('should work with value binding', async () => { const { component, psSelect } = await initTest(TestValueComponent); await psSelect.clickOptions({ text: ITEMS.red.label }); expect(component.value).toEqual(ITEMS.red.value); }); it('should emit only once when selecting an option', async () => { const { component, psSelect } = await initTest(TestComponent); await psSelect.clickOptions({ text: ITEMS.green.label }); await psSelect.clickOptions({ text: '--' }); expect(component.emittedValues).toEqual([ITEMS.green.value, undefined]); }); it('should use the error state matcher input', async () => { const { component, psSelect } = await initTest(TestComponent); // Default matcher component.control.patchValue(null); expect(await psSelect.isErrorState()).toBe(false); // Custom matcher - empty value component.errorStateMatcher = { isErrorState: (control: FormControl | null, _form: FormGroupDirective | NgForm | null): boolean => !!(control && control.invalid), }; expect(await psSelect.isErrorState()).toBe(true); // Custom matcher - item 1 component.control.patchValue(1); expect(await psSelect.isErrorState()).toBe(false); }); it('should use clearable input', async () => { const { component, psSelect } = await initTest(TestComponent); component.clearable = true; await psSelect.open(); expect(await psSelect.getEmptyOption()).toBeTruthy(); component.clearable = false; expect(await psSelect.getEmptyOption()).toBeFalsy(); }); it('toggle all functionality should work', async () => { const { component, psSelect } = await initTest(TestMultipleComponent); component.showToggleAll = true; await psSelect.open(); const selectSearch = await psSelect.getPanelHeader(); const toggle = await selectSearch.getToggleAll(); expect(await getOptionIsSelected(psSelect)).toEqual([false, false, false]); await toggle.check(); expect(await getOptionIsSelected(psSelect)).toEqual([true, true, true]); await toggle.uncheck(); expect(await getOptionIsSelected(psSelect)).toEqual([false, false, false]); const options = await psSelect.getOptions(); await last(options).click(); expect(await getOptionIsSelected(psSelect)).toEqual([false, false, true]); expect(await toggle.isIndeterminate()).toBe(true); await toggle.check(); expect(await getOptionIsSelected(psSelect)).toEqual([true, true, true]); component.showToggleAll = false; expect(await selectSearch.getToggleAll()).toBeFalsy(); }); it('should set the right css classes', async () => { const { fixture, component, psSelect } = await initTest(TestComponent); let errorState = false; component.errorStateMatcher = { isErrorState: (_control: FormControl | null, _form: FormGroupDirective | NgForm | null): boolean => errorState, }; await psSelect.open(); // Empty assertPsSelectCssClasses(fixture, ['ps-select', 'ps-select-empty']); // Item selected const options = await psSelect.getOptions(); await last(options).click(); fixture.detectChanges(); assertPsSelectCssClasses(fixture, ['ps-select']); // Disabled component.control.disable(); fixture.detectChanges(); assertPsSelectCssClasses(fixture, ['ps-select', 'ps-select-disabled']); component.control.enable(); // Invalid errorState = true; fixture.detectChanges(); assertPsSelectCssClasses(fixture, ['ps-select', 'ps-select-invalid']); errorState = false; // Required component.select.required = true; fixture.detectChanges(); assertPsSelectCssClasses(fixture, ['ps-select', 'ps-select-required']); component.select.required = false; // mat-option component.panelClass = { 'custom-mat-option-class': true }; fixture.detectChanges(); const matSelectTrigger = fixture.debugElement.query(By.css('.mat-select-trigger')); matSelectTrigger.triggerEventHandler('click', new Event('click')); fixture.detectChanges(); // select panel const selectPanelNode = document.querySelector('.mat-select-panel'); expect(selectPanelNode).not.toBeNull(); expect(selectPanelNode.classList).toContain('custom-mat-option-class'); const matOptionNodes = selectPanelNode.querySelectorAll('mat-option'); // mat-select-search expect(matOptionNodes.item(0).classList.contains('mat-option-disabled')).toBeTruthy(); expect(matOptionNodes.item(0).classList.contains('ps-select__search')).toBeTruthy(); // empty input expect(matOptionNodes.item(1).classList.contains('ps-select__empty-option')).toBeTruthy(); // items expect(matOptionNodes.item(2).classList.contains('ps-select__option')).toBeTruthy(); }); it('should set multiple css class for multiple mode', async () => { const { fixture } = await initTest(TestMultipleComponent); const classes = getPsSelectCssClasses(fixture); expect(classes).toContain('ps-select-multiple'); }); it('should work with custom templates', async () => { const { fixture } = await initTest(TestCustomTemplateComponent); const matSelectTrigger = fixture.debugElement.query(By.css('.mat-select-trigger')); matSelectTrigger.triggerEventHandler('click', new Event('click')); fixture.detectChanges(); // mat-option text const selectPanelNode = document.querySelector('.mat-select-panel'); const matOptionNodes = selectPanelNode.querySelectorAll('mat-option'); const itemNode = matOptionNodes.item(2); expect(itemNode.textContent.trim()).toEqual('color:blue:Blue'); // select the mat-option itemNode.dispatchEvent(new Event('click')); fixture.detectChanges(); // trigger text expect(matSelectTrigger.nativeElement.textContent.trim()).toEqual('trigger:blue:color:blue:Blue'); // static trigger text + value + mat-option viewValue }); it('should disable matOption for item with disable', async () => { const { component, psSelect } = await initTest(TestMultipleComponent); component.dataSource = new DefaultPsSelectDataSource({ mode: 'id', labelKey: 'label', idKey: 'value', disabledKey: 'disabled', items: [ { label: 'disabled', value: 1, disabled: true }, { label: 'active', value: 2, disabled: false }, { label: 'default', value: 3 }, ], }); await psSelect.open(); expect(await (await psSelect.getOptions({ text: 'disabled' }))[0].isDisabled()).toBeTruthy(); expect(await (await psSelect.getOptions({ text: 'active' }))[0].isDisabled()).toBeFalsy(); expect(await (await psSelect.getOptions({ text: 'default' }))[0].isDisabled()).toBeFalsy(); }); it('should take DataSource compareWith function', async () => { const { component, psSelect } = await initTest(TestComponent); component.dataSource = new DefaultPsSelectDataSource({ mode: 'id', labelKey: 'label', idKey: 'value', items: [ { label: '1', value: 1 }, { label: '2', value: 2 }, ], }); let calledCount = 0; component.dataSource.compareWith = (a: any, b: any) => { ++calledCount; return a === 1 && b === 2; }; component.control.patchValue(2); await psSelect.open(); const optionTexts = await getOptionData(psSelect, (o) => o.getText(), { isSelected: true }); expect(optionTexts).toEqual(['1']); expect(calledCount).toBeGreaterThan(0); }); it('should switch to new dataSource when new dataSource is set', async () => { const { fixture, component, psSelect } = await initTest(TestComponent); TestPsSelectService.calledwith = []; component.dataSource = new DefaultPsSelectDataSource({ mode: 'id', labelKey: 'label', idKey: 'value', items: [ { label: '1', value: 1 }, { label: '2', value: 2 }, ], }); component.control.patchValue(2); fixture.detectChanges(); expect(TestPsSelectService.calledwith.length).toBe(1); expect(TestPsSelectService.calledwith[0].dataSource).toBe(component.dataSource); expect(TestPsSelectService.calledwith[0].control).toBe(component.control); await psSelect.open(); const selectSearch = await psSelect.getPanelHeader(); { await selectSearch.setFilter('2'); const optionTexts = await getOptionData(psSelect, (o) => o.getText(), { isSelected: true }); expect(optionTexts).toEqual(['2']); } { component.dataSource = new DefaultPsSelectDataSource({ mode: 'id', labelKey: 'label', idKey: 'value', items: [ { label: '3', value: 3 }, { label: '1', value: 1 }, // selected label missing ], }); fixture.detectChanges(); expect(TestPsSelectService.calledwith.length).toBe(2); expect(TestPsSelectService.calledwith[1].dataSource).toBe(component.dataSource); expect(TestPsSelectService.calledwith[1].control).toBe(component.control); const selectedOptionTexts = await getOptionData(psSelect, (o) => o.getText(), { isSelected: true }); expect(selectedOptionTexts.length).toBe(1); expect(selectedOptionTexts[0]).toContain('???'); // missing options got created const options1 = await psSelect.getOptions({ text: '1' }); expect(await (await options1[0].host()).hasClass('ps-select__option--hidden')).toBe(true); // filter got applied const optionTexts = await getOptionData(psSelect, (o) => o.getText()); // sorting is correct expect(optionTexts[0]).toContain('2'); expect(optionTexts[1]).toBe('1'); expect(optionTexts[2]).toBe('3'); } }); it('should show load errors as disabled option, but still show selected option', async () => { const { fixture, component, psSelect } = await initTest(TestComponent); component.dataSource = new DefaultPsSelectDataSource({ mode: 'id', labelKey: 'label', idKey: 'value', items: () => throwError('my error'), }); component.control.patchValue(2); fixture.detectChanges(); await psSelect.open(); let options = await psSelect.getOptions(); expect(options.length).toBe(3); expect(await options[0].getText()).toBe('my error'); expect(await options[0].isDisabled()).toBe(true); expect(await options[1].getText()).toBe('--'); expect(await options[1].isDisabled()).toBe(false); expect(await options[2].getText()).toContain('2'); expect(await options[2].isDisabled()).toBe(false); expect(await options[2].isSelected()).toBe(true); await options[1].click(); await psSelect.open(); options = await psSelect.getOptions(); expect(options.length).toBe(1); expect(await options[0].getText()).toBe('my error'); expect(await options[0].isDisabled()).toBe(true); }); it('should show loading spinner while loading and open', async () => { const { component, psSelect } = await initTest(TestComponent); const items$ = new ReplaySubject(1); component.dataSource = new DefaultPsSelectDataSource({ mode: 'id', labelKey: 'label', idKey: 'value', items: () => items$ as Observable<any>, }); await psSelect.open(); const header = await psSelect.getPanelHeader(); expect(await header.isLoading()).toBe(true); items$.next([]); await delay(); // the datasource debounces the items... expect(await header.isLoading()).toBe(false); items$.complete(); }); }); async function getOptionIsSelected(psSelect: PsSelectHarness) { return getOptionData(psSelect, (o) => o.isSelected()); } async function getOptionData<T>( psSelect: PsSelectHarness, transform: (option: MatOptionHarness) => Promise<T>, filter?: Omit<OptionHarnessFilters, 'ancestor'> ) { const options = await psSelect.getOptions(filter); return Promise.all(options.map((o) => transform(o))); } function getPsSelectCssClasses(fixture: ComponentFixture<any>) { const testComponentElement: HTMLElement = fixture.nativeElement; const classes = testComponentElement .querySelector('ps-select') .className.split(' ') .filter((x) => x.startsWith('ps-')) .sort(); return classes; } function assertPsSelectCssClasses(fixture: ComponentFixture<any>, exprectedClasses: string[]) { const classes = getPsSelectCssClasses(fixture); expect(classes).toEqual(exprectedClasses.sort()); } function last<T>(a: T[]): T { return a[a.length - 1]; } function delay(duration = 0) { return new Promise<void>((resolve, _) => { setTimeout(() => { resolve(); }, duration); }); }
BirMa/components
projects/prosoft-components-demo/src/app/number-input-demo/number-input-demo.component.ts
import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { ErrorStateMatcher } from '@angular/material/core'; @Component({ selector: 'app-number-input-demo', template: ` <mat-card> <h1>ps-slider</h1> <div class="app-number-input-demo__settings"> <div class="app-number-input-demo__checkboxes"> <mat-checkbox [(ngModel)]="disabled" (change)="onDisabledChanged()">disabled</mat-checkbox> <mat-checkbox [(ngModel)]="readonly">readonly</mat-checkbox> <mat-checkbox [(ngModel)]="required">required</mat-checkbox> <mat-checkbox [(ngModel)]="validatorRequired" (change)="onValidatorChange()">required validator</mat-checkbox> <mat-checkbox [(ngModel)]="useErrorStateMatcher" (change)="onUseErrorStateMatcherChange()" >errorStateMatcher (always invalid)</mat-checkbox > </div> <ps-form-field> <mat-label>min value</mat-label> <input matInput type="number" [(ngModel)]="min" /> </ps-form-field> <ps-form-field> <mat-label>max value</mat-label> <input matInput type="number" [(ngModel)]="max" /> </ps-form-field> <ps-form-field> <mat-label>step size</mat-label> <input matInput type="number" [(ngModel)]="stepSize" /> </ps-form-field> <ps-form-field> <mat-label>decimals</mat-label> <input matInput type="number" [(ngModel)]="decimals" /> </ps-form-field> <ps-form-field> <mat-label>placeholder</mat-label> <input matInput type="text" [(ngModel)]="placeholder" /> </ps-form-field> <button type="button" mat-stroked-button (click)="setValues(null)">set values null</button> <button type="button" mat-stroked-button (click)="recreate()">recreate slider</button> </div> <ng-container *ngIf="show"> <div class="app-number-input-demo__input-block"> <ps-form-field [hint]="'Value: ' + value"> <mat-label>value</mat-label> <ps-number-input [min]="min" [max]="max" [stepSize]="stepSize" [decimals]="decimals" [placeholder]="placeholder" [required]="required" [disabled]="disabled" [readonly]="readonly" [errorStateMatcher]="errorStateMatcher" [(value)]="value" ></ps-number-input> </ps-form-field> Code: <pre class="app-number-input-demo__code">{{ getCodeSnippet('value') }}</pre> </div> <div class="app-number-input-demo__input-block"> <ps-form-field [hint]="'Value: ' + model"> <mat-label>ngModel</mat-label> <ps-number-input [min]="min" [max]="max" [stepSize]="stepSize" [decimals]="decimals" [placeholder]="placeholder" [required]="required" [disabled]="disabled" [readonly]="readonly" [errorStateMatcher]="errorStateMatcher" [(ngModel)]="model" ></ps-number-input> </ps-form-field> Code: <pre class="app-number-input-demo__code">{{ getCodeSnippet('ngmodel') }}</pre> </div> <div class="app-number-input-demo__input-block" [formGroup]="form"> <ps-form-field [hint]="'Value: ' + form.get('control').value"> <mat-label>form</mat-label> <ps-number-input [min]="min" [max]="max" [stepSize]="stepSize" [decimals]="decimals" [placeholder]="placeholder" [required]="required" [disabled]="disabled" [readonly]="readonly" [errorStateMatcher]="errorStateMatcher" formControlName="control" ></ps-number-input> </ps-form-field> Code: <pre class="app-number-input-demo__code">{{ getCodeSnippet('form') }}</pre> </div> </ng-container> </mat-card> `, styles: [ ` .app-number-input-demo__settings { margin-bottom: 2em; } .app-number-input-demo__checkboxes { display: flex; } .app-number-input-demo__checkboxes mat-checkbox { margin-right: 1em; } .app-number-input-demo__input-block { border: 1px solid #ccc; margin: 0.5em 0; padding: 1em; } .app-number-input-demo__code { margin-bottom: 0; } `, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class NumberInputDemoComponent { public value = 5; public model = 5; public control = new FormControl(5); public form = new FormGroup({ control: this.control, }); public show = true; public min = 0; public max = 20; public stepSize = 1; public decimals = 1; public placeholder = ''; public required = false; public disabled = false; public readonly = false; public errorStateMatcher: ErrorStateMatcher = null; public validatorRequired = false; public useErrorStateMatcher = false; constructor(private cd: ChangeDetectorRef) {} public onValidatorChange() { const validators = []; if (this.validatorRequired) { validators.push(Validators.required); } this.control.setValidators(validators); } public onUseErrorStateMatcherChange() { if (this.useErrorStateMatcher) { this.errorStateMatcher = { isErrorState: () => true, }; } else { this.errorStateMatcher = null; } } public setValues(value: number) { this.value = value; this.model = value; this.control.patchValue(value); } public onDisabledChanged() { if (this.disabled) { this.form.disable(); } else { this.form.enable(); } } public recreate() { this.show = false; setTimeout(() => { this.show = true; this.cd.markForCheck(); }); } public getCodeSnippet(type: 'value' | 'ngmodel' | 'form') { let valueBinding; if (type === 'value') { valueBinding = '[(value)]="value"'; } else if (type === 'ngmodel') { valueBinding = '[(ngModel)]="value"'; } else { valueBinding = 'formControlName="control"'; } return ` <ps-number-input [min]="${this.min}" [max]="${this.max}" [stepSize]="${this.stepSize}" [decimals]="${this.decimals}" [placeholder]="${this.placeholder}" [required]="${this.required}" [disabled]="${this.disabled}" [readonly]="${this.readonly}" [errorStateMatcher]="${ this.errorStateMatcher ? 'errorStateMatcher' : 'null' }" ${valueBinding} ></ps-number-input>`; } }
BirMa/components
projects/prosoft-components-demo/src/app/select-demo/demos/select-with-custom-template.component.ts
import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-select-with-custom-template', template: ` <h2>Custom options template</h2> <mat-form-field> <mat-label>select</mat-label> <ps-select [(ngModel)]="ngModelValue" [dataSource]="items" [panelClass]="panelNgClass"> <ng-container *psSelectTriggerTemplate="let item"> color: <span [style.color]="item.value" class="asdf">{{ item.viewValue }}</span> </ng-container> <ng-container *psSelectOptionTemplate="let item"> <div>color:</div> <span [style.color]="item.value.color" [style.font-size]="item.value.size" class="asdf">{{ item.label }}</span> </ng-container> </ps-select> </mat-form-field> value: {{ ngModelValue | json }} <ul> <li>The selectable items should be in the color of their name</li> </ul> `, styles: [ ` .app-select-with-custom-template__custom-panel.mat-select-panel .mat-option { height: auto; min-height: 3em; line-height: 1.5em; padding-top: 3px; padding-bottom: 3px; } `, ], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class SelectWithCustomTemplateComponent { public items = [ { value: { color: `red`, size: '3em', }, label: `Red`, }, { value: { color: `green`, size: '2em', }, label: `Green`, }, { value: { color: `blue`, size: '1.5em', }, label: `Blue`, }, ]; public ngModelValue: any = null; public panelNgClass = { // eslint-disable-next-line @typescript-eslint/naming-convention 'app-select-with-custom-template__custom-panel': true, }; }
BirMa/components
projects/components/table/src/subcomponents/table-settings.component.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output, TemplateRef } from '@angular/core'; import { MatCheckboxChange } from '@angular/material/checkbox'; import { IPsTableIntlTexts } from '@prosoft/components/core'; import { Observable, Subscription } from 'rxjs'; import { first, map } from 'rxjs/operators'; import { PsTableColumnDirective } from '../directives/table.directives'; import { IPsTableSortDefinition } from '../models'; import { IPsTableSetting, PsTableSettingsService } from '../services/table-settings.service'; @Component({ selector: 'ps-table-settings', templateUrl: './table-settings.component.html', styles: [ ` .ps-table-settings__form { display: flex; justify-content: space-between; } .ps-table-settings__form > * { min-width: 20%; } .ps-table-settings__form__display-columns { display: flex; flex-direction: column; } `, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PsTableSettingsComponent implements OnInit { @Input() public intl: IPsTableIntlTexts; @Input() public tableId: string; @Input() public columnDefinitions: PsTableColumnDirective[] = []; @Input() public sortDefinitions: IPsTableSortDefinition[] = []; @Input() public pageSizeOptions: number[]; @Input() public customSettings: TemplateRef<any> | null = null; @Output() public readonly settingsSaved = new EventEmitter<void>(); @Output() public readonly settingsAborted = new EventEmitter<void>(); public settings$: Observable<IPsTableSetting>; private _settingSaveSub: Subscription; constructor(public settingsService: PsTableSettingsService) {} public ngOnInit(): void { this.settings$ = this.settingsService.getStream(this.tableId, true).pipe( map((settings) => { settings = settings || ({} as IPsTableSetting); return <IPsTableSetting>{ ...settings, columnBlacklist: settings.columnBlacklist || [], pageSize: settings.pageSize || 15, sortDirection: settings.sortDirection || 'asc', }; }) ); } public columnVisible(settings: IPsTableSetting, columnDef: PsTableColumnDirective) { return !settings.columnBlacklist.some((x) => x === columnDef.property); } public onSortChanged(event: { sortColumn: string; sortDirection: 'asc' | 'desc' }, settings: IPsTableSetting) { if (settings.sortColumn !== event.sortColumn) { settings.sortColumn = event.sortColumn; settings.columnBlacklist = settings.columnBlacklist.filter((x) => x !== event.sortColumn); } settings.sortDirection = event.sortDirection; } public onColumnVisibilityChange(event: MatCheckboxChange, settings: IPsTableSetting, columnDef: PsTableColumnDirective) { if (event.checked) { settings.columnBlacklist = settings.columnBlacklist.filter((x) => x !== columnDef.property); } else if (!settings.columnBlacklist.find((x) => x === columnDef.property)) { settings.columnBlacklist.push(columnDef.property); } } public onSaveClick(setting: IPsTableSetting) { if (this._settingSaveSub) { this._settingSaveSub.unsubscribe(); } this._settingSaveSub = this.settingsService .save(this.tableId, setting) .pipe(first()) .subscribe({ complete: () => this.settingsSaved.emit(), }); } public onCancelClick() { this.settingsAborted.emit(); } }
BirMa/components
projects/components/header/public_api.ts
<reponame>BirMa/components export { PsHeaderComponent } from './src/header.component'; export { PsHeaderCaptionSectionDirective, PsHeaderDescriptionSectionDirective, PsHeaderTopButtonSectionDirective, } from './src/header.directives'; export { PsHeaderModule } from './src/header.module';
BirMa/components
projects/components/savebar/src/savebar.component.ts
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, EventEmitter, Input, NgZone, OnChanges, OnDestroy, OnInit, Output, Renderer2, SimpleChanges, TemplateRef, ViewEncapsulation, } from '@angular/core'; import { IPsSavebarIntlTexts, PsIntlService } from '@prosoft/components/core'; import { merge, Subject, Subscription } from 'rxjs'; import { startWith, takeUntil } from 'rxjs/operators'; import { IPsSavebarMode } from './models'; import { PsSavebarRightContentDirective } from './savebar-right-content.directive'; import type { FormGroup } from '@angular/forms'; /** * @deprecated Please use ps-form instead, will be removed in a later release */ @Component({ selector: 'ps-savebar', templateUrl: './savebar.component.html', styleUrls: ['./savebar.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class PsSavebarComponent implements OnInit, OnChanges, OnDestroy { @Input() public mode: IPsSavebarMode = 'auto'; @Input() public form: FormGroup; // eslint-disable-next-line @angular-eslint/no-input-prefix @Input() public canSave: boolean | null; @Input() public intlOverride: Partial<IPsSavebarIntlTexts>; @Input() public saveKey = 's'; @Output() public readonly save = new EventEmitter<void>(); @Output() public readonly saveAndClose = new EventEmitter<void>(); @Output() public readonly cancel = new EventEmitter<void>(); @ContentChild(PsSavebarRightContentDirective, { read: TemplateRef }) public customRightContent: TemplateRef<any> | null; public get isHidden(): boolean { return this.mode === 'hide'; } public get isSticky(): boolean { if (this.mode && this.mode !== 'auto') { return this.mode === 'sticky'; } if (this.form) { return this.form.dirty || this.form.touched; } return false; } public get saveDisabled(): boolean { if (typeof this.canSave === 'boolean') { return !this.canSave; } if (this.form) { return this.form.pristine || this.form.invalid; } return true; } public intl: IPsSavebarIntlTexts; private ngUnsubscribe$ = new Subject<void>(); private _formSub: Subscription; private _stopListening: () => void; constructor(private intlService: PsIntlService, private renderer: Renderer2, private ngZone: NgZone, public cd: ChangeDetectorRef) {} public ngOnInit() { this.intlService.intlChanged$.pipe(startWith(null as any), takeUntil(this.ngUnsubscribe$)).subscribe(() => { this.updateIntl(); this.cd.markForCheck(); }); this.updateSaveKeyListener(); } public ngOnChanges(changes: SimpleChanges) { if (changes.intlOverride) { this.updateIntl(); } if (changes.form) { if (this._formSub) { this._formSub.unsubscribe(); } if (this.form) { // Die Werte für isSticky und saveDisabled können hier nicht direkt berechnet und gespeichert werden, // weil ValueChanges/statusChanges teils läuft, bevor die dirty, etc. Werte an der FormGroup richtig sind. // Über markForCheck() funktioniert es, weil die ChangeDetection nicht sofort läuft und die Werte stimmen, sobald sie dann läuft. // Wenn es ein Event für dirty/pristine und touched/untouched gäbe, könnte man es umbauen: https://github.com/angular/angular/issues/10887 this._formSub = merge(this.form.valueChanges, this.form.statusChanges).subscribe(() => { this.cd.markForCheck(); }); } } if (changes.saveKey) { this.updateSaveKeyListener(); } } public ngOnDestroy(): void { this.ngUnsubscribe$.next(); this.ngUnsubscribe$.complete(); if (this._stopListening) { this._stopListening(); } if (this._formSub) { this._formSub.unsubscribe(); } } public hasObservers(emitter: EventEmitter<any>) { return emitter && !!emitter.observers.length; } private updateIntl() { const intl = this.intlService.get('savebar'); this.intl = this.intlService.merge(intl, this.intlOverride); } private updateSaveKeyListener() { if (this._stopListening) { this._stopListening(); } if (this.saveKey) { this.ngZone.runOutsideAngular(() => { this._stopListening = this.renderer.listen('document', 'keydown', this.onKeydown.bind(this)); }); } } private onKeydown(event: KeyboardEvent) { if (event.ctrlKey && event.key === this.saveKey && !this.saveDisabled) { if (this.hasObservers(this.save)) { event.preventDefault(); this.ngZone.run(() => this.save.emit()); } else if (this.hasObservers(this.saveAndClose)) { event.preventDefault(); this.ngZone.run(() => this.saveAndClose.emit()); } } } }
BirMa/components
projects/components/table/src/data/table-data-source.spec.ts
<gh_stars>0 /* eslint-disable @typescript-eslint/naming-convention */ import { fakeAsync, tick } from '@angular/core/testing'; import { NEVER, of, Subject, throwError } from 'rxjs'; import { delay, map } from 'rxjs/operators'; import { PsTableDataSource, PsTableDataSourceOptions } from '../data/table-data-source'; import { IExtendedPsTableUpdateDataInfo } from '../models'; describe('PsTableDataSource', () => { it('should have sensible default values', fakeAsync(() => { const loadedData = [{ prop: 'x' }]; const dataSource = new PsTableDataSource<any>(() => of(loadedData).pipe(delay(500))); dataSource.tableReady = true; expect(dataSource.loading).toBe(true); expect(dataSource.data).toEqual([]); expect(dataSource.locale).toBeFalsy(); expect(dataSource.mode).toEqual('client'); expect(dataSource.pageIndex).toEqual(0); expect(dataSource.pageSize).toEqual(15); expect(dataSource.sortColumn).toEqual(null); expect(dataSource.sortDirection).toEqual('asc'); expect(dataSource.filter).toEqual(''); expect(dataSource.visibleRows).toEqual([]); expect(dataSource.dataLength).toEqual(0); expect(dataSource.selectionModel.isMultipleSelection()).toEqual(true); expect(dataSource.selectionModel.selected).toEqual([]); })); it('should return empty array on connect, even if data is not loaded yet', fakeAsync(() => { const dataSource = new PsTableDataSource<any>(() => <any>NEVER); dataSource.tableReady = true; const renderDataUpdates: any[] = []; const sub = dataSource.connect().subscribe((data) => { renderDataUpdates.push(data); }); expect(renderDataUpdates.length).toBe(1); expect(renderDataUpdates.pop()).toEqual([]); dataSource.disconnect(); sub.unsubscribe(); })); it('should not start loading data on connect (the table has to triggers this)', fakeAsync(() => { const dataSource = new PsTableDataSource<any>(() => <any>NEVER); dataSource.tableReady = true; spyOn(dataSource, 'updateData'); const sub = dataSource.connect().subscribe(); dataSource.disconnect(); sub.unsubscribe(); expect(dataSource.updateData).not.toHaveBeenCalled(); })); it('should not load data until the table is ready', fakeAsync(() => { let dataLoadCalled = false; const dataSource = new PsTableDataSource<any>(() => { dataLoadCalled = true; return <any>NEVER; }); const sub = dataSource.connect().subscribe(); dataSource.updateData(false); dataSource.updateData(true); dataSource.disconnect(); sub.unsubscribe(); expect(dataLoadCalled).toBeFalsy(); dataSource.tableReady = true; dataSource.updateData(false); expect(dataLoadCalled).toBeTruthy(); })); it('should work with minimal options object and set default values', fakeAsync(() => { const options: PsTableDataSourceOptions<any> = { loadDataFn: () => of([]), }; spyOn(options, 'loadDataFn').and.callThrough(); const dataSource = new PsTableDataSource<any>(options); dataSource.tableReady = true; expect(dataSource.mode).toEqual('client'); const sub = dataSource.connect().subscribe(); expect(options.loadDataFn).not.toHaveBeenCalled(); dataSource.updateData(true); dataSource.disconnect(); sub.unsubscribe(); expect(options.loadDataFn).toHaveBeenCalledTimes(1); })); it('should work with complete options object', fakeAsync(() => { const trigger$ = new Subject<void>(); const options: PsTableDataSourceOptions<any> = { loadTrigger$: trigger$, loadDataFn: () => of([]), mode: 'server', }; spyOn(options, 'loadDataFn').and.callThrough(); const dataSource = new PsTableDataSource<any>(options); dataSource.tableReady = true; expect(dataSource.mode).toEqual('server'); // trigger before connect shouldn't do anything trigger$.next(); const sub = dataSource.connect().subscribe(); expect(options.loadDataFn).not.toHaveBeenCalled(); // trigger while connected should call the load function trigger$.next(); dataSource.disconnect(); sub.unsubscribe(); expect(options.loadDataFn).toHaveBeenCalledTimes(1); })); it('should reset error/loading/data/selection before updateData and after', fakeAsync(() => { let doThrowError: Error = null; let beforeVisibleRows: any[] = []; const beforeDataItem = {}; const loadedData = [{ prop: 'x' }, { prop: 'y' }]; const dataSource = new PsTableDataSource<any>(() => { let result = of(loadedData).pipe(delay(500)); if (doThrowError) { result = result.pipe( map(() => { throw doThrowError; }) ); } return result; }); dataSource.tableReady = true; let renderDataUpdates: any[] = []; dataSource.connect().subscribe((data) => { renderDataUpdates.push(data); }); // first load should load data from the server doThrowError = new Error('oh no'); initDirtyState([beforeDataItem]); dataSource.updateData(false); expectAsyncLoadingState(); tick(500); expectErrorState(); // as long as no data is successfullyloaded, it should load data from the server doThrowError = null; initDirtyState([beforeDataItem]); dataSource.updateData(false); expectAsyncLoadingState(); tick(500); expectLoadedState(loadedData, loadedData.length, loadedData); // when data is already loaded, just update the visible items and clear the selection model { const error = new Error(); dataSource.loading = false; dataSource.error = error; dataSource.data = loadedData; dataSource.dataLength = loadedData.length; dataSource.selectionModel.select(loadedData[0]); renderDataUpdates = []; dataSource.filter = 'x'; dataSource.updateData(false); // check, that loading, error and data are unchanged expect(dataSource.loading).toBe(false); expect(dataSource.error).toBe(error); expect(dataSource.data).toBe(loadedData); expect(dataSource.dataLength).toBe(1); // check for the neccessary changes const visibleRows = loadedData.filter((x) => x.prop === 'x'); expect(dataSource.visibleRows).toEqual(visibleRows); expect(dataSource.selectionModel.selected).toEqual([]); expect(renderDataUpdates.length).toEqual(1); expect(renderDataUpdates.pop()).toEqual(visibleRows); dataSource.filter = ''; } // when data is already loaded AND another update request is in flight, don't do anything { const error = new Error(); dataSource.loading = true; dataSource.error = error; dataSource.data = loadedData; dataSource.dataLength = loadedData.length; dataSource.selectionModel.select(loadedData[0]); renderDataUpdates = []; dataSource.filter = 'x'; dataSource.updateData(false); // check, that loading, error and data are unchanged expect(dataSource.loading).toBe(true); expect(dataSource.error).toBe(error); expect(dataSource.data).toBe(loadedData); expect(dataSource.dataLength).toBe(loadedData.length); expect(dataSource.visibleRows).toEqual(loadedData); expect(dataSource.selectionModel.selected).toEqual([loadedData[0]]); expect(renderDataUpdates.length).toEqual(0); dataSource.filter = ''; } // with force reload, it should load data from the server initDirtyState([beforeDataItem]); dataSource.updateData(true); expectAsyncLoadingState(); tick(500); expectLoadedState(loadedData, loadedData.length, loadedData); function initDirtyState(data: any[]) { dataSource.loading = false; dataSource.error = new Error(); dataSource.data = data; dataSource.dataLength = data.length; dataSource.selectionModel.select(data[0]); renderDataUpdates = []; beforeVisibleRows = dataSource.visibleRows; } function expectAsyncLoadingState() { // state should be resetted expect(dataSource.loading).toBe(true); expect(dataSource.error).toBe(null); expect(dataSource.selectionModel.selected).toEqual([]); expect(renderDataUpdates.length).toEqual(0); // data shouldn't have changed, otherwise pagination breaks expect(dataSource.data).toEqual([beforeDataItem]); expect(dataSource.dataLength).toEqual(1); // but visible rows should be unmodified, so the table doesn't have to trash and rebuild the dom while loading expect(dataSource.visibleRows).toEqual(beforeVisibleRows); } function expectLoadedState(data: any[], dataLength: number, visibleData: any[]) { expect(dataSource.loading).toBe(false); expect(dataSource.error).toBe(null); expect(dataSource.data).toEqual(data); expect(dataSource.dataLength).toEqual(dataLength); expect(dataSource.visibleRows).toEqual(visibleData); expect(dataSource.selectionModel.selected).toEqual([]); expect(renderDataUpdates.length).toEqual(1); expect(renderDataUpdates.pop()).toEqual(visibleData); } function expectErrorState() { expect(dataSource.loading).toBe(false); expect(dataSource.error).toBe(doThrowError); expect(dataSource.data).toEqual([]); expect(dataSource.dataLength).toEqual(0); expect(dataSource.visibleRows).toEqual([]); expect(dataSource.selectionModel.selected).toEqual([]); expect(renderDataUpdates.length).toEqual(1); expect(renderDataUpdates.pop()).toEqual([]); } })); it('should not sort/filter/page, but provide info to loadData when mode is server', () => { const loadedData = Array.from(new Array(20).keys()).map((x) => ({ prop: x })); let lastUpdateInfo: IExtendedPsTableUpdateDataInfo<any> = null; const dataSource = new PsTableDataSource<any>((updateInfo) => { lastUpdateInfo = updateInfo; return of(loadedData); }, 'server'); dataSource.tableReady = true; spyOn(dataSource, 'filterProperties'); spyOn(dataSource, 'filterValues'); spyOn(dataSource, 'filterPredicate'); spyOn(dataSource, 'sortingDataAccessor'); spyOn(dataSource, 'sortData'); let renderData: any[] = []; const sub = dataSource.connect().subscribe((data) => { renderData = data; }); dataSource.pageSize = 2; dataSource.pageIndex = 3; dataSource.filter = 'a'; dataSource.sortColumn = 'prop'; dataSource.sortDirection = 'desc'; dataSource.updateData(false); expect(lastUpdateInfo).toEqual({ pageSize: 2, currentPage: 3, searchText: 'a', sortColumn: 'prop', sortDirection: 'desc', triggerData: null, }); expect(renderData).toBe(loadedData); expect(dataSource.filterProperties).not.toHaveBeenCalled(); expect(dataSource.filterValues).not.toHaveBeenCalled(); expect(dataSource.filterPredicate).not.toHaveBeenCalled(); expect(dataSource.sortingDataAccessor).not.toHaveBeenCalled(); expect(dataSource.sortData).not.toHaveBeenCalled(); sub.unsubscribe(); }); it('should call sortData with the right parameters when mode is client', fakeAsync(() => { const loadedData = [{ prop: 'a' }]; const dataSource = new PsTableDataSource<any>(() => of(loadedData), 'client'); dataSource.tableReady = true; spyOn(dataSource, 'sortData').and.returnValue([{ x: 'sorted' }]); let renderData: any[] = []; const sub = dataSource.connect().subscribe((data) => { renderData = data; }); dataSource.sortColumn = 'prop'; dataSource.sortDirection = 'asc'; dataSource.updateData(); expect(dataSource.sortData).toHaveBeenCalledWith([{ prop: 'a' }], { sortColumn: 'prop', sortDirection: 'asc' }); expect(renderData).toEqual([{ x: 'sorted' }]); dataSource.sortColumn = 'prop_d'; dataSource.sortDirection = 'desc'; dataSource.updateData(); expect(dataSource.sortData).toHaveBeenCalledWith([{ prop: 'a' }], { sortColumn: 'prop_d', sortDirection: 'desc' }); expect(renderData).toEqual([{ x: 'sorted' }]); sub.unsubscribe(); })); it('should use cached data if loading is not neccessary in client mode', fakeAsync(() => { let counter = 0; let throwErr = false; const dataProvider = { loadData: () => (throwErr ? throwError(new Error('error')) : of([{ a: ++counter }])), }; const clientDataSource = new PsTableDataSource<any>(() => dataProvider.loadData(), 'client'); clientDataSource.tableReady = true; let renderData: any[] = []; const sub = clientDataSource.connect().subscribe((data) => { renderData = data; }); clientDataSource.updateData(false); expect(renderData).toEqual([{ a: 1 }]); clientDataSource.updateData(false); expect(renderData).toEqual([{ a: 1 }]); clientDataSource.updateData(true); expect(renderData).toEqual([{ a: 2 }]); throwErr = true; clientDataSource.updateData(false); expect(renderData).toEqual([{ a: 2 }]); clientDataSource.updateData(true); expect(renderData).toEqual([]); throwErr = false; clientDataSource.updateData(false); expect(renderData).toEqual([{ a: 3 }]); sub.unsubscribe(); })); it('should never cache data for server mode', fakeAsync(() => { let counter = 0; const dataProvider = { loadData: () => of([{ a: ++counter }]), }; spyOn(dataProvider, 'loadData').and.callThrough(); const serverDataSource = new PsTableDataSource<any>(() => dataProvider.loadData(), 'server'); serverDataSource.tableReady = true; serverDataSource.updateData(false); serverDataSource.updateData(false); serverDataSource.updateData(true); serverDataSource.updateData(false); expect(dataProvider.loadData).toHaveBeenCalledTimes(4); })); describe('sortingDataAccessor', () => { it('should return the requested property value', () => { const dataSource = new PsTableDataSource<any>(() => of([]), 'client'); dataSource.tableReady = true; expect(dataSource.sortingDataAccessor({ prop: 5 }, 'prop')).toBe(5); expect(dataSource.sortingDataAccessor({ prop: 'a' }, 'prop')).toBe('a'); const nestedObj = {}; expect(dataSource.sortingDataAccessor({ prop: nestedObj }, 'prop')).toBe(nestedObj); expect(dataSource.sortingDataAccessor({ prop: nestedObj }, 'a')).toBe(undefined); }); }); describe('sortData', () => { function sortAssert<T>(inData: T[], ascExpectedData: T[], descExpectedData: T[]) { const dataSource = new PsTableDataSource<any>(() => of([]), 'client'); dataSource.tableReady = true; const data = inData.map((x) => ({ prop: x })); const sortedDataAsc = dataSource.sortData(data, { sortColumn: 'prop', sortDirection: 'asc' }); expect(sortedDataAsc).toEqual(ascExpectedData.map((x) => ({ prop: x }))); const sortedDataDesc = dataSource.sortData(data, { sortColumn: 'prop', sortDirection: 'desc' }); expect(sortedDataDesc).toEqual(descExpectedData.map((x) => ({ prop: x }))); } it('should sort strings', () => { sortAssert(['b', 'a', 'c'], ['a', 'b', 'c'], ['c', 'b', 'a']); }); it('should sort numbers', () => { sortAssert([2, 1, 3], [1, 2, 3], [3, 2, 1]); }); it('should sort string numbers', () => { sortAssert(['2', '10', '3'], ['2', '3', '10'], ['10', '3', '2']); }); it('should sort booleans', () => { sortAssert([true, false, true], [false, true, true], [true, true, false]); }); it('should sort dates', () => { const now = new Date(); const future = new Date(); future.setMinutes(70); const past = new Date(); past.setMinutes(-70); sortAssert([now, future, past], [past, now, future], [future, now, past]); }); it('should use sortingDataAccessor to get the sort property', () => { const dataSource = new PsTableDataSource<any>(() => of([]), 'client'); dataSource.tableReady = true; spyOn(dataSource, 'sortingDataAccessor').and.callThrough(); const data = [{ prop: 'b' }, { prop: 'a' }]; dataSource.sortData(data, { sortColumn: 'prop', sortDirection: 'asc' }); expect(dataSource.sortingDataAccessor).toHaveBeenCalledWith({ prop: 'b' }, 'prop'); expect(dataSource.sortingDataAccessor).toHaveBeenCalledWith({ prop: 'a' }, 'prop'); }); }); it('should call filterPredicate with the right parameters when mode is client', fakeAsync(() => { const loadedData = [{ prop: 'a' }]; const dataSource = new PsTableDataSource<any>(() => of(loadedData), 'client'); dataSource.tableReady = true; spyOn(dataSource, 'filterPredicate').and.callThrough(); let renderData: any[] = []; const sub = dataSource.connect().subscribe((data) => { renderData = data; }); dataSource.filter = 'b'; dataSource.updateData(); expect(dataSource.filterPredicate).toHaveBeenCalledWith({ prop: 'a' }, 'b'); expect(renderData).toEqual([]); dataSource.filter = 'a'; dataSource.updateData(); expect(dataSource.filterPredicate).toHaveBeenCalledWith({ prop: 'a' }, 'a'); expect(renderData).toEqual([{ prop: 'a' }]); sub.unsubscribe(); })); describe('filterProperties', () => { it('should return all object keys, but no nested keys', () => { const dataSource = new PsTableDataSource<any>(() => of([]), 'client'); dataSource.tableReady = true; expect(dataSource.filterProperties({ a: 5, b: { b_a: 3 }, 'c c': 4 })).toEqual(['a', 'b', 'c c']); }); }); describe('filterValues', () => { it('should call filterProperties and return the values of the given properties', () => { const dataSource = new PsTableDataSource<any>(() => of([]), 'client'); dataSource.tableReady = true; spyOn(dataSource, 'filterProperties').and.returnValue(['a', 'c c']); const obj = { a: 1, b: { b_a: 2 }, 'c c': 3, invisible: 5 }; expect(dataSource.filterValues(obj)).toEqual([1, 3]); expect(dataSource.filterProperties).toHaveBeenCalledWith(obj); }); }); describe('filterPredicate', () => { it('should call filterValues and search for the filter text on the values', () => { const dataSource = new PsTableDataSource<any>(() => of([]), 'client'); dataSource.tableReady = true; spyOn(dataSource, 'filterValues').and.returnValue(['value 1', 'value 2']); const obj = { a: 1, b: { b_a: 2 }, 'c c': 3 }; expect(dataSource.filterPredicate(obj, '1')).toBe(true); expect(dataSource.filterPredicate(obj, 'asdf')).toBe(false); expect(dataSource.filterValues).toHaveBeenCalledWith(obj); }); it('should work with different casing and values types', () => { const dataSource = new PsTableDataSource<any>(() => of([]), 'client'); dataSource.tableReady = true; expect(dataSource.filterPredicate({ a: 'hallo' }, 'HALLO')).toBe(true); expect(dataSource.filterPredicate({ a: true }, 'true')).toBe(true); expect(dataSource.filterPredicate({ a: 12 }, '1')).toBe(true); expect(dataSource.filterPredicate({ a: new Date(2019, 8, 26) }, '2019')).toBe(true); }); }); describe('getUpdateDataInfo', () => { it('should work', () => { const loadTrigger$ = new Subject<string>(); const dataSource = new PsTableDataSource({ loadTrigger$: loadTrigger$, loadDataFn: () => of([]), mode: 'client', }); dataSource.connect().subscribe(); loadTrigger$.next('triggered'); dataSource.tableReady = true; dataSource.pageSize = 33; dataSource.pageIndex = 7; dataSource.filter = 'asdf'; dataSource.sortColumn = 'sortProp'; dataSource.sortDirection = 'desc'; expect(dataSource.getUpdateDataInfo()).toEqual({ pageSize: 33, currentPage: 7, searchText: 'asdf', sortColumn: 'sortProp', sortDirection: 'desc', }); dataSource.pageSize = 5; dataSource.pageIndex = 3; dataSource.filter = null; dataSource.sortColumn = 'a'; dataSource.sortDirection = 'asc'; expect(dataSource.getUpdateDataInfo()).toEqual({ pageSize: 5, currentPage: 3, searchText: null, sortColumn: 'a', sortDirection: 'asc', }); expect(dataSource.getUpdateDataInfo(true)).toEqual({ pageSize: 5, currentPage: 3, searchText: null, sortColumn: 'a', sortDirection: 'asc', triggerData: 'triggered', }); dataSource.disconnect(); }); }); it('selection should work', () => { const loadedData = Array.from(new Array(6).keys()).map((x) => ({ prop: x })); const dataSource = new PsTableDataSource<any>(() => of(loadedData), 'client'); const sub = dataSource.connect().subscribe(); dataSource.tableReady = true; dataSource.pageIndex = 1; dataSource.pageSize = 2; dataSource.updateData(); expect(dataSource.visibleRows).toEqual([{ prop: 2 }, { prop: 3 }]); expect(dataSource.allVisibleRowsSelected).toBe(false); dataSource.selectVisibleRows(); expect(dataSource.selectionModel.selected).toEqual([{ prop: 2 }, { prop: 3 }]); expect(dataSource.allVisibleRowsSelected).toBe(true); dataSource.toggleVisibleRowSelection(); expect(dataSource.selectionModel.selected).toEqual([]); expect(dataSource.allVisibleRowsSelected).toBe(false); dataSource.toggleVisibleRowSelection(); expect(dataSource.selectionModel.selected).toEqual([{ prop: 2 }, { prop: 3 }]); expect(dataSource.allVisibleRowsSelected).toBe(true); dataSource.selectionModel.clear(); dataSource.selectionModel.select(dataSource.visibleRows[0]); dataSource.toggleVisibleRowSelection(); expect(dataSource.selectionModel.selected).toEqual([{ prop: 2 }, { prop: 3 }]); expect(dataSource.allVisibleRowsSelected).toBe(true); sub.unsubscribe(); }); it('should update visibleRows but not data on client pagination', () => { const loadedData = Array.from(new Array(6).keys()).map((x) => ({ prop: x })); const dataSource = new PsTableDataSource<any>(() => of(loadedData), 'client'); let renderData: any[] = []; const sub = dataSource.connect().subscribe((data) => { renderData = data; }); dataSource.tableReady = true; dataSource.pageIndex = 1; dataSource.pageSize = 2; dataSource.updateData(); expect(dataSource.visibleRows).toEqual([{ prop: 2 }, { prop: 3 }]); expect(dataSource.visibleRows).toBe(renderData); expect(dataSource.data).toBe(loadedData); dataSource.pageIndex = 0; dataSource.pageSize = 3; dataSource.updateData(); expect(dataSource.visibleRows).toEqual([{ prop: 0 }, { prop: 1 }, { prop: 2 }]); expect(dataSource.visibleRows).toBe(renderData); expect(dataSource.data).toBe(loadedData); sub.unsubscribe(); }); it('should update visibleRows, data and dataLength on server pagination', () => { const dataSource = new PsTableDataSource<any>((filter) => of({ items: [{ prop: filter.currentPage }], totalItems: 100 }), 'server'); dataSource.tableReady = true; dataSource.pageIndex = 0; dataSource.pageSize = 1; let renderData: any[] = []; const sub = dataSource.connect().subscribe((data) => { renderData = data; }); dataSource.updateData(); expect(dataSource.visibleRows).toEqual([{ prop: 0 }]); expect(dataSource.visibleRows).toBe(renderData); expect(dataSource.data).toEqual([{ prop: 0 }]); expect(dataSource.dataLength).toEqual(100); dataSource.pageIndex = 5; dataSource.updateData(); expect(dataSource.visibleRows).toEqual([{ prop: 5 }]); expect(dataSource.visibleRows).toBe(renderData); expect(dataSource.data).toEqual([{ prop: 5 }]); expect(dataSource.dataLength).toEqual(100); sub.unsubscribe(); }); it('should fix pageIndex when currentPage would have no items on server pagination', () => { const dataSource = new PsTableDataSource<any>((filter) => of({ items: [{ prop: filter.currentPage }], totalItems: 1 }), 'server'); dataSource.tableReady = true; dataSource.pageIndex = 1; dataSource.pageSize = 1; let renderData: any[] = []; const sub = dataSource.connect().subscribe((data) => { renderData = data; }); dataSource.updateData(); expect(dataSource.pageIndex).toEqual(0); expect(dataSource.visibleRows).toEqual([{ prop: 0 }]); expect(dataSource.visibleRows).toBe(renderData); expect(dataSource.data).toEqual([{ prop: 0 }]); expect(dataSource.dataLength).toEqual(1); dataSource.pageIndex = 5; dataSource.updateData(); expect(dataSource.pageIndex).toEqual(0); expect(dataSource.visibleRows).toEqual([{ prop: 0 }]); expect(dataSource.visibleRows).toBe(renderData); expect(dataSource.data).toEqual([{ prop: 0 }]); expect(dataSource.dataLength).toEqual(1); sub.unsubscribe(); }); it('should pass last loadTrigger$ value to loadDataFn', () => { const loadTrigger$ = new Subject<string>(); const loadTriggerValues: string[] = []; const dataSource = new PsTableDataSource<any>({ loadTrigger$: loadTrigger$, loadDataFn: (filter) => { loadTriggerValues.push(filter.triggerData); return of([]); }, }); dataSource.tableReady = true; const sub = dataSource.connect().subscribe(); expect(loadTriggerValues).toEqual([]); // updateData should call loadDataFn even if loadTrigger$ didn't emit yet dataSource.updateData(); expect(loadTriggerValues).toEqual([null]); // loadTrigger$ emit should call loadDataFn with the emitted value loadTrigger$.next('test'); expect(loadTriggerValues).toEqual([null, 'test']); // updateData should call loadDataFn with the last emitted loadTrigger$ value dataSource.updateData(); expect(loadTriggerValues).toEqual([null, 'test', 'test']); sub.unsubscribe(); }); });
BirMa/components
projects/components/table/src/subcomponents/table-header.component.spec.ts
import { CommonModule } from '@angular/common'; import { ChangeDetectionStrategy, Component, TemplateRef, ViewChild } from '@angular/core'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { PsTableHeaderComponent } from './table-header.component'; import { PsTableSearchComponent } from './table-search.component'; import { PsTableSortComponent } from './table-sort.component'; @Component({ selector: 'ps-test-component', template: ` <ps-table-header [caption]="caption" [showSorting]="showSorting" [filterable]="filterable" [topButtonSection]="topButtonSection" [intl]="tableIntl" ></ps-table-header> <ng-template #tpl></ng-template> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestComponent { public caption = 'caption'; public showSorting = true; public filterable = true; public tableIntl = {}; public topButtonSection: TemplateRef<any> | null = null; @ViewChild(PsTableHeaderComponent, { static: true }) cmp: PsTableHeaderComponent; @ViewChild('tpl', { read: TemplateRef, static: true }) public dummyTpl: TemplateRef<any> | null = null; } describe('PsTableHeaderComponent', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule, CommonModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatButtonModule, MatIconModule], declarations: [TestComponent, PsTableHeaderComponent, PsTableSearchComponent, PsTableSortComponent], }).compileComponents(); }) ); it('should only add top padding if sort, search or action buttons are visible without a caption', () => { const fixture = TestBed.createComponent(TestComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); component.caption = ''; component.showSorting = false; component.filterable = false; component.topButtonSection = null; fixture.detectChanges(); expect(component.cmp.paddingTop).toBe('0'); component.caption = 'test'; component.showSorting = false; component.filterable = false; component.topButtonSection = null; fixture.detectChanges(); expect(component.cmp.paddingTop).toBe('0'); component.caption = 'test'; component.showSorting = true; component.filterable = true; component.topButtonSection = component.dummyTpl; fixture.detectChanges(); expect(component.cmp.paddingTop).toBe('0'); component.caption = ''; component.showSorting = true; component.filterable = false; component.topButtonSection = null; fixture.detectChanges(); expect(component.cmp.paddingTop).toBe('1em'); component.caption = ''; component.showSorting = false; component.filterable = true; component.topButtonSection = null; fixture.detectChanges(); expect(component.cmp.paddingTop).toBe('1em'); component.caption = ''; component.showSorting = false; component.filterable = false; component.topButtonSection = component.dummyTpl; fixture.detectChanges(); expect(component.cmp.paddingTop).toBe('1em'); }); });
BirMa/components
projects/components/form-field/src/form-field.component.ts
import type { QueryList } from '@angular/core'; import { AfterContentInit, ChangeDetectionStrategy, Component, ContentChild, ContentChildren, ElementRef, HostBinding, Inject, InjectionToken, Input, OnChanges, OnDestroy, Optional, SimpleChanges, ViewChild, ViewEncapsulation, } from '@angular/core'; import { FormControl, NgControl } from '@angular/forms'; import { FloatLabelType, MatFormField, MatFormFieldAppearance, MatFormFieldControl, MatFormFieldDefaultOptions, MatLabel, MatPrefix, MatSuffix, MAT_FORM_FIELD_DEFAULT_OPTIONS, } from '@angular/material/form-field'; import { hasRequiredField, IPsFormError, PsFormService } from '@prosoft/components/form-base'; import { Observable, of, Subscription } from 'rxjs'; import { tap } from 'rxjs/operators'; import { DummyMatFormFieldControl } from './dummy-mat-form-field-control'; export declare type PsFormFieldSubscriptType = 'bubble' | 'resize' | 'single-line'; export interface PsFormFieldConfig { subscriptType?: PsFormFieldSubscriptType; hintToggle?: boolean; } export const PS_FORM_FIELD_CONFIG = new InjectionToken<PsFormFieldConfig>('PS_FORM_FIELD_CONFIG'); @Component({ selector: 'ps-form-field', template: ` <mat-form-field style="width: 100%;" [class.mat-form-field--emulated]="emulated" [class.mat-form-field--no-underline]="noUnderline" [floatLabel]="floatLabel" [hintLabel]="visibleHint" [appearance]="appearance" > <mat-label *ngIf="_labelChild"> <ng-content select="mat-label"></ng-content> </mat-label> <mat-label *ngIf="!_labelChild && calculatedLabel"> <mat-label>{{ calculatedLabel }}</mat-label> </mat-label> <ng-container matPrefix *ngIf="_prefixChildren.length"> <ng-content select="[matPrefix]"></ng-content> </ng-container> <ng-content></ng-content> <ng-container matSuffix *ngIf="_suffixChildren.length"> <ng-content select="[matSuffix]"></ng-content> </ng-container> <button type="button" mat-icon-button matSuffix (click)="toggleHint($event)" *ngIf="showHintToggle"> <mat-icon>info_outline</mat-icon> </button> <mat-error *ngFor="let error of errors$ | async">{{ error.errorText }}</mat-error> </mat-form-field> `, styleUrls: ['./form-field.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class PsFormFieldComponent implements OnChanges, AfterContentInit, OnDestroy { @Input() public createLabel = true; @Input() public floatLabel: FloatLabelType = this.matDefaults?.floatLabel || 'auto'; @Input() public hint: string = null; @Input() public appearance: MatFormFieldAppearance = this.matDefaults?.appearance || 'legacy'; @Input() public subscriptType: PsFormFieldSubscriptType = this.defaults ? this.defaults.subscriptType : 'resize'; @Input() public hintToggle: boolean | null = null; @ViewChild(MatFormField, { static: true }) public _matFormField: MatFormField; /** We can get the FromControl from this */ @ContentChild(NgControl) public _ngControl: NgControl | null; /** The MatFormFieldControl or null, if it is no MatFormFieldControl */ @ContentChild(MatFormFieldControl) public _control: MatFormFieldControl<any> | null; /** The MatLabel, if it is set or null */ @ContentChild(MatLabel) public set labelChild(value: MatLabel) { this._labelChild = value; this.updateLabel(); if (this._matFormField) { (<any>this._matFormField)._changeDetectorRef.markForCheck(); } } public _labelChild: MatLabel; @ContentChildren(MatPrefix) public _prefixChildren: QueryList<MatPrefix>; @ContentChildren(MatSuffix) public _suffixChildren: QueryList<MatSuffix>; @HostBinding('class.ps-form-field--bubble') public get showBubble() { return this.subscriptType === 'bubble' && (!!this.visibleHint || this.hasError); } @HostBinding('class.ps-form-field--error-bubble') public get showErrorBubble() { return this.subscriptType === 'bubble' && this.hasError; } @HostBinding('class.ps-form-field--subscript-resize') public get autoResizeHintError() { return this.subscriptType === 'resize'; } // mat-form-field childs, that we dont support: // @ContentChild(MatPlaceholder) _placeholderChild: MatPlaceholder; // Deprecated, placeholder attribute of the form field control should be used instead! // @ContentChildren(MatError) public _errorChildren: QueryList<MatError>; // Will be created automatically // @ContentChildren(MatHint) public _hintChildren: QueryList<MatHint>; // No idea how to make this work... public get hintToggleOptionActive(): boolean { return typeof this.hintToggle === 'boolean' ? this.hintToggle : this.defaults.hintToggle; } public get showHintToggle(): boolean { return !!this.hint && this.hintToggleOptionActive; } public get visibleHint(): string | null { return this.showHint || !this.hintToggleOptionActive ? this.hint : null; } /** The error messages to show */ public errors$: Observable<IPsFormError[]> = of([]); /** indicates if the control is no real MatFormFieldControl */ public emulated = false; /** ide the underline for the control */ public noUnderline = false; public showHint = false; public calculatedLabel: string = null; private formControl: FormControl; /** Either the MatFormFieldControl or a DummyMatFormFieldControl */ private matFormFieldControl: MatFormFieldControl<any>; /** The real control instance (MatSlider, MatSelect, MatCheckbox, ...) */ private realFormControl: any; /** The control type. Most of the time this is the same as the selector */ private controlType: string; private hasError = false; private labelTextSubscription: Subscription; constructor( private _elementRef: ElementRef, private formsService: PsFormService, @Optional() @Inject(PS_FORM_FIELD_CONFIG) private defaults?: PsFormFieldConfig, @Optional() @Inject(MAT_FORM_FIELD_DEFAULT_OPTIONS) private matDefaults?: MatFormFieldDefaultOptions ) { if (!this.defaults) { this.defaults = { hintToggle: false, subscriptType: 'resize', }; } } public ngOnChanges(changes: SimpleChanges) { if (changes.hintToggle) { this.showHint = !this.hintToggleOptionActive; } } public ngAfterContentInit(): void { this.formControl = this._ngControl && (this._ngControl.control as FormControl); this.matFormFieldControl = this._control || new DummyMatFormFieldControl(this._ngControl, this.formControl); this._matFormField._control = this.matFormFieldControl; this.emulated = this.matFormFieldControl instanceof DummyMatFormFieldControl; this.realFormControl = getRealFormControl(this._ngControl, this.matFormFieldControl); this.controlType = this.formsService.getControlType(this.realFormControl) || 'unknown'; this._elementRef.nativeElement.classList.add(`ps-form-field-type-${this.controlType}`); this.noUnderline = this.emulated || !!this.realFormControl.noUnderline; if (this.floatLabel === 'auto' && (this.emulated || this.realFormControl.shouldLabelFloat === undefined)) { this.floatLabel = 'always'; } if (this.formControl) { if (this.formsService.tryDetectRequired) { (<any>this.matFormFieldControl).required = hasRequiredField(this.formControl); } this.errors$ = this.formsService.getControlErrors(this.formControl).pipe( tap((errors) => { this.hasError = !!errors.length; }) ); this.updateLabel(); } } public ngOnDestroy(): void { if (this.matFormFieldControl instanceof DummyMatFormFieldControl) { // eslint-disable-next-line @angular-eslint/no-lifecycle-call this.matFormFieldControl.ngOnDestroy(); } if (this.labelTextSubscription) { this.labelTextSubscription.unsubscribe(); } } public toggleHint(event: MouseEvent) { this.showHint = !this.showHint; event.stopPropagation(); } private updateLabel() { this.calculatedLabel = null; if (!this.createLabel || this._labelChild || !this.formControl) { return; } const labelText$ = this.formsService.getLabel(this.formControl); if (!labelText$) { return; } if (this.labelTextSubscription) { this.labelTextSubscription.unsubscribe(); } this.labelTextSubscription = labelText$.subscribe((label) => { if (this.controlType.startsWith('mat-checkbox')) { const labelNode = this._elementRef.nativeElement.querySelectorAll('.mat-checkbox-label')[0]; if (!labelNode.innerText.trim()) { if (labelNode.childNodes.length === 1) { labelNode.appendChild(document.createTextNode(label)); } else { labelNode.childNodes[1].nodeValue = label; } } } else { this.calculatedLabel = label; } // when only our own component is marked for check, then the label will not be shown // when labelText$ didn't run synchronously (<any>this._matFormField)._changeDetectorRef.markForCheck(); }); } } function getRealFormControl(ngControl: NgControl, matFormFieldControl: MatFormFieldControl<any>): any { if (!(matFormFieldControl instanceof DummyMatFormFieldControl) || !ngControl) { return matFormFieldControl; } return ngControl.valueAccessor; }
BirMa/components
projects/components/flip-container/src/flip-container.component.spec.ts
import { CommonModule } from '@angular/common'; import { ChangeDetectionStrategy, Component, ViewChild } from '@angular/core'; import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { PsFlipContainerComponent } from './flip-container.component'; import { PsFlipContainerModule } from './flip-container.module'; @Component({ selector: 'ps-test-component', template: ` <ps-flip-container [removeHiddenNodes]="removeHiddenNodes"> <div *psFlipContainerFront><span>front</span></div> <div *psFlipContainerBack><span>back</span></div> </ps-flip-container> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestComponent { public removeHiddenNodes = true; @ViewChild(PsFlipContainerComponent, { static: true }) cmp: PsFlipContainerComponent; } describe('PsFlipContainerComponent', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule, CommonModule, PsFlipContainerModule], declarations: [TestComponent], }).compileComponents(); }) ); it('should initially show front and correctly switch between front and back', fakeAsync(() => { const fixture = TestBed.createComponent(TestComponent); const component = fixture.componentInstance; fixture.detectChanges(); const flipBoxDbg = fixture.debugElement.query(By.css('.ps-flip-container__flip-box')); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(0deg)'); expect(component.cmp.active).toEqual('front'); component.cmp.toggleFlip(); expect(component.cmp.active).toEqual('back'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(180deg)'); expect(component.cmp.active).toEqual('back'); component.cmp.toggleFlip(); expect(component.cmp.active).toEqual('front'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(0deg)'); expect(component.cmp.active).toEqual('front'); component.cmp.showFront(); expect(component.cmp.active).toEqual('front'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(0deg)'); expect(component.cmp.active).toEqual('front'); component.cmp.showBack(); expect(component.cmp.active).toEqual('back'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(180deg)'); expect(component.cmp.active).toEqual('back'); component.cmp.showBack(); expect(component.cmp.active).toEqual('back'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(180deg)'); expect(component.cmp.active).toEqual('back'); component.cmp.show('back'); expect(component.cmp.active).toEqual('back'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(180deg)'); expect(component.cmp.active).toEqual('back'); component.cmp.show('front'); expect(component.cmp.active).toEqual('front'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(0deg)'); expect(component.cmp.active).toEqual('front'); component.cmp.show('front'); expect(component.cmp.active).toEqual('front'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(0deg)'); expect(component.cmp.active).toEqual('front'); component.cmp.show('back'); expect(component.cmp.active).toEqual('back'); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(flipBoxDbg.nativeElement.style.transform).toEqual('rotateY(180deg)'); expect(component.cmp.active).toEqual('back'); })); it('should hide DOM nodes with removeHiddenNodes false', fakeAsync(() => { const fixture = TestBed.createComponent(TestComponent); const component = fixture.componentInstance; component.removeHiddenNodes = false; fixture.detectChanges(); const backEl = fixture.debugElement.query(By.css('.ps-flip-container__side__back')).nativeElement; const frontEl = fixture.debugElement.query(By.css('.ps-flip-container__side__front')).nativeElement; expect(backEl.hidden).toEqual(true); expect(backEl.children.length).toEqual(1); expect(frontEl.hidden).toEqual(false); expect(frontEl.children.length).toEqual(1); component.cmp.toggleFlip(); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(backEl.hidden).toEqual(false); expect(backEl.children.length).toEqual(1); expect(frontEl.hidden).toEqual(true); expect(frontEl.children.length).toEqual(1); })); it('should hide and remove DOM nodes with removeHiddenNodes true', fakeAsync(() => { const fixture = TestBed.createComponent(TestComponent); const component = fixture.componentInstance; component.removeHiddenNodes = true; fixture.detectChanges(); const backEl = fixture.debugElement.query(By.css('.ps-flip-container__side__back')).nativeElement; const frontEl = fixture.debugElement.query(By.css('.ps-flip-container__side__front')).nativeElement; expect(backEl.hidden).toEqual(true); expect(backEl.children.length).toEqual(0); expect(frontEl.hidden).toEqual(false); expect(frontEl.children.length).toEqual(1); component.cmp.toggleFlip(); fixture.detectChanges(); tick(300); fixture.detectChanges(); expect(backEl.hidden).toEqual(false); expect(backEl.children.length).toEqual(1); expect(frontEl.hidden).toEqual(true); expect(frontEl.children.length).toEqual(0); })); });
BirMa/components
projects/prosoft-components-demo/src/app/select-demo/demos/select-with-custom-select-service.component.ts
import { ChangeDetectionStrategy, Component, Injectable } from '@angular/core'; import { AbstractControl, FormControl, FormGroup } from '@angular/forms'; import { DefaultPsSelectService, PsSelectData, PsSelectDataSource, PsSelectLoadTrigger, PsSelectService } from '@prosoft/components/select'; import { Observable, of } from 'rxjs'; @Injectable() export class CustomPsSelectService extends DefaultPsSelectService { constructor() { super(); } public override createDataSource<T>(data: PsSelectData | string, control: AbstractControl): PsSelectDataSource<T> { if (typeof data === 'string') { data = getLookupData(data); } return super.createDataSource(data, control); } } @Component({ selector: 'app-select-with-custom-select-service', template: ` <h2>Custom PsSelectService</h2> <div [formGroup]="form"> <mat-form-field style="display:inline-block"> <mat-label>lookup (mode: entity)</mat-label> <ps-select formControlName="lookupEntity" [dataSource]="'lookup:country'"></ps-select> </mat-form-field> value: {{ form.value.lookupEntity | json }}<br /> <mat-form-field style="display:inline-block"> <mat-label>lookup (mode: id)</mat-label> <ps-select formControlName="lookupId" [dataSource]="'idlookup:country'"></ps-select> </mat-form-field> value: {{ form.value.lookupId | json }}<br /> <mat-form-field style="display:inline-block"> <mat-label>options (mode: entity)</mat-label> <ps-select formControlName="optionsEntity" [dataSource]="{ mode: 'entity', idKey: 'id', labelKey: 'Name', items: items$ }" ></ps-select> </mat-form-field> value: {{ form.value.optionsEntity | json }}<br /> <mat-form-field style="display:inline-block"> <mat-label>options (mode: id)</mat-label> <ps-select formControlName="optionsId" [dataSource]="{ mode: 'id', idKey: 'id', labelKey: 'Name', items: items$ }"></ps-select> </mat-form-field> value: {{ form.value.optionsId | json }}<br /> </div> <ul> <li>The initially visible selections should be 'not visible after first open', '??? (ID: country1)', 'Item 1' and 'Item 1'</li> <li>After first opening the lookup dropdowns (when the items are loaded) the label should update to 'country 1'</li> <li>For mode 'entity' the whole object should be in the form value</li> <li>For mode 'id' only the id should be in the form value</li> </ul> `, changeDetection: ChangeDetectionStrategy.OnPush, providers: [{ provide: PsSelectService, useClass: CustomPsSelectService }], }) export class SelectWithCustomSelectServiceComponent { public items$: Observable<ILookup[]> = of( Array.from(Array(50).keys()).map((i) => ({ id: `id${i}`, name: `Item ${i}`, })) ); public form = new FormGroup({ lookupEntity: new FormControl({ id: 'country1', name: 'not visible after first open' }), lookupId: new FormControl('country1'), optionsEntity: new FormControl({ id: 'id1', name: 'not visible in select' }), optionsId: new FormControl('id1'), }); } export interface ILookup { name?: string; id?: string; } function getLookupData(lookup: string): PsSelectData<ILookup> { // lookup:<entityname> or idlookup:<entityname> if (!/^(id)?lookup:/.test(lookup)) { throw new Error(lookup); } const entityName = lookup.split(':')[1]; const data$: Observable<ILookup[]> = of( Array.from(Array(50).keys()).map((i) => ({ id: `${entityName}${i}`, name: `${entityName} ${i}`, })) ); return { mode: lookup.startsWith('id') ? 'id' : 'entity', idKey: 'id', labelKey: 'name', items: data$, loadTrigger: PsSelectLoadTrigger.everyPanelOpen, }; }
BirMa/components
projects/components/card/src/testing/card.harness.ts
<reponame>BirMa/components<filename>projects/components/card/src/testing/card.harness.ts import { BaseHarnessFilters, ContentContainerComponentHarness, HarnessPredicate, TestElement } from '@angular/cdk/testing'; import { PsHeaderHarness } from '@prosoft/components/header/src/testing/header.harness'; export interface PsCardHarnessFilters extends BaseHarnessFilters { caption?: string | RegExp; description?: string | RegExp; } export const enum PsCardSection { footer = '.mat-card-footer', actions = '.mat-card-actions', } export class PsCardHarness extends ContentContainerComponentHarness<PsCardSection> { static hostSelector = 'ps-card'; private _header = this.locatorForOptional(PsHeaderHarness); private _actionsChildren = this.locatorForAll(PsCardSection.actions + ' > *'); private _footerChildren = this.locatorForAll(PsCardSection.footer + ' > *'); static with(options: PsCardHarnessFilters = {}): HarnessPredicate<PsCardHarness> { return new HarnessPredicate(PsCardHarness, options) .addOption('caption', options.caption, (harness, title) => HarnessPredicate.stringMatches(harness.getCaptionText(), title)) .addOption('description', options.description, (harness, subtitle) => HarnessPredicate.stringMatches(harness.getDescriptionText(), subtitle) ); } async getHeader(): Promise<PsHeaderHarness> { return await this._header(); } async getActionTemplateNodes(): Promise<TestElement[]> { return (await this._actionsChildren()) ?? []; } async getFooterTemplateNodes(): Promise<TestElement[]> { return (await this._footerChildren()) ?? []; } private async getCaptionText(): Promise<string> { return (await this._header())?.getCaptionText() ?? ''; } private async getDescriptionText(): Promise<string> { return (await this._header())?.getDescriptionText() ?? ''; } }
BirMa/components
projects/components/table/src/directives/table.directives.ts
import { ContentChild, Directive, ElementRef, Input, TemplateRef } from '@angular/core'; @Directive({ selector: '[psTableColumnTemplate]' }) export class PsTableColumnTemplateDirective { constructor(public templateRef: TemplateRef<any>) {} } @Directive({ selector: '[psTableColumnHeaderTemplate]' }) export class PsTableColumnHeaderTemplateDirective { constructor(public templateRef: TemplateRef<any>) {} } @Directive({ // eslint-disable-next-line @angular-eslint/directive-selector selector: 'ps-table-column', }) export class PsTableColumnDirective { @Input() public header = ''; @Input() public property = ''; @Input() public sortable = true; @Input() public mandatory = false; @Input() public width = 'auto'; @Input() public headerStyles: { [key: string]: string } = {}; @Input() public columnStyles: { [key: string]: string } = {}; @ContentChild(PsTableColumnTemplateDirective, { read: TemplateRef }) public columnTemplate: TemplateRef<any> | null = null; @ContentChild(PsTableColumnHeaderTemplateDirective, { read: TemplateRef }) public headerTemplate: TemplateRef<any> | null = null; } @Directive({ selector: '[psTableTopButtonSection]', }) export class PsTableTopButtonSectionDirective { constructor(public el: ElementRef) {} } /** * @deprecated Please use actions from PsTableDataSource */ @Directive({ selector: '[psTableListActions]', }) export class PsTableListActionsDirective { constructor(public el: ElementRef) {} } /** * @deprecated Please use actions from PsTableDataSource */ @Directive({ selector: '[psTableRowActions]', }) export class PsTableRowActionsDirective { constructor(public el: ElementRef) {} } @Directive({ selector: '[psTableCustomHeader]', }) export class PsTableCustomHeaderDirective { constructor(public el: ElementRef) {} } @Directive({ selector: '[psTableCustomSettings]', }) export class PsTableCustomSettingsDirective { constructor(public el: ElementRef) {} } @Directive({ selector: '[psTableRowDetailTemplate]' }) export class PsTableRowDetailTemplateDirective { constructor(public templateRef: TemplateRef<any>) {} } @Directive({ // eslint-disable-next-line @angular-eslint/directive-selector selector: 'ps-table-row-detail', }) export class PsTableRowDetailDirective { /** Gibt an, ob die Row Details initial expanded sein sollen */ @Input() public expanded = false; @Input() public showToggleColumn: boolean | ((row: any) => boolean) = true; @ContentChild(PsTableRowDetailTemplateDirective, { read: TemplateRef }) public template: TemplateRef<any> | null = null; private expandedItems = new WeakSet(); private seenItems = new WeakSet(); public toggle(item: any, open?: boolean) { if (this.expandedItems.has(item)) { if (open === true) { return; } this.expandedItems.delete(item); } else { if (open === false) { return; } this.expandedItems.add(item); } } public isExpanded(item: any) { // Beim ersten Aufruf für ein Item expanden, wenn expanded === true if (this.expanded && !this.seenItems.has(item)) { this.expandedItems.add(item); this.seenItems.add(item); } return this.expandedItems.has(item); } }
BirMa/components
projects/prosoft-components-demo/src/app/select-demo/demos/select-with-other-load-trigger.component.ts
<filename>projects/prosoft-components-demo/src/app/select-demo/demos/select-with-other-load-trigger.component.ts import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { DefaultPsSelectDataSource, PsSelectDataSource, PsSelectLoadTrigger } from '@prosoft/components/select'; import { of } from 'rxjs'; import { delay } from 'rxjs/operators'; @Component({ selector: 'app-select-with-other-load-trigger', template: ` <h2>Custom load trigger with 1 second loading delay</h2> <div> <mat-radio-group [(ngModel)]="currentLoadTrigger" (change)="onTriggerChanged($event.value)"> <mat-radio-button value="initial">initial</mat-radio-button> <mat-radio-button value="firstopen">first panel open</mat-radio-button> <mat-radio-button value="everyopen">every panel open</mat-radio-button> </mat-radio-group> </div> <span [formGroup]="form"> <mat-form-field style="display:inline-block"> <mat-label>select</mat-label> <ps-select formControlName="select" [dataSource]="dataSource"></ps-select> </mat-form-field> </span> value: {{ form.value.select | json }}<br /> current load trigger: {{ currentLoadTrigger }}<br /> load trigger count: {{ loadCount }} <ul> <li>Initially '??? (ID: idx)' should be selected and load trigger should be 'initial' with count 1</li> <li>For load trigger 'first panel open' count should be 0, increase to 1 on first open. It should never go beyond 1</li> <li>For load trigger 'every panel open' count should be 0 and increase by 1 on every open</li> <li>When switching the load trigger, the selected value shouldn't vanish</li> </ul> `, changeDetection: ChangeDetectionStrategy.OnPush, }) export class SelectWithOtherLoadTriggerComponent { public dataSource: PsSelectDataSource; public currentLoadTrigger = 'initial'; public loadCount = 0; public form = new FormGroup({ select: new FormControl('idx'), }); constructor(private cd: ChangeDetectorRef) { this.onTriggerChanged(this.currentLoadTrigger); } public onTriggerChanged(value: string) { this.loadCount = 0; if (value === 'initial') { this.dataSource = this.createDataSource(PsSelectLoadTrigger.initial); } else if (value === 'firstopen') { this.dataSource = this.createDataSource(PsSelectLoadTrigger.firstPanelOpen); } else { this.dataSource = this.createDataSource(PsSelectLoadTrigger.everyPanelOpen); } this.cd.markForCheck(); } private createDataSource(loadTrigger: PsSelectLoadTrigger) { return new DefaultPsSelectDataSource<number>({ mode: 'id', idKey: 'value', labelKey: 'label', items: () => { this.loadCount++; const rnd1 = Math.random(); const rnd2 = Math.random(); return of([ { value: rnd1, label: 'item ' + rnd1, }, { value: rnd2, label: 'item ' + rnd2, }, ]).pipe(delay(1000)); }, loadTrigger: loadTrigger, }); } }
BirMa/components
projects/components/select/src/select.component.ts
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, DoCheck, ElementRef, EventEmitter, HostBinding, Input, OnDestroy, OnInit, Optional, Output, Self, TemplateRef, ViewChild, ViewEncapsulation, } from '@angular/core'; import { ControlValueAccessor, FormControl, FormGroupDirective, NgControl, NgForm } from '@angular/forms'; import { ErrorStateMatcher, MatOption, mixinDisabled, mixinErrorState } from '@angular/material/core'; import { MatFormFieldControl } from '@angular/material/form-field'; import { MatSelect, MatSelectChange } from '@angular/material/select'; import { BehaviorSubject, Subject, Subscription } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { getSelectUnknownDataSourceError } from './errors'; import { PsSelectItem } from './models'; import { DEFAULT_COMPARER, isPsSelectDataSource, PsSelectDataSource } from './select-data-source'; import { PsSelectOptionTemplateDirective } from './select-option-template.directive'; import { PsSelectTriggerTemplateDirective } from './select-trigger-template.directive'; import { PsSelectService } from './select.service'; const enum ValueChangeSource { matSelect = 1, toggleAll = 2, valueInput = 3, writeValue = 4, } // Boilerplate for applying mixins to MatSelect. /** @docs-private */ class PsSelectBase { constructor( public _elementRef: ElementRef, public _defaultErrorStateMatcher: ErrorStateMatcher, public _parentForm: NgForm, public _parentFormGroup: FormGroupDirective, public ngControl: NgControl ) {} } // eslint-disable-next-line @typescript-eslint/naming-convention const _PsSelectMixinBase = mixinDisabled(mixinErrorState(PsSelectBase)); @Component({ selector: 'ps-select', templateUrl: './select.component.html', styleUrls: ['./select.component.scss'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, // eslint-disable-next-line @angular-eslint/no-inputs-metadata-property inputs: ['disabled'], // eslint-disable-next-line @angular-eslint/no-host-metadata-property host: { '[class.ps-select-multiple]': 'multiple', '[class.ps-select-disabled]': 'disabled', '[class.ps-select-invalid]': 'errorState', '[class.ps-select-required]': 'required', '[class.ps-select-empty]': 'empty', class: 'ps-select', }, providers: [{ provide: MatFormFieldControl, useExisting: PsSelectComponent }], }) export class PsSelectComponent<T = unknown> extends _PsSelectMixinBase implements ControlValueAccessor, MatFormFieldControl<T>, DoCheck, OnInit, OnDestroy { public static nextId = 0; @HostBinding() public id = `ps-select-${PsSelectComponent.nextId++}`; @ContentChild(PsSelectOptionTemplateDirective, { read: TemplateRef }) public optionTemplate: TemplateRef<any> | null = null; @ContentChild(PsSelectTriggerTemplateDirective, { read: TemplateRef }) public triggerTemplate: TemplateRef<any> | null = null; @ViewChild(MatSelect, { static: true }) public set setMatSelect(select: MatSelect) { this._matSelect = select; // MatSelect doesn't trigger stateChanges on close which causes problems, so we patch it here. const close = select.close; select.close = () => { close.call(select); select.stateChanges.next(); }; } /** * Stream containing the latest information on what rows are being displayed on screen. * Can be used by the data source to as a heuristic of what data should be provided. */ public viewChange = new BehaviorSubject<{ start: number; end: number }>({ start: 0, end: Number.MAX_VALUE }); /** * The selects's source of data, which can be provided in three ways (in order of complexity): * - Simple data array (each object represents one select option) * - Stream that emits a data array each time the array changes * - `DataSource` object that implements the connect/disconnect interface. */ @Input() get dataSource(): any { return this._dataSourceInstance; } set dataSource(dataSource: any) { if (this._dataSourceInput !== dataSource) { this._dataSourceInput = dataSource; this._switchDataSource(dataSource); } } @Input() public get value(): T | null { return this._value; } public set value(value: T | null) { this._propagateValueChange(value, ValueChangeSource.valueInput); } private _value: T | null = null; /** If true, then there will be a empty option available to deselect any values (only single select mode) */ @Input() public clearable = true; /** If true, then there will be a toggle all checkbox available (only multiple select mode) */ @Input() public showToggleAll = true; @Input() public multiple = false; @Input() public override errorStateMatcher: ErrorStateMatcher = null; @Input() public panelClass: string | string[] | Set<string> | { [key: string]: any } = null; @Input() public placeholder: string = null; @Input() public required = false; /** * Event that emits whenever the raw value of the select changes. This is here primarily * to facilitate the two-way binding for the `value` input. * * @docs-private */ @Output() readonly valueChange: EventEmitter<T | null> = new EventEmitter<T | null>(); @Output() public readonly openedChange = new EventEmitter<boolean>(); @Output() public readonly selectionChange = new EventEmitter<MatSelectChange>(); public empty = true; public get shouldLabelFloat() { return !this.empty; } public get focused() { // eslint-disable-next-line import/no-deprecated return this._matSelect.focused; } public get compareWith(): (o1: any, o2: any) => boolean { return this._dataSourceInstance?.compareWith ?? DEFAULT_COMPARER; } public readonly controlType = 'ps-select'; /** FormControl for the search filter */ public filterCtrl = new FormControl(''); /** The items to display */ public items: PsSelectItem<T>[] | ReadonlyArray<PsSelectItem<T>> = []; public toggleAllCheckboxChecked = false; public toggleAllCheckboxIndeterminate = false; /** true while the options are loading */ public get loading(): boolean { return !!this._dataSourceInstance?.loading; } /** true when there was an error while loading the options */ public get hasError(): boolean { return !!this.error; } /** the error that occured while loading the options */ public get error() { return this._dataSourceInstance?.error; } /** If true, then the empty option should be shown. */ public get showEmptyInput() { if (this.multiple || !this.clearable || !this.items?.length) { return false; } const searchText = (this.filterCtrl.value || '').toLowerCase(); return !searchText || '--'.indexOf(searchText) > -1; } public get tooltip(): string { // MatSelect is not fully initialized in the beginning, so we need to skip this here until it is ready if (this.multiple && this._matSelect?._selectionModel && this._matSelect.selected) { return (<MatOption[]>this._matSelect.selected).map((x) => x.viewValue).join(', '); } return ''; } /** The value displayed in the trigger. */ get customTriggerData(): { value: string; viewValue: string } | { value: string; viewValue: string }[] { if (this.empty) { return null; } const selectedOptions = this._matSelect._selectionModel.selected.map(toTriggerDataObj); if (this.multiple) { if (this._matSelect._isRtl()) { selectedOptions.reverse(); } return selectedOptions; } return selectedOptions[0]; function toTriggerDataObj(option: MatOption): { value: string; viewValue: string } { return { value: option.value, viewValue: option.viewValue, }; } } /** Subject that emits when the component has been destroyed. */ private _ngUnsubscribe$ = new Subject<void>(); /** Subscription that listens for the data provided by the data source. */ private _renderChangeSubscription = Subscription.EMPTY; /** The data source. */ private _dataSourceInstance: PsSelectDataSource<T>; /** The value the [dataSource] input was called with. */ private _dataSourceInput: any; private _matSelect!: MatSelect; private _onInitCalled = false; /** View -> model callback called when value changes */ private _onChange: (value: any) => void = () => {}; constructor( elementRef: ElementRef, defaultErrorStateMatcher: ErrorStateMatcher, private selectService: PsSelectService, private cd: ChangeDetectorRef, @Optional() parentForm: NgForm, @Optional() parentFormGroup: FormGroupDirective, @Optional() @Self() public override ngControl: NgControl ) { super(elementRef, defaultErrorStateMatcher, parentForm, parentFormGroup, ngControl); if (this.ngControl) { // Note: we provide the value accessor through here, instead of // the `providers` to avoid running into a circular import. this.ngControl.valueAccessor = this; } } public ngDoCheck() { if (this.ngControl) { this.updateErrorState(); } } public ngOnInit() { this._onInitCalled = true; // before oninit ngControl.control isn't set, but it is needed for datasource creation this._switchDataSource(this._dataSourceInput); this.filterCtrl.valueChanges .pipe(takeUntil(this._ngUnsubscribe$)) .subscribe((searchText) => this.dataSource.searchTextChanged(searchText)); this._matSelect.stateChanges.pipe(takeUntil(this._ngUnsubscribe$)).subscribe(this.stateChanges); } public ngOnDestroy() { this._ngUnsubscribe$.next(); this._ngUnsubscribe$.complete(); this.viewChange.complete(); this._renderChangeSubscription.unsubscribe(); } public onContainerClick(_: MouseEvent): void { this._matSelect.onContainerClick(); } public setDescribedByIds(ids: string[]): void { this._matSelect.setDescribedByIds(ids); } public writeValue(value: any) { this._propagateValueChange(value, ValueChangeSource.writeValue); } public registerOnChange(fn: () => void) { this._onChange = fn; } public registerOnTouched(fn: any): void { this._matSelect.registerOnTouched(fn); } public setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } public onSelectionChange(event: MatSelectChange) { this._updateToggleAllCheckbox(); this.selectionChange.emit(event); } public onOpenedChange(open: boolean) { this.openedChange.emit(open); this._dataSourceInstance.panelOpenChanged(open); } public onValueChange(value: any) { this._propagateValueChange(value, ValueChangeSource.matSelect); } public onToggleAll(state: boolean) { const newValue = state ? (this.items as PsSelectItem<T>[]).map((x) => x.value) : []; this._propagateValueChange(newValue, ValueChangeSource.toggleAll); } public trackByOptions(_: number, item: PsSelectItem<T>) { return `${item.value}#${item.label}`; } private _propagateValueChange(value: any, source: ValueChangeSource) { this._value = value; this.empty = this.multiple ? !value?.length : !value; this._updateToggleAllCheckbox(); this._pushSelectedValuesToDataSource(value); if (source !== ValueChangeSource.valueInput) { this.valueChange.emit(value); } if (source !== ValueChangeSource.writeValue) { this._onChange(value); } this.cd.markForCheck(); } private _pushSelectedValuesToDataSource(value: any): void { if (!this._dataSourceInstance) { return; } let values: any[]; if (this.multiple) { values = Array.isArray(value) ? value : []; } else { values = value ? [value] : []; } this._dataSourceInstance.selectedValuesChanged(values); } /** Set up a subscription for the data provided by the data source. */ private _switchDataSource(dataSource: any) { if (!this._onInitCalled) { // before oninit ngControl.control isn't set, but it is needed for datasource creation return; } // Stop listening for data from the previous data source. this._dataSourceInstance?.disconnect(); this._renderChangeSubscription.unsubscribe(); this._dataSourceInstance = this.selectService.createDataSource(dataSource, this.ngControl?.control); if (!isPsSelectDataSource(this._dataSourceInstance)) { throw getSelectUnknownDataSourceError(); } this._dataSourceInstance.searchTextChanged(this.filterCtrl.value); this._dataSourceInstance.panelOpenChanged(this._matSelect.panelOpen); this._pushSelectedValuesToDataSource(this._value); this._renderChangeSubscription = this._dataSourceInstance.connect().subscribe((items) => { this.items = items || []; this._updateToggleAllCheckbox(); this.cd.markForCheck(); }); } private _updateToggleAllCheckbox() { if (this.multiple && this.items && Array.isArray(this._value)) { const selectedValueCount = this._value.length; this.toggleAllCheckboxChecked = this.items.length === selectedValueCount; this.toggleAllCheckboxIndeterminate = selectedValueCount > 0 && selectedValueCount < this.items.length; } } }
BirMa/components
projects/components/schematics/ps-select-load-trigger-and-sort-by-rename/index_spec.ts
import { Tree, FileEntry } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; const tsContent = ` import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core'; import { PsSelectLoadTrigger, PsSelectSortBy } from '@prosoft/components/select'; @Component({ selector: 'app-some-component', templateUrl: './some-template.html', styles: ['./some-styles.scss'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class SomeComponent { public loadTriggerInitial = PsSelectLoadTrigger.Initial; public loadTriggerFirstPanelOpen = PsSelectLoadTrigger.FirstPanelOpen; public loadTriggerEveryPanelOpen = PsSelectLoadTrigger.EveryPanelOpen; public loadTriggerAll = PsSelectLoadTrigger.All; public noSort = PsSelectSortBy.None; public sortBySelected = PsSelectSortBy.Selected; public sortByComparer = PsSelectSortBy.Comparer; public sortByBoth = PsSelectSortBy.Both; constructor() {} } `; const tsModifiedContent = ` import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core'; import { PsSelectLoadTrigger, PsSelectSortBy } from '@prosoft/components/select'; @Component({ selector: 'app-some-component', templateUrl: './some-template.html', styles: ['./some-styles.scss'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class SomeComponent { public loadTriggerInitial = PsSelectLoadTrigger.initial; public loadTriggerFirstPanelOpen = PsSelectLoadTrigger.firstPanelOpen; public loadTriggerEveryPanelOpen = PsSelectLoadTrigger.everyPanelOpen; public loadTriggerAll = PsSelectLoadTrigger.all; public noSort = PsSelectSortBy.none; public sortBySelected = PsSelectSortBy.selected; public sortByComparer = PsSelectSortBy.comparer; public sortByBoth = PsSelectSortBy.both; constructor() {} } `; describe('ps-select-load-trigger-and-sort-by-rename', () => { it('should work with empty tree', async () => { const runner = new SchematicTestRunner('test', require.resolve('../migrations.json')); const tree = await runner.runSchematicAsync('ps-select-load-trigger-and-sort-by-rename', {}, Tree.empty()).toPromise(); expect(tree.files).toEqual([]); }); it('should rename LoadTrigger and SortBy enum values from PascalCase to camelCase for paths not blacklisted', async () => { const runner = new SchematicTestRunner('test', require.resolve('../migrations.json')); const tree = Tree.empty(); tree.create('/app.component.ts', tsContent); tree.create('/multiple/sub/folders/test.component.ts', tsContent); const resultTree = await runner.runSchematicAsync('ps-select-load-trigger-and-sort-by-rename', {}, tree).toPromise(); expect(resultTree.files).toEqual(['/app.component.ts', '/multiple/sub/folders/test.component.ts']); validateFile(resultTree.get('/app.component.html'), true); validateFile(resultTree.get('/multiple/sub/folders/test.component.html'), true); }); it('should skip non .ts files', async () => { const runner = new SchematicTestRunner('test', require.resolve('../migrations.json')); const tree = Tree.empty(); tree.create('/html.component.html', tsContent); tree.create('/json.component.json', tsContent); tree.create('/scss.component.scss', tsContent); const resultTree = await runner.runSchematicAsync('ps-select-load-trigger-and-sort-by-rename', {}, tree).toPromise(); expect(resultTree.files).toEqual(['/html.component.html', '/json.component.json', '/scss.component.scss']); validateFile(resultTree.get('/html.component.html'), false); validateFile(resultTree.get('/json.component.json'), false); validateFile(resultTree.get('/scss.component.scss'), false); }); it('should skip dist, angular and node_modules folders', async () => { const runner = new SchematicTestRunner('test', require.resolve('../migrations.json')); const tree = Tree.empty(); tree.create('/dist/dist.component.ts', tsContent); tree.create('/.angular/angular.component.ts', tsContent); tree.create('/some-folder/node_modules/node.component.ts', tsContent); const resultTree = await runner.runSchematicAsync('ps-select-load-trigger-and-sort-by-rename', {}, tree).toPromise(); expect(resultTree.files).toEqual([ '/dist/dist.component.ts', '/.angular/angular.component.ts', '/some-folder/node_modules/node.component.ts', ]); validateFile(resultTree.get('/dist/dist.component.ts'), false); validateFile(resultTree.get('/.angular/angular.component.ts'), false); validateFile(resultTree.get('/some-folder/node_modules/node.component.ts'), false); }); function validateFile(file: FileEntry | null, changed: boolean) { expect(file).toBeDefined(); if (file) { expect(file.content.toString()).toEqual(changed ? tsModifiedContent : tsContent); } } });
BirMa/components
projects/components/utils/src/auto-form-array.spec.ts
<reponame>BirMa/components import { FormControl, Validators } from '@angular/forms'; import { of } from 'rxjs'; import { AutoFormArray } from './auto-form-array'; describe('AutoFormArray', () => { it('should initialize FormArray when constructed', () => { const asyncValidator = () => of(null); const array = new AutoFormArray(() => new FormControl(''), Validators.required, asyncValidator); expect(array.length).toEqual(0); expect(array.validator).toEqual(Validators.required); expect(array.asyncValidator).toEqual(asyncValidator); }); it('should add subforms when resizeTo is called with a higher value than length', () => { const array = new AutoFormArray(() => new FormControl('')); array.push(new FormControl(0)); array.resizeTo(3); expect(array.length).toBe(3); expect(array.value).toEqual([0, '', '']); }); it('should remove subforms when resizeTo is called with a lower value than length', () => { const array = new AutoFormArray(() => new FormControl('')); array.push(new FormControl(0)); array.push(new FormControl(1)); array.push(new FormControl(2)); array.resizeTo(2); expect(array.length).toBe(2); expect(array.value).toEqual([0, 1]); }); it('should not modify subforms when resizeTo is called with same value than length', () => { const array = new AutoFormArray(() => new FormControl('')); array.push(new FormControl(0)); array.push(new FormControl(1)); array.push(new FormControl(2)); array.resizeTo(3); expect(array.length).toBe(3); expect(array.value).toEqual([0, 1, 2]); }); it('should add subforms disabled if FormArray is disabled', () => { const array = new AutoFormArray(() => new FormControl('')); array.push(new FormControl(0)); array.disable(); array.resizeTo(3); for (const ctrl of array.controls) { expect(ctrl.disabled).toBeTruthy(); } }); it('should add subforms enabled if FormArray is enabled', () => { const array = new AutoFormArray(() => new FormControl('')); array.push(new FormControl(0)); array.resizeTo(3); for (const ctrl of array.controls) { expect(ctrl.disabled).toBeFalsy(); } }); it('should adjust number of subforms when patchValue is called', () => { const array = new AutoFormArray(() => new FormControl('')); spyOn(array, 'resizeTo').and.callThrough(); array.patchValue([0, 1, 2, 3]); expect(array.resizeTo).toHaveBeenCalledWith(4); expect(array.length).toBe(4); expect(array.value).toEqual([0, 1, 2, 3]); }); it('should adjust number of subforms when reset is called', () => { const array = new AutoFormArray(() => new FormControl('')); spyOn(array, 'resizeTo').and.callThrough(); array.reset([0, 1, 2, 3]); expect(array.resizeTo).toHaveBeenCalledWith(4); expect(array.length).toBe(4); expect(array.value).toEqual([0, 1, 2, 3]); }); it('should NOT adjust number of subforms when setValue is called', () => { const array = new AutoFormArray(() => new FormControl('')); spyOn(array, 'resizeTo').and.callThrough(); expect(() => array.setValue([0, 1, 2, 3])).toThrow(); expect(array.resizeTo).not.toHaveBeenCalled(); expect(array.length).toBe(0); expect(array.value).toEqual([]); }); });
BirMa/components
projects/components/form/src/form.component.spec.ts
import { CommonModule } from '@angular/common'; import { ChangeDetectionStrategy, Component, DebugElement, Injectable, ViewChild } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { FormGroup } from '@angular/forms'; import { MatIcon } from '@angular/material/icon'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { PsBlockUiComponent } from '@prosoft/components/block-ui'; import { PsIntlService, PsIntlServiceEn } from '@prosoft/components/core'; import { BasePsFormService, IPsFormError, IPsFormErrorData, PsFormService } from '@prosoft/components/form-base'; import { Observable, of, Subject, Subscription } from 'rxjs'; import { IPsFormDataSource, IPsFormDataSourceConnectOptions } from './form-data-source'; import { dependencies, PsFormComponent } from './form.component'; import { PsFormModule } from './form.module'; @Injectable() class TestPsFormService extends BasePsFormService { constructor() { super(); this.options.debounceTime = null; } public getLabel(formControl: any): Observable<string> | null { return formControl.psLabel ? of(formControl.psLabel) : null; } protected mapDataToError(errorData: IPsFormErrorData[]): Observable<IPsFormError[]> { return of( errorData.map((data) => ({ errorText: data.errorKey, data: data, })) ); } } @Component({ selector: 'ps-test-component', template: ` <ps-form [dataSource]="dataSource"> <div id="content">content text</div> <div id="hight-strech" style="height: 2000px;">hight strech</div> <ng-container psFormSavebarButtons> <button type="button">btnCus</button> </ng-container> </ps-form> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestDataSourceComponent { public dataSource: IPsFormDataSource; @ViewChild(PsFormComponent) formComponent: PsFormComponent; } describe('PsFormComponent', () => { describe('integration with dataSource', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule, CommonModule, PsFormModule], declarations: [TestDataSourceComponent], providers: [ { provide: PsFormService, useClass: TestPsFormService }, { provide: PsIntlService, useClass: PsIntlServiceEn }, ], }).compileComponents(); }) ); it('should render buttons correctly', async () => { const fixture = TestBed.createComponent(TestDataSourceComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); let btn2Clicked = false; component.dataSource = createDataSource({ buttons: [ { type: 'stroked', label: 'btn1', color: 'primary', disabled: () => true, click: () => {} }, { type: 'raised', label: 'btn2', color: 'accent', disabled: () => false, click: () => { btn2Clicked = true; }, }, ], }); fixture.detectChanges(); const buttons = getButtons(fixture); expect(buttons.length).toBe(3); { const customButton = buttons.find((x) => x.nativeElement.textContent === 'btnCus'); expect(customButton).toBeTruthy(); } { const btn1Button = buttons.find((x) => x.nativeElement.textContent.trim() === 'btn1'); expect(btn1Button).toBeTruthy(); const btn1Classes = getClasses(btn1Button); expect(btn1Classes).toContain('mat-stroked-button'); expect(btn1Classes).toContain('mat-primary'); expect(btn1Button.attributes.type).toEqual('button'); expect(btn1Button.attributes.disabled).toEqual('true'); } { const btn2Button = buttons.find((x) => x.nativeElement.textContent.trim() === 'btn2'); expect(btn2Button).toBeTruthy(); const btn2Classes = getClasses(btn2Button); expect(btn2Classes).toContain('mat-raised-button'); expect(btn2Classes).toContain('mat-accent'); expect(btn2Button.attributes.type).toEqual('button'); expect(btn2Button.attributes.disabled).toBeFalsy(); btn2Button.triggerEventHandler('click', null); expect(btn2Clicked).toBeTruthy(); } }); it('should show error view, when exception property is not null', async () => { const fixture = TestBed.createComponent(TestDataSourceComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); const dataSource = createDataSource(); component.dataSource = dataSource; fixture.detectChanges(); expect(getErrorContainer(fixture)).toBe(null); dataSource.exception = { errorObject: null, }; dataSource.cdTrigger$.next(); fixture.detectChanges(); let errorContainer = getErrorContainer(fixture); expect(errorContainer).not.toBe(null); expect(errorContainer.classes['ps-form__error-container--center']).toBeFalsy(); expect(getErrorIcon(fixture)).toBe(null); expect(getErrorText(fixture)).toBe(''); dataSource.exception.errorObject = new Error('error1'); dataSource.cdTrigger$.next(); fixture.detectChanges(); errorContainer = getErrorContainer(fixture); expect(errorContainer).not.toBe(null); expect(errorContainer.classes['ps-form__error-container--center']).toBeFalsy(); expect(getErrorIcon(fixture)).toBe(null); expect(getErrorText(fixture)).toBe('error1'); dataSource.exception.alignCenter = true; dataSource.cdTrigger$.next(); fixture.detectChanges(); errorContainer = getErrorContainer(fixture); expect(errorContainer.classes['ps-form__error-container--center']).toBe(true); dataSource.exception.icon = 'asdf-icon'; dataSource.cdTrigger$.next(); fixture.detectChanges(); expect(getErrorIcon(fixture).nativeElement.textContent.trim()).toBe('asdf-icon'); expect(getErrorText(fixture)).toBe('error1'); }); it('should block ui when contentBlocked is true', async () => { const fixture = TestBed.createComponent(TestDataSourceComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); const dataSource = createDataSource(); component.dataSource = dataSource; fixture.detectChanges(); const blockUi = getBlockUi(fixture); expect(blockUi.componentInstance.blocked).toBe(false); dataSource.contentBlocked = true; dataSource.cdTrigger$.next(); fixture.detectChanges(); expect(blockUi.componentInstance.blocked).toBe(true); }); it('should hide content when contentVisible is false', async () => { const fixture = TestBed.createComponent(TestDataSourceComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); const dataSource = createDataSource(); component.dataSource = dataSource; fixture.detectChanges(); let contentNode = fixture.debugElement.query(By.css('#content')); expect(contentNode).toBeTruthy(); dataSource.contentVisible = false; dataSource.cdTrigger$.next(); fixture.detectChanges(); contentNode = fixture.debugElement.query(By.css('#content')); expect(contentNode).toBeFalsy(); }); it("should call dataSource's connect() once per new dataSource", () => { const fixture = TestBed.createComponent(TestDataSourceComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); const ds1 = createDataSource(); component.dataSource = ds1; spyOn(ds1, 'connect').and.callThrough(); fixture.detectChanges(); expect(ds1.connect).toHaveBeenCalledTimes(1); const ds2 = createDataSource(); component.dataSource = ds2; spyOn(ds1, 'disconnect').and.callThrough(); spyOn(ds2, 'connect').and.callThrough(); fixture.detectChanges(); expect(ds2.connect).toHaveBeenCalledTimes(1); expect(ds1.disconnect).toHaveBeenCalledTimes(1); }); it('should handle scrolling to error card and visibility updates correctly', async () => { let intersectCallback: (x: any) => void; let observedEl: any; let observerOptions: any; dependencies.intersectionObserver = function mockIO(callback: any, options: any) { intersectCallback = callback; observerOptions = options; return { observe: (el: any) => { observedEl = el; }, disconnect: () => {}, }; } as any; const fixture = TestBed.createComponent(TestDataSourceComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); const ds = createDataSource(); const errorInViewValues: boolean[] = []; let opts: IPsFormDataSourceConnectOptions; let errorInViewSub: Subscription; ds.connect = (options) => { opts = options; expect(errorInViewSub).not.toBeDefined(); errorInViewSub = options.errorInView$.subscribe((value) => errorInViewValues.push(value)); return ds.cdTrigger$; }; ds.exception = { errorObject: new Error('asdf') }; component.dataSource = ds; fixture.detectChanges(); expect(opts).toBeDefined(); expect(observerOptions).toEqual({ root: null as any, rootMargin: '-100px', threshold: 0, }); expect(getErrorContainer(fixture)).not.toBe(null); expect(observedEl).toBe(component.formComponent.errorCardWrapper.nativeElement); spyOn(component.formComponent.errorCardWrapper.nativeElement, 'scrollIntoView').and.callThrough(); opts.scrollToError(); expect(component.formComponent.errorCardWrapper.nativeElement.scrollIntoView).toHaveBeenCalledTimes(1); intersectCallback([{ intersectionRatio: 1 }]); intersectCallback([{ intersectionRatio: 1 }]); intersectCallback([{ intersectionRatio: 0 }]); expect(errorInViewValues).toEqual([false, true, false]); errorInViewSub.unsubscribe(); }); }); }); type ITestPsFormDataSource = { -readonly [K in keyof IPsFormDataSource]: IPsFormDataSource[K]; }; function createDataSource(override: Partial<IPsFormDataSource> = {}): ITestPsFormDataSource & { cdTrigger$: Subject<void> } { const cdTrigger$ = new Subject<void>(); return { autocomplete: 'off', cdTrigger$: cdTrigger$, buttons: [], contentBlocked: false, contentVisible: true, exception: null, savebarMode: 'auto', form: new FormGroup({}), connect: () => cdTrigger$, disconnect: () => {}, ...override, }; } function getButtons(fixture: ComponentFixture<TestDataSourceComponent>): DebugElement[] { return fixture.debugElement.query(By.css('.ps-form__buttons')).children; } function getClasses(node: DebugElement): string[] { return (node.nativeElement.className as string).split(' '); } function getBlockUi(fixture: ComponentFixture<any>): DebugElement { return fixture.debugElement.query(By.directive(PsBlockUiComponent)); } function getErrorContainer(fixture: ComponentFixture<any>): DebugElement { return fixture.debugElement.query(By.css('.ps-form__error-container')); } function getErrorIcon(fixture: ComponentFixture<any>): DebugElement { return getErrorContainer(fixture).query(By.directive(MatIcon)); } function getErrorText(fixture: ComponentFixture<any>): string { let errorText: string = getErrorContainer(fixture).nativeElement.textContent.trim(); const errorIconNode = getErrorIcon(fixture); if (errorIconNode) { const errorIconText = errorIconNode.nativeElement.textContent.trim(); errorText = errorText.substr(errorIconText.length); } return errorText; }
BirMa/components
projects/prosoft-components-demo/src/app/select-demo/select-demo.component.ts
<gh_stars>0 import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewEncapsulation } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { DefaultPsSelectDataSource, PsSelectLoadTrigger, PsSelectSortBy } from '@prosoft/components/select'; import { NEVER, of, throwError } from 'rxjs'; import { tap, delay } from 'rxjs/operators'; declare type DemoDataSourceItems = 'default' | 'error' | 'loading' | 'empty'; interface DemoLogs { loadCount: number; } @Component({ selector: 'app-select-demo', template: ` <div class="app-select-demo__settings"> <mat-card class="app-select-demo__settings-box"> <strong>ps-select</strong> <span>[dataSource] = new DefaultPsSelectDataSource(...)</span> <mat-checkbox [(ngModel)]="multiple" (change)="recreate()">[multiple]</mat-checkbox> <mat-checkbox [(ngModel)]="clearable">[clearable]</mat-checkbox> <mat-checkbox [(ngModel)]="disabled" (change)="disabledChanged()">[disabled]</mat-checkbox> <mat-checkbox [(ngModel)]="required">[required]</mat-checkbox> <span>[errorStateMatcher]</span> <mat-checkbox [(ngModel)]="panelClass">[panelClass] (color: green)</mat-checkbox> <div>(openedChange) $event = boolean</div> <div>(selectionChange) $event = MatSelectChange</div> <mat-checkbox [(ngModel)]="customTriggerTpl">*psSelectTriggerTemplate="let item"</mat-checkbox> <mat-checkbox [(ngModel)]="customOptionTpl">*psSelectOptionTemplate="let item"</mat-checkbox> </mat-card> <mat-card class="app-select-demo__settings-box"> <strong>DefaultPsSelectDataSource</strong> <mat-form-field> <mat-label>items</mat-label> <mat-select [(ngModel)]="dataSourceItems" (selectionChange)="resetDataSource()"> <mat-option [value]="'default'">500 items</mat-option> <mat-option [value]="'error'">error while loading</mat-option> <mat-option [value]="'loading'">endless loading</mat-option> <mat-option [value]="'empty'">empty result</mat-option> </mat-select> </mat-form-field> <strong>items array</strong> <mat-checkbox [(ngModel)]="itemsAsObservable" (change)="resetDataSource()">wrapped in observable</mat-checkbox> <mat-checkbox [(ngModel)]="itemsAsFunction" (change)="resetDataSource()">result of load function</mat-checkbox> <mat-form-field> <mat-label>mode</mat-label> <mat-select [(ngModel)]="dataSourceMode" (selectionChange)="resetDataSource()"> <mat-option [value]="'id'">id</mat-option> <mat-option [value]="'entity'">entity</mat-option> </mat-select> </mat-form-field> <mat-form-field> <mat-label>idKey</mat-label> <mat-select [(ngModel)]="dataSourceIdKey" (selectionChange)="resetDataSource()"> <mat-option [value]="'id'">id property</mat-option> <mat-option [value]="'strId'">strId property</mat-option> </mat-select> </mat-form-field> <mat-form-field> <mat-label>labelKey</mat-label> <mat-select [(ngModel)]="dataSourceLabelKey" (selectionChange)="resetDataSource()"> <mat-option [value]="'labelA'">labelA property</mat-option> <mat-option [value]="'labelB'">labelB property</mat-option> </mat-select> </mat-form-field> <mat-form-field> <mat-label>searchDebounce</mat-label> <input matInput type="number" [(ngModel)]="dataSourceSearchDebounce" (change)="resetDataSource()" /> </mat-form-field> <strong>loadTrigger</strong> <mat-checkbox [(ngModel)]="loadTriggerInitial" (change)="resetDataSource()">Initial</mat-checkbox> <mat-checkbox [(ngModel)]="loadTriggerFirstPanelOpen" (change)="resetDataSource()">FirstPanelOpen</mat-checkbox> <mat-checkbox [(ngModel)]="loadTriggerEveryPanelOpen" (change)="resetDataSource()">EveryPanelOpen</mat-checkbox> <strong>sortBy</strong> <mat-checkbox [(ngModel)]="sortBySelected" (change)="resetDataSource()">Selected</mat-checkbox> <mat-checkbox [(ngModel)]="sortByComparer" (change)="resetDataSource()">Comparer</mat-checkbox> <strong>sortCompare</strong> <mat-checkbox [(ngModel)]="reverseSort" (change)="resetDataSource()">custom (reverse by id)</mat-checkbox> </mat-card> </div> <mat-card *ngIf="visible" style="margin-bottom: 1em;"> <mat-form-field style="width: 100%;"> <mat-label>ngModel</mat-label> <ps-select [(ngModel)]="ngModel" [dataSource]="ngModelDataSource" [multiple]="multiple" [clearable]="clearable" [disabled]="disabled" [required]="required" [panelClass]="{ 'app-select-demo__panel': panelClass }" > <ng-container *ngIf="customTriggerTpl"> <ng-container *psSelectTriggerTemplate="let item"> {{ item | json }} </ng-container> </ng-container> <ng-container *ngIf="customOptionTpl"> <ng-container *psSelectOptionTemplate="let item"> {{ item | json }} </ng-container> </ng-container> </ps-select> </mat-form-field> <div [formGroup]="form"> <mat-form-field style="width: 100%;"> <mat-label>FormControl</mat-label> <ps-select formControlName="ctrl" [dataSource]="formDataSource" [multiple]="multiple" [clearable]="clearable" [disabled]="disabled" [required]="required" [panelClass]="{ 'app-select-demo__panel': panelClass }" > <ng-container *ngIf="customTriggerTpl"> <ng-container *psSelectTriggerTemplate="let item"> {{ item | json }} </ng-container> </ng-container> <ng-container *ngIf="customOptionTpl"> <ng-container *psSelectOptionTemplate="let item"> {{ item | json }} </ng-container> </ng-container> </ps-select> </mat-form-field> </div> </mat-card> <mat-card style="margin-bottom: 1em;"> <strong>ngModel logs</strong> <div>value: {{ ngModel | json }}</div> <div>load count: {{ ngModelLogs.loadCount }}</div> </mat-card> <mat-card style="margin-bottom: 1em;"> <strong>FormControl logs</strong> <div>value: {{ form.value.ctrl | json }}</div> <div>load count: {{ formLogs.loadCount }}</div> </mat-card> <app-select-with-multiselect></app-select-with-multiselect> <app-select-with-events-only></app-select-with-events-only> <app-select-with-ng-model></app-select-with-ng-model> <app-select-with-selected-item-not-in-datasource></app-select-with-selected-item-not-in-datasource> <app-select-with-endless-loading-datasource></app-select-with-endless-loading-datasource> <app-select-with-error-in-datasource></app-select-with-error-in-datasource> <app-select-with-other-load-trigger></app-select-with-other-load-trigger> <app-select-with-custom-select-service></app-select-with-custom-select-service> <app-select-with-custom-template></app-select-with-custom-template> <app-select-with-error-state-matcher></app-select-with-error-state-matcher> `, styles: [ ` .app-select-demo__settings { display: grid !important; grid-auto-flow: column; gap: 1em; margin-bottom: 1em; } .app-select-demo__settings-box { display: grid !important; gap: 1em; align-content: start; } .app-select-demo__panel .mat-option-text { color: green; } `, ], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class SelectDemoComponent implements OnInit { public visible = true; public ngModel: any = null; public form = new FormGroup({ ctrl: new FormControl(null), }); public items = Array.from(Array(500).keys()).map((i) => ({ id: i, strId: `id${i}`, labelA: `Label A ${i}`, labelB: `Label B ${i}`, disabled: i % 5 === 4, })); public unknowIitem = { id: -1, strId: `id-1`, labelA: `Label A -1`, labelB: `Label B -1`, }; public ngModelDataSource: DefaultPsSelectDataSource; public formDataSource: DefaultPsSelectDataSource; public multiple = false; public clearable = true; public disabled = false; public required = false; public panelClass = false; public customTriggerTpl = false; public customOptionTpl = false; public dataSourceItems: DemoDataSourceItems = 'default'; public dataSourceMode: 'id' | 'entity' = 'id'; public dataSourceIdKey = 'id'; public dataSourceLabelKey = 'labelA'; public dataSourceSearchDebounce = 300; public loadTriggerInitial = true; public loadTriggerFirstPanelOpen = false; public loadTriggerEveryPanelOpen = false; public sortBySelected = true; public sortByComparer = true; public reverseSort = false; public itemsAsObservable = false; public itemsAsFunction = false; public ngModelLogs: DemoLogs = { loadCount: 0 }; public formLogs: DemoLogs = { loadCount: 0 }; constructor(private cd: ChangeDetectorRef) {} public ngOnInit() { this.resetDataSource(); } public createDataSource(logs: DemoLogs) { const ds = new DefaultPsSelectDataSource({ mode: this.dataSourceMode, idKey: this.dataSourceIdKey, labelKey: this.dataSourceLabelKey, disabledKey: 'disabled', items: this.getDataSourceItems(logs), searchDebounce: this.dataSourceSearchDebounce, loadTrigger: this.getPsSelectLoadTrigger(), sortBy: this.getPsSelectSortBy(), }); if (this.reverseSort) { ds.sortCompare = (a, b) => b.entity.id - a.entity.id; } return ds; } public getPsSelectLoadTrigger() { return ( // eslint-disable-next-line no-bitwise (this.loadTriggerInitial && PsSelectLoadTrigger.initial) | (this.loadTriggerFirstPanelOpen && PsSelectLoadTrigger.firstPanelOpen) | (this.loadTriggerEveryPanelOpen && PsSelectLoadTrigger.everyPanelOpen) ); } public getPsSelectSortBy() { // eslint-disable-next-line no-bitwise return (this.sortBySelected && PsSelectSortBy.selected) | (this.sortByComparer && PsSelectSortBy.comparer); } public getDataSourceItems(logs: DemoLogs) { logs.loadCount = 0; switch (this.dataSourceItems) { case 'default': let items: any = this.items; if (this.itemsAsObservable) { items = of(items).pipe( tap(() => { ++logs.loadCount; }), delay(1000) ); } if (this.itemsAsFunction) { const originalItems = items; items = () => { ++logs.loadCount; return originalItems; }; } return items; case 'empty': return []; case 'loading': return NEVER; case 'error': return throwError(new Error('loading failed')); } } public resetDataSource() { this.ngModelDataSource = this.createDataSource(this.ngModelLogs); this.formDataSource = this.createDataSource(this.formLogs); } public patchUnknownItem() { const item = this.multiple ? [this.unknowIitem] : this.unknowIitem; this.ngModel = item; this.form.patchValue({ ctrl: item }); } public disabledChanged() { if (this.disabled) { this.form.disable(); } else { this.form.enable(); } } public recreate() { this.visible = false; setTimeout(() => { this.resetDataSource(); this.visible = true; this.cd.markForCheck(); }, 0); } }
BirMa/components
projects/components/table/src/subcomponents/table-actions.component.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output, SimpleChanges, ViewChild } from '@angular/core'; import { MatMenu } from '@angular/material/menu'; import { IPsTableIntlTexts } from '@prosoft/components/core'; import { IPsTableAction } from '../models'; @Component({ selector: 'ps-table-actions', templateUrl: './table-actions.component.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class PsTableActionsComponent implements OnChanges { @Input() public root = true; @Input() public actions: IPsTableAction<unknown>[]; @Input() public items: unknown[]; @Input() public refreshable: boolean; @Input() public settingsEnabled: boolean; @Input() public intl: IPsTableIntlTexts; @Output() public readonly refreshData = new EventEmitter<void>(); @Output() public readonly showSettings = new EventEmitter<void>(); public showIcon: boolean; @ViewChild('menu', { static: true }) menu: MatMenu; public ngOnChanges(changes: SimpleChanges): void { if (changes.root || changes.actions) { this.showIcon = this.root || this.actions?.some((x) => x.icon); } } }
BirMa/components
projects/components/table/src/helper/table.helper.ts
<filename>projects/components/table/src/helper/table.helper.ts<gh_stars>0 import { coerceNumberProperty } from '@angular/cdk/coercion'; import { IPsTableUpdateDataInfo } from '../models'; export function asQueryParams(settings: IPsTableUpdateDataInfo): string { return [settings.pageSize, settings.currentPage, settings.searchText, settings.sortColumn, settings.sortDirection].join('◬'); } export function fromQueryParams(settingsString: string): IPsTableUpdateDataInfo { if (!settingsString) { return null; } const settings = settingsString.split('◬', 5); if (!settings.reduce((prev, curr) => prev || !!curr, false)) { return null; } return { pageSize: coerceNumberProperty(settings[0], null), currentPage: coerceNumberProperty(settings[1], null), searchText: settings[2] || null, sortColumn: settings[3] || null, sortDirection: coerceSortDirectionProperty(settings[4], null), }; } function coerceSortDirectionProperty(input: unknown, fallback: 'asc' | 'desc' | null): 'asc' | 'desc' | null { const inputStr = (input + '').toLowerCase(); if (inputStr === 'asc' || inputStr === 'desc') { return inputStr; } return fallback; } /** * Whether the provided value is considered a number. * * @docs-private */ export function _isNumberValue(value: any): boolean { // parseFloat(value) handles most of the cases we're interested in (it treats null, empty string, // and other non-number values as NaN, where Number just uses 0) but it considers the string // '123hello' to be a valid number. Therefore we also check if Number(value) is NaN. return !isNaN(parseFloat(value as any)) && !isNaN(Number(value)); }
BirMa/components
projects/prosoft-components-demo/src/app/table-demo/table-demo.module.ts
<filename>projects/prosoft-components-demo/src/app/table-demo/table-demo.module.ts import { CommonModule } from '@angular/common'; import { NgModule, Injectable } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatCardModule } from '@angular/material/card'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { RouterModule } from '@angular/router'; import { PsIntlService, PsIntlServiceEn } from '@prosoft/components/core'; import { IPsTableSetting, PsTableModule, PsTableSettingsService } from '@prosoft/components/table'; import { BehaviorSubject, Observable, of } from 'rxjs'; import { map } from 'rxjs/operators'; import { TableDemoComponent } from './table-demo.component'; @Injectable() export class DemoPsTableSettingsService extends PsTableSettingsService { private settings$ = new BehaviorSubject<{ [id: string]: IPsTableSetting }>({}); constructor() { super(); this.settingsEnabled = true; } public override getStream(tableId: string): Observable<IPsTableSetting> { return this.settings$.pipe(map((settings) => settings[tableId])); } public override save(tableId: string, settings: IPsTableSetting): Observable<void> { this.settings$.next({ [tableId]: settings }); return of(null); } } @NgModule({ declarations: [TableDemoComponent], imports: [ CommonModule, FormsModule, MatCardModule, MatCheckboxModule, MatInputModule, MatSelectModule, PsTableModule, MatFormFieldModule, RouterModule.forChild([ { path: '', component: TableDemoComponent, }, ]), ], providers: [ { provide: PsIntlService, useClass: PsIntlServiceEn }, { provide: PsTableSettingsService, useClass: DemoPsTableSettingsService }, ], }) export class TableDemoModule {}
BirMa/components
projects/components/card/src/card.component.spec.ts
import { HarnessLoader } from '@angular/cdk/testing'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { ChangeDetectionStrategy, Component, ViewChild } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MatButtonModule } from '@angular/material/button'; import { PsHeaderHarness } from '@prosoft/components/header/src/testing/header.harness'; import { PsCardComponent } from './card.component'; import { PsCardModule } from './card.module'; import { PsCardHarness } from './testing/card.harness'; @Component({ selector: 'ps-test-component', template: ` <ps-card [caption]="caption" [description]="description"> <ng-container *psCardCaptionSection> <h1 *ngIf="addCaptionTemplate">customCaption</h1> </ng-container> <ng-container *psCardDescriptionSection> <span *ngIf="addDescriptionTemplate">customDescription</span> </ng-container> <ng-container *psCardTopButtonSection> <button *ngIf="addTopButton" mat-button>testTopButton</button> </ng-container> <ng-container *psCardFooterSection> <span *ngIf="addFooterTemplate">testFooter</span> </ng-container> <ng-container *psCardActionsSection> <button *ngIf="addCardActionButton" mat-button>testActionButton</button> </ng-container> <h2>Test content</h2> </ps-card> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestDataSourceComponent { public caption: string; public description: string; public addTopButton = false; public addCardActionButton = false; public addCaptionTemplate = false; public addDescriptionTemplate = false; public addFooterTemplate = false; @ViewChild(PsCardComponent) headerComponent: PsCardComponent; } describe('PsCardComponent', () => { let fixture: ComponentFixture<TestDataSourceComponent>; let component: TestDataSourceComponent; let loader: HarnessLoader; let header: PsHeaderHarness; let card: PsCardHarness; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [PsCardModule, MatButtonModule], declarations: [TestDataSourceComponent], }); fixture = TestBed.createComponent(TestDataSourceComponent); component = fixture.componentInstance; expect(component).toBeDefined(); loader = TestbedHarnessEnvironment.loader(fixture); card = await loader.getHarness(PsCardHarness); header = await card.getHeader(); }); it('should show caption text', async () => { expect(await header.getCaptionText()).toBeFalsy(); component.caption = 'foo'; expect(await header.getCaptionText()).toBe('foo'); }); it('should show caption template', async () => { expect(await header.getCaptionText()).toBeFalsy(); component.addCaptionTemplate = true; const nodes = await header.getCaptionTemplateNodes(); expect(nodes.length).toEqual(1); const captionNode = nodes[0]; expect(await captionNode.matchesSelector('h1')).toEqual(true); expect(await captionNode.text()).toEqual('customCaption'); }); it('should show caption text when input and template are set at the same time', async () => { expect(await header.getCaptionText()).toBeFalsy(); component.caption = 'foo'; expect(await header.getCaptionText()).toBeTruthy(); component.addCaptionTemplate = true; expect(await header.getCaptionText()).toBeTruthy(); const nodes = await header.getCaptionTemplateNodes(); expect(nodes.length).toEqual(0); }); it('should show description text', async () => { expect(await header.getDescriptionText()).toBeFalsy(); component.description = 'bar'; expect(await header.getDescriptionText()).toBe('bar'); }); it('should show description template', async () => { expect(await header.getDescriptionText()).toBeFalsy(); component.addDescriptionTemplate = true; const nodes = await header.getDescriptionTemplateNodes(); expect(nodes.length).toEqual(1); const descriptionNode = nodes[0]; expect(await descriptionNode.matchesSelector('span')).toEqual(true); expect(await descriptionNode.text()).toEqual('customDescription'); }); it('should show description text when input and template are set at the same time', async () => { expect(await header.getDescriptionText()).toBeFalsy(); component.description = 'foo'; expect(await header.getDescriptionText()).toBeTruthy(); component.addDescriptionTemplate = true; expect(await header.getDescriptionText()).toBeTruthy(); const nodes = await header.getDescriptionTemplateNodes(); expect(nodes.length).toEqual(0); }); it('should show top buttons', async () => { let nodes = await header.getActionTemplateNodes(); expect(nodes.length).toBe(0); component.addTopButton = true; nodes = await header.getActionTemplateNodes(); expect(nodes.length).toBe(1); const buttonNodes = nodes[0]; expect(await buttonNodes.matchesSelector('button')).toEqual(true); expect(await nodes[0].text()).toEqual('testTopButton'); }); it('should show action buttons', async () => { let nodes = await card.getActionTemplateNodes(); expect(nodes.length).toBe(0); component.addCardActionButton = true; nodes = await card.getActionTemplateNodes(); expect(nodes.length).toBe(1); expect(await nodes[0].text()).toEqual('testActionButton'); }); it('should show footer template', async () => { let nodes = await card.getFooterTemplateNodes(); expect(nodes.length).toBe(0); component.addFooterTemplate = true; nodes = await card.getFooterTemplateNodes(); expect(nodes.length).toBe(1); expect(await nodes[0].text()).toEqual('testFooter'); }); });
BirMa/components
projects/components/dialog-wrapper/src/dialog-wrapper.component.ts
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnDestroy, ViewEncapsulation } from '@angular/core'; import { IPsButton, IPsException } from '@prosoft/components/core'; import { Subject, Subscription } from 'rxjs'; import { IPsDialogWrapperDataSource } from './dialog-wrapper.models'; @Component({ selector: 'ps-dialog-wrapper', templateUrl: './dialog-wrapper.component.html', styleUrls: ['./dialog-wrapper.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class PsDialogWrapperComponent implements OnDestroy { public get dialogTitle(): string { return this.dataSource.dialogTitle; } public get buttons(): IPsButton[] { return this.dataSource.buttons; } public get contentVisible(): boolean { return this.dataSource.contentVisible; } public get contentBlocked(): boolean { return this.dataSource.contentBlocked; } public get exception(): IPsException | null { return this.dataSource.exception; } @Input() public set dataSource(value: IPsDialogWrapperDataSource) { if (this._dataSource) { this._dataSource.disconnect(); this._dataSourceSubscription.unsubscribe(); } this._dataSource = value; if (this._dataSource) { this._dataSourceSubscription = this._dataSource.connect().subscribe(() => { this.cd.markForCheck(); }); } } public get dataSource(): IPsDialogWrapperDataSource { return this._dataSource; } private _dataSource: IPsDialogWrapperDataSource; private _dataSourceSubscription = Subscription.EMPTY; private _ngUnsubscribe$ = new Subject<void>(); constructor(private cd: ChangeDetectorRef) {} public ngOnDestroy() { this._ngUnsubscribe$.next(); this._ngUnsubscribe$.complete(); this._dataSourceSubscription.unsubscribe(); if (this._dataSource) { this._dataSource.disconnect(); } } }
MusicalPatterns/pattern-playroomTest
src/material/constants.ts
<gh_stars>0 // tslint:disable no-magic-numbers import { as, Pitch, Scalar, Value } from '@musical-patterns/utilities' const PLAYROOM_TEST_NOTE_VALUE_SCALAR: Scalar<Value> = as.Scalar<Value>(15) const PLAYROOM_TEST_NOTE_PITCH_SCALAR: Scalar<Pitch> = as.Scalar<Pitch>(0.5) export { PLAYROOM_TEST_NOTE_VALUE_SCALAR, PLAYROOM_TEST_NOTE_PITCH_SCALAR, }
MusicalPatterns/pattern-playroomTest
src/patterns.ts
<reponame>MusicalPatterns/pattern-playroomTest // tslint:disable max-file-line-count import { Id } from '@musical-patterns/id' import { Pattern, Patterns } from '@musical-patterns/pattern' import { finiteMaterial, material, repetendMaterial } from './material' import * as metadata from './metadata' import * as specs from './spec' const playroomTestSpecControls: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_SPEC_CONTROLS, material, metadata: metadata.playroomTestSpecControlsMetadata, spec: specs.spec, } const playroomTestPost: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_POST, material, metadata: metadata.playroomTestPostMetadata, spec: specs.specDifferent, } const playroomTestTimeControls: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_TIME_CONTROLS, material, metadata: metadata.playroomTestTimeControlsMetadata, spec: specs.specDifferent, } const playroomTestOnlyPatternParticularSpecs: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_ONLY_PATTERN_PARTICULAR_SPECS, material, metadata: metadata.playroomTestOnlyPatternParticularSpecsMetadata, spec: specs.specOnlyPatternParticularInitial, } const playroomTestOnlyStandardSpecs: Pattern = { id: Id.PLAYROOM_TEST_ONLY_STANDARD_SPECS, material, metadata: metadata.playroomTestOnlyStandardSpecsMetadata, spec: specs.specOnlyStandardInitial, } const playroomTestValidation: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_VALIDATION, material, metadata: metadata.playroomTestValidationMetadata, spec: specs.specValidation, } const playroomTestPresets: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_PRESETS, material, metadata: metadata.playroomTestPresetsMetadata, spec: specs.specPresets, } const playroomTestLongDuration: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_LONG_DURATION, material, metadata: metadata.playroomTestLongDurationMetadata, spec: specs.specLongDuration, } const playroomTestFinite: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_FINITE, material: finiteMaterial, metadata: metadata.playroomTestFiniteMetadata, spec: specs.spec, } const playroomTestRepetend: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_REPETEND, material: repetendMaterial, metadata: metadata.playroomTestRepetendMetadata, spec: specs.spec, } const playroomTestRestart: Pattern<specs.PlayroomTestSpecs> = { id: Id.PLAYROOM_TEST_RESTART, material, metadata: metadata.playroomTestRestartMetadata, spec: specs.specRestart, } const patterns: Partial<Patterns> = { [ playroomTestSpecControls.id ]: playroomTestSpecControls, [ playroomTestPost.id ]: playroomTestPost, [ playroomTestTimeControls.id ]: playroomTestTimeControls, [ playroomTestOnlyPatternParticularSpecs.id ]: playroomTestOnlyPatternParticularSpecs, [ playroomTestOnlyStandardSpecs.id ]: playroomTestOnlyStandardSpecs, [ playroomTestValidation.id ]: playroomTestValidation, [ playroomTestPresets.id ]: playroomTestPresets, [ playroomTestLongDuration.id ]: playroomTestLongDuration, [ playroomTestFinite.id ]: playroomTestFinite, [ playroomTestRepetend.id ]: playroomTestRepetend, [ playroomTestRestart.id ]: playroomTestRestart, } const pattern: Pattern<specs.PlayroomTestSpecs> = playroomTestSpecControls export { pattern, patterns, }
MusicalPatterns/pattern-playroomTest
src/spec/index.ts
export { spec, specDifferent, specOnlyStandardInitial, specOnlyPatternParticularInitial, specValidation, specPresets, specLongDuration, specRestart, } from './specs' export { PlayroomTestSpecs, } from './types'
MusicalPatterns/pattern-playroomTest
src/spec/constants.ts
<reponame>MusicalPatterns/pattern-playroomTest // tslint:disable no-magic-numbers import { as, Duration, musicalAs, round, ScientificPitchNoteName, ScientificPitchOctaveNumber, SCIENTIFIC_PITCHES, Tone, Translation, } from '@musical-patterns/utilities' const PLAYROOM_TEST_INITIAL_MS_PHYSICALIZATION: Duration = musicalAs.Duration(100) const PLAYROOM_TEST_INITIAL_HZ_PHYSICALIZATION: Tone = round( SCIENTIFIC_PITCHES[ ScientificPitchNoteName.C ][ ScientificPitchOctaveNumber._8 ], ) const PLAYROOM_TEST_INITIAL_ARRAYED_SPEC: number[] = [ 0, 1, 1, 2, 3 ] const PLAYROOM_TEST_INITIAL_ARRAYED_SPEC_WITH_INITIAL_ELEMENT_VALUE: number[] = [ 7, 8, 9 ] const DIFFERENT: Translation = as.Translation(1) const PLAYROOM_TEST_LONG_DURATION_INITIAL_MS_PHYSICALIZATION: Duration = musicalAs.Duration(1000) export { PLAYROOM_TEST_INITIAL_MS_PHYSICALIZATION, PLAYROOM_TEST_INITIAL_HZ_PHYSICALIZATION, PLAYROOM_TEST_INITIAL_ARRAYED_SPEC, PLAYROOM_TEST_INITIAL_ARRAYED_SPEC_WITH_INITIAL_ELEMENT_VALUE, DIFFERENT, PLAYROOM_TEST_LONG_DURATION_INITIAL_MS_PHYSICALIZATION, }
MusicalPatterns/pattern-playroomTest
src/material/index.ts
export { material, repetendMaterial, finiteMaterial } from './materials'
MusicalPatterns/pattern-playroomTest
src/spec/constraints.ts
import { OptionedConstraint, RangedConstraint, StandardSpec, StringedConstraint } from '@musical-patterns/spec' import { as, ObjectOf } from '@musical-patterns/utilities' import { PLAYROOM_TEST_MAX_MS_PHYSICALIZATION, PLAYROOM_TEST_MIN_MS_PHYSICALIZATION } from '../constants' import { OptionedSpecOneOption, OptionedSpecTwoOption, PlayroomTestSpec } from './types' const rangedConstraints: ObjectOf<RangedConstraint> = { [ PlayroomTestSpec.ARRAYED_SPEC ]: { min: 0, required: true, }, [ StandardSpec.MS_PHYSICALIZATION ]: { excludeMax: true, excludeMin: true, integer: true, max: as.number(PLAYROOM_TEST_MAX_MS_PHYSICALIZATION), min: as.number(PLAYROOM_TEST_MIN_MS_PHYSICALIZATION), required: true, }, } const optionedConstraints: ObjectOf<OptionedConstraint> = { [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: { required: true } && [ { formattedName: 'Option one', value: OptionedSpecOneOption.OPTION_ONE, }, { formattedName: 'Option two', order: 1, value: OptionedSpecOneOption.OPTION_TWO, }, { formattedName: 'Option three', order: 2, value: OptionedSpecOneOption.OPTION_THREE, }, ], [ PlayroomTestSpec.OPTIONED_SPEC_TWO_NOT_REQUIRED ]: [ { formattedName: '', value: undefined, }, { formattedName: 'Option the First', value: OptionedSpecTwoOption.OPTION_THE_FIRST, }, { description: 'Option the Second has no formatted name, but it sure does have a description!', value: OptionedSpecTwoOption.OPTION_THE_SECOND, }, ], } const stringedConstraints: ObjectOf<StringedConstraint> = { [ PlayroomTestSpec.STRINGED_SPEC ]: { maxLength: 4, minLength: 3, required: true, }, } export { rangedConstraints, optionedConstraints, stringedConstraints, }
MusicalPatterns/pattern-playroomTest
src/metadata/metadatas.ts
<filename>src/metadata/metadatas.ts // tslint:disable max-file-line-count import { Metadata } from '@musical-patterns/metadata' import { nonPost, post } from './posts' const baseMetadata: Metadata = { mostRecentPublish: process.env.PUBLISH_DATE || '2018-12-19T07:00:00.000Z', musicalIdeaIllustrated: '', originalPublish: '', version: process.env.PATTERN_VERSION || 'unknown', } const playroomTestSpecControlsMetadata: Metadata = { ...baseMetadata, description: nonPost, musicalIdeaIllustrated: 'spec controls', originalPublish: '2018-12-19T07:00:00.000Z', } const playroomTestPostMetadata: Metadata = { ...baseMetadata, description: post, formattedName: 'Playroom Test', musicalIdeaIllustrated: 'post', order: 1, originalPublish: '2019-01-15T07:00:00.000Z', } const playroomTestTimeControlsMetadata: Metadata = { ...baseMetadata, description: `I really should add a new pattern for testing text-only descriptions \ but this wouldn't be the first overloaded pattern here so why start being good now`, musicalIdeaIllustrated: 'time controls', originalPublish: '2019-01-18T07:00:00.000Z', } const playroomTestOnlyPatternParticularSpecsMetadata: Metadata = { ...baseMetadata, musicalIdeaIllustrated: 'only pattern-particular spec', originalPublish: '2019-01-18T08:00:00.000Z', } const playroomTestOnlyStandardSpecsMetadata: Metadata = { ...baseMetadata, musicalIdeaIllustrated: 'only standard spec', originalPublish: '2019-01-18T09:00:00.000Z', } const playroomTestValidationMetadata: Metadata = { ...baseMetadata, musicalIdeaIllustrated: 'validation', order: 3, originalPublish: '2019-01-18T10:00:00.000Z', } const playroomTestPresetsMetadata: Metadata = { ...baseMetadata, musicalIdeaIllustrated: 'presets', order: 7, originalPublish: '2019-01-18T11:00:00.000Z', } const playroomTestLongDurationMetadata: Metadata = { ...baseMetadata, musicalIdeaIllustrated: 'long value', order: 8, originalPublish: '2019-03-03T11:00:00.000Z', } const playroomTestFiniteMetadata: Metadata = { ...baseMetadata, musicalIdeaIllustrated: 'does not repeat forever', order: 9, originalPublish: '2019-04-02T11:00:00.000Z', } const playroomTestRepetendMetadata: Metadata = { ...baseMetadata, musicalIdeaIllustrated: 'repeats forever but not from the beginning', order: 10, originalPublish: '2019-04-02T11:00:00.000Z', } const playroomTestRestartMetadata: Metadata = { ...baseMetadata, musicalIdeaIllustrated: 'restarts upon spec modification', order: 11, originalPublish: '2019-04-04T11:00:00.000Z', } export { playroomTestSpecControlsMetadata, playroomTestPostMetadata, playroomTestTimeControlsMetadata, playroomTestOnlyPatternParticularSpecsMetadata, playroomTestOnlyStandardSpecsMetadata, playroomTestValidationMetadata, playroomTestPresetsMetadata, playroomTestLongDurationMetadata, playroomTestFiniteMetadata, playroomTestRepetendMetadata, playroomTestRestartMetadata, }
MusicalPatterns/pattern-playroomTest
src/constants.ts
// tslint:disable no-magic-numbers import { Duration, musicalAs } from '@musical-patterns/utilities' const PLAYROOM_TEST_MAX_MS_PHYSICALIZATION: Duration = musicalAs.Duration(1003) const PLAYROOM_TEST_MIN_MS_PHYSICALIZATION: Duration = musicalAs.Duration(9) export { PLAYROOM_TEST_MAX_MS_PHYSICALIZATION, PLAYROOM_TEST_MIN_MS_PHYSICALIZATION, }
MusicalPatterns/pattern-playroomTest
src/spec/configurations.ts
<reponame>MusicalPatterns/pattern-playroomTest<filename>src/spec/configurations.ts import { InputType, RangedInputType, standardConfigurations, StandardSpec } from '@musical-patterns/spec' import { optionedConstraints, rangedConstraints, stringedConstraints } from './constraints' import { PlayroomTestConfigurations, PlayroomTestSpec } from './types' const configurations: PlayroomTestConfigurations = { ...standardConfigurations, [ PlayroomTestSpec.ARRAYED_SPEC ]: { arrayedConstraint: { maxLength: 7, minLength: 4, required: true, }, constraint: rangedConstraints[ PlayroomTestSpec.ARRAYED_SPEC ], formattedName: 'example arrayed spec', hideInput: RangedInputType.RANGE, inputType: InputType.RANGED, isArrayed: true, }, [ PlayroomTestSpec.ARRAYED_SPEC_WITH_INITIAL_FIELD_VALUE ]: { arrayedConstraint: { required: true, }, arrayedNewFieldInitialValue: 0, constraint: { required: true, }, formattedName: 'example arrayed control, with an initial value for its elements', hideInput: RangedInputType.NUMBER, inputType: InputType.RANGED, isArrayed: true, }, [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: { constraint: optionedConstraints[ PlayroomTestSpec.OPTIONED_SPEC_ONE ], formattedName: 'example optioned control one', inputType: InputType.OPTIONED, }, [ PlayroomTestSpec.OPTIONED_SPEC_TWO_NOT_REQUIRED ]: { constraint: optionedConstraints[ PlayroomTestSpec.OPTIONED_SPEC_TWO_NOT_REQUIRED ], formattedName: 'example optioned control two', inputType: InputType.OPTIONED, }, [ PlayroomTestSpec.STRINGED_SPEC ]: { constraint: stringedConstraints[ PlayroomTestSpec.STRINGED_SPEC ], formattedName: `example control that's a string`, inputType: InputType.STRINGED, order: 6, }, [ PlayroomTestSpec.TOGGLED_SPEC ]: { formattedName: 'example on/off control', inputType: InputType.TOGGLED, order: 1, }, [ StandardSpec.MS_PHYSICALIZATION ]: { ...standardConfigurations[ StandardSpec.MS_PHYSICALIZATION ], constraint: rangedConstraints[ StandardSpec.MS_PHYSICALIZATION ], formattedName: 'example ranged control one', order: 2, }, [ StandardSpec.HZ_PHYSICALIZATION ]: { ...standardConfigurations[ StandardSpec.HZ_PHYSICALIZATION ], description: 'I need to describe something to you and it is super cereal you guys', formattedName: 'example ranged control two', hideInput: RangedInputType.RANGE, order: 3, }, } const differentConfigurations: PlayroomTestConfigurations = { ...standardConfigurations, ...configurations, [ StandardSpec.HZ_PHYSICALIZATION ]: { ...standardConfigurations[ StandardSpec.HZ_PHYSICALIZATION ], hideInput: RangedInputType.NUMBER, }, [ PlayroomTestSpec.ARRAYED_SPEC ]: { arrayedConstraint: { required: true, }, constraint: { min: 0, required: true, }, formattedName: 'example arrayed control hiding neither input', inputType: InputType.RANGED, isArrayed: true, }, } export { configurations, differentConfigurations, }
MusicalPatterns/pattern-playroomTest
src/spec/specs.ts
import { Spec } from '@musical-patterns/spec' import { configurations, differentConfigurations } from './configurations' import { differentInitial, initials, longDurationInitial, onlyPatternParticularInitial, onlyStandardInitial, } from './initials' import { presets } from './presets' import { PlayroomTestSpecs } from './types' import { computeValidations } from './validations' const spec: Spec<PlayroomTestSpecs> = { configurations, initialSpecs: initials, } const specDifferent: Spec<PlayroomTestSpecs> = { configurations: differentConfigurations, initialSpecs: differentInitial, } const specOnlyStandardInitial: Spec = { configurations, initialSpecs: onlyStandardInitial, } const specOnlyPatternParticularInitial: Spec<PlayroomTestSpecs> = { configurations, initialSpecs: onlyPatternParticularInitial, } const specValidation: Spec<PlayroomTestSpecs> = { computeValidations, configurations, initialSpecs: initials, } const specPresets: Spec<PlayroomTestSpecs> = { configurations, initialSpecs: initials, presets, } const specLongDuration: Spec<PlayroomTestSpecs> = { configurations, initialSpecs: longDurationInitial, presets, } const specRestart: Spec<PlayroomTestSpecs> = { configurations, initialSpecs: longDurationInitial, presets, restartOnModify: true, } export { spec, specDifferent, specOnlyStandardInitial, specOnlyPatternParticularInitial, specValidation, specPresets, specLongDuration, specRestart, }
MusicalPatterns/pattern-playroomTest
src/spec/types.ts
import { Configurations, OptionedConfiguration, RangedConfiguration, Specs, StandardSpec, StringedConfiguration, ToggledConfiguration, } from '@musical-patterns/spec' enum OptionedSpecOneOption { OPTION_ONE = 'OPTION_ONE', OPTION_TWO = 'OPTION_TWO', OPTION_THREE = 'OPTION_THREE', } enum OptionedSpecTwoOption { OPTION_THE_FIRST = 'OPTION_THE_FIRST', OPTION_THE_SECOND = 'OPTION_THE_SECOND', } enum PlayroomTestSpec { ARRAYED_SPEC = 'arrayedSpec', ARRAYED_SPEC_WITH_INITIAL_FIELD_VALUE = 'arrayedSpecWithInitialFieldValue', OPTIONED_SPEC_ONE = 'optionedSpecOne', OPTIONED_SPEC_TWO_NOT_REQUIRED = 'optionedSpecTwoNotRequired', STRINGED_SPEC = 'stringedSpec', TOGGLED_SPEC = 'toggledSpec', } interface PlayroomTestConfigurations extends Configurations<PlayroomTestSpecs> { [ StandardSpec.MS_PHYSICALIZATION ]: RangedConfiguration, [ StandardSpec.HZ_PHYSICALIZATION ]: RangedConfiguration, [ PlayroomTestSpec.ARRAYED_SPEC ]: RangedConfiguration, [ PlayroomTestSpec.ARRAYED_SPEC_WITH_INITIAL_FIELD_VALUE ]: RangedConfiguration, [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: OptionedConfiguration, [ PlayroomTestSpec.OPTIONED_SPEC_TWO_NOT_REQUIRED ]: OptionedConfiguration, [ PlayroomTestSpec.STRINGED_SPEC ]: StringedConfiguration, [ PlayroomTestSpec.TOGGLED_SPEC ]: ToggledConfiguration, } interface PlayroomTestSpecs extends Specs { [ PlayroomTestSpec.ARRAYED_SPEC ]: number[], [ PlayroomTestSpec.ARRAYED_SPEC_WITH_INITIAL_FIELD_VALUE ]: number[], [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: OptionedSpecOneOption, [ PlayroomTestSpec.OPTIONED_SPEC_TWO_NOT_REQUIRED ]: OptionedSpecTwoOption, [ PlayroomTestSpec.STRINGED_SPEC ]: string, [ PlayroomTestSpec.TOGGLED_SPEC ]: boolean, } export { PlayroomTestSpecs, PlayroomTestConfigurations, OptionedSpecOneOption, OptionedSpecTwoOption, PlayroomTestSpec, }
MusicalPatterns/pattern-playroomTest
src/material/notes.ts
<filename>src/material/notes.ts<gh_stars>0 import { Note } from '@musical-patterns/material' import { Thunk } from '@musical-patterns/utilities' import { PLAYROOM_TEST_NOTE_PITCH_SCALAR, PLAYROOM_TEST_NOTE_VALUE_SCALAR } from './constants' const thunkNotes: Thunk<Note[]> = (): Note[] => [ { pitch: { scalar: PLAYROOM_TEST_NOTE_PITCH_SCALAR }, value: { scalar: PLAYROOM_TEST_NOTE_VALUE_SCALAR }, } ] export { thunkNotes, }
MusicalPatterns/pattern-playroomTest
src/spec/validations.ts
import { ComputeValidations, StandardSpec, Validations } from '@musical-patterns/spec' import { as, computeLength, Duration, isEven, musicalAs, Tone } from '@musical-patterns/utilities' import { PlayroomTestSpecs } from './types' const computeValidations: ComputeValidations<PlayroomTestSpecs> = (specs: PlayroomTestSpecs): Validations<PlayroomTestSpecs> => { const tone: Tone = specs[ StandardSpec.HZ_PHYSICALIZATION ] || musicalAs.Tone(1) const value: Duration = specs[ StandardSpec.MS_PHYSICALIZATION ] || musicalAs.Duration(1) const arrayedSpec: number[] = specs.arrayedSpec if (as.number(tone) < as.number(value)) { return { [ StandardSpec.HZ_PHYSICALIZATION ]: 'pitch must be more than value, obvs', [ StandardSpec.MS_PHYSICALIZATION ]: 'value must be less than pitch, obvs', } } if (isEven(computeLength(arrayedSpec))) { return { arrayedSpec: arrayedSpec.map((): string => 'arrays can only be odd in length, duoy'), } } return undefined } export { computeValidations, }
MusicalPatterns/pattern-playroomTest
src/spec/presets.ts
<reponame>MusicalPatterns/pattern-playroomTest import { Preset } from '@musical-patterns/spec' import { ObjectOf } from '@musical-patterns/utilities' import { PLAYROOM_TEST_INITIAL_ARRAYED_SPEC, PLAYROOM_TEST_INITIAL_ARRAYED_SPEC_WITH_INITIAL_ELEMENT_VALUE, } from './constants' import { initials } from './initials' import { OptionedSpecOneOption, OptionedSpecTwoOption, PlayroomTestSpec, PlayroomTestSpecs } from './types' const presetSpecs: PlayroomTestSpecs = { ...initials, [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: OptionedSpecOneOption.OPTION_ONE, } const otherPresetSpecs: PlayroomTestSpecs = { [ PlayroomTestSpec.ARRAYED_SPEC ]: PLAYROOM_TEST_INITIAL_ARRAYED_SPEC, [ PlayroomTestSpec.ARRAYED_SPEC_WITH_INITIAL_FIELD_VALUE ]: PLAYROOM_TEST_INITIAL_ARRAYED_SPEC_WITH_INITIAL_ELEMENT_VALUE, [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: OptionedSpecOneOption.OPTION_TWO, [ PlayroomTestSpec.OPTIONED_SPEC_TWO_NOT_REQUIRED ]: OptionedSpecTwoOption.OPTION_THE_SECOND, [ PlayroomTestSpec.STRINGED_SPEC ]: 'ABD', [ PlayroomTestSpec.TOGGLED_SPEC ]: true, } const presetOne: Preset<PlayroomTestSpecs> = { formattedName: 'Preset Uno', order: 4, specs: presetSpecs, } const presetTwo: Preset<PlayroomTestSpecs> = { formattedName: 'Preset Dos', order: 7, specs: otherPresetSpecs, } const presetThree: Preset<PlayroomTestSpecs> = { description: 'this preset exists to QA preset presentation', specs: { ...presetSpecs, [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: OptionedSpecOneOption.OPTION_THREE, }, } const presets: ObjectOf<Preset<PlayroomTestSpecs>> = { presetOne, presetThree, presetTwo, } export { presets, }
MusicalPatterns/pattern-playroomTest
src/material/entities.ts
<reponame>MusicalPatterns/pattern-playroomTest<filename>src/material/entities.ts import { Entity, MaterializeEntities } from '@musical-patterns/material' import { as } from '@musical-patterns/utilities' import { thunkNotes } from './notes' const materializeEntitiesUsingCrazyStrategyCircumventingScales: MaterializeEntities = (): Entity[] => [ { sections: [ { notes: thunkNotes(), }, ], }, ] const materializeFiniteEntitiesUsingCrazyStrategyCircumventingScales: MaterializeEntities = (): Entity[] => [ { sections: [ { notes: thunkNotes(), repetitions: as.Cardinal(1), }, ], }, ] const materializeRepetendEntitiesUsingCrazyStrategyCircumventingScales: MaterializeEntities = (): Entity[] => [ { sections: [ { notes: thunkNotes(), repetitions: as.Cardinal(1), }, { notes: thunkNotes(), }, ], }, ] export { materializeEntitiesUsingCrazyStrategyCircumventingScales, materializeFiniteEntitiesUsingCrazyStrategyCircumventingScales, materializeRepetendEntitiesUsingCrazyStrategyCircumventingScales, }
MusicalPatterns/pattern-playroomTest
src/metadata/posts.ts
// tslint:disable import { Maybe } from '@musical-patterns/utilities' const env: Maybe<string> = process.env.NODE_ENV const post: string = env !== 'test' && env != 'material' ? require('./post.html') : '' const nonPost: string = env === 'development' || env === 'production' ? require('./nonPost.html') : '' export { post, nonPost, }
MusicalPatterns/pattern-playroomTest
src/metadata/index.ts
export { playroomTestSpecControlsMetadata, playroomTestPostMetadata, playroomTestTimeControlsMetadata, playroomTestOnlyPatternParticularSpecsMetadata, playroomTestOnlyStandardSpecsMetadata, playroomTestValidationMetadata, playroomTestPresetsMetadata, playroomTestLongDurationMetadata, playroomTestFiniteMetadata, playroomTestRepetendMetadata, playroomTestRestartMetadata, } from './metadatas' export { nonPost, post, } from './posts'
MusicalPatterns/pattern-playroomTest
src/material/materials.ts
import { Material, materializeStandardScales } from '@musical-patterns/material' import { materializeEntitiesUsingCrazyStrategyCircumventingScales, materializeFiniteEntitiesUsingCrazyStrategyCircumventingScales, materializeRepetendEntitiesUsingCrazyStrategyCircumventingScales, } from './entities' const material: Material = { materializeEntities: materializeEntitiesUsingCrazyStrategyCircumventingScales, materializeScales: materializeStandardScales, } const finiteMaterial: Material = { materializeEntities: materializeFiniteEntitiesUsingCrazyStrategyCircumventingScales, materializeScales: materializeStandardScales, } const repetendMaterial: Material = { materializeEntities: materializeRepetendEntitiesUsingCrazyStrategyCircumventingScales, materializeScales: materializeStandardScales, } export { material, finiteMaterial, repetendMaterial, }
MusicalPatterns/pattern-playroomTest
src/spec/initials.ts
import { Specs, StandardSpec } from '@musical-patterns/spec' import { Duration, insteadOf, Tone, Translation, use } from '@musical-patterns/utilities' import { DIFFERENT, PLAYROOM_TEST_INITIAL_ARRAYED_SPEC, PLAYROOM_TEST_INITIAL_ARRAYED_SPEC_WITH_INITIAL_ELEMENT_VALUE, PLAYROOM_TEST_INITIAL_HZ_PHYSICALIZATION, PLAYROOM_TEST_INITIAL_MS_PHYSICALIZATION, PLAYROOM_TEST_LONG_DURATION_INITIAL_MS_PHYSICALIZATION, } from './constants' import { OptionedSpecOneOption, OptionedSpecTwoOption, PlayroomTestSpec, PlayroomTestSpecs } from './types' const onlyPatternParticularInitial: PlayroomTestSpecs = { [ PlayroomTestSpec.ARRAYED_SPEC ]: PLAYROOM_TEST_INITIAL_ARRAYED_SPEC, [ PlayroomTestSpec.ARRAYED_SPEC_WITH_INITIAL_FIELD_VALUE ]: PLAYROOM_TEST_INITIAL_ARRAYED_SPEC_WITH_INITIAL_ELEMENT_VALUE, [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: OptionedSpecOneOption.OPTION_TWO, [ PlayroomTestSpec.OPTIONED_SPEC_TWO_NOT_REQUIRED ]: OptionedSpecTwoOption.OPTION_THE_FIRST, [ PlayroomTestSpec.STRINGED_SPEC ]: 'ABC', [ PlayroomTestSpec.TOGGLED_SPEC ]: true, } const onlyStandardInitial: Specs = { [ StandardSpec.MS_PHYSICALIZATION ]: PLAYROOM_TEST_INITIAL_MS_PHYSICALIZATION, [ StandardSpec.HZ_PHYSICALIZATION ]: PLAYROOM_TEST_INITIAL_HZ_PHYSICALIZATION, } const initials: PlayroomTestSpecs = { ...onlyPatternParticularInitial, ...onlyStandardInitial, } const differentInitial: PlayroomTestSpecs = { [ PlayroomTestSpec.ARRAYED_SPEC ]: PLAYROOM_TEST_INITIAL_ARRAYED_SPEC, [ PlayroomTestSpec.ARRAYED_SPEC_WITH_INITIAL_FIELD_VALUE ]: PLAYROOM_TEST_INITIAL_ARRAYED_SPEC_WITH_INITIAL_ELEMENT_VALUE, [ PlayroomTestSpec.OPTIONED_SPEC_ONE ]: OptionedSpecOneOption.OPTION_ONE, [ PlayroomTestSpec.OPTIONED_SPEC_TWO_NOT_REQUIRED ]: OptionedSpecTwoOption.OPTION_THE_SECOND, [ PlayroomTestSpec.STRINGED_SPEC ]: 'ABF', [ PlayroomTestSpec.TOGGLED_SPEC ]: false, [ StandardSpec.MS_PHYSICALIZATION ]: use.Translation(PLAYROOM_TEST_INITIAL_MS_PHYSICALIZATION, insteadOf<Translation, Duration>(DIFFERENT)), [ StandardSpec.HZ_PHYSICALIZATION ]: use.Translation(PLAYROOM_TEST_INITIAL_HZ_PHYSICALIZATION, insteadOf<Translation, Tone>(DIFFERENT)), } const longDurationInitial: PlayroomTestSpecs = { ...initials, [ StandardSpec.MS_PHYSICALIZATION ]: PLAYROOM_TEST_LONG_DURATION_INITIAL_MS_PHYSICALIZATION, } export { onlyPatternParticularInitial, onlyStandardInitial, initials, differentInitial, longDurationInitial, }
gabefgonc/san-francisco-rice-dotfiles
dot_vim/plugged/yats.vim/test/test.tsx
var fragment = <div sdss="123" ></div> var b = <Div sss="123"></Div> var a = 123 var a= <Option key={item}></Option>; var a= <Option key={item} value="test" > </Option>; var a = <React.Fragment> { this.state.thing ? <p>Hello <strong data-role={`${this.props.prefix}-name`}>world</strong></p> : <h1>Hey!</h1> } <h1 className={`${this.props.baz}-class`}>wow</h1> </React.Fragment> var a = <ion-gesture> <div></div> </ion-gesture> var b = 123 var c = ( <> <Route component={this.renderHome} /> </> ) class A { render() { var d = ( <Link to="/" className={styles.logo} onClick={this.closeNavBar}> {this.renderStuff()} </Link> ) return <Route exact/> } } // paren + function child var d = ( <Route component={() => <Home/>}/> )
gabefgonc/san-francisco-rice-dotfiles
dot_vim/plugged/yats.vim/test/test.ts
var a = (): string => 123 var p: Promise<void> var a = { template: /*eee*/ this.template } type A = [ /*test*/ string, /*test*/ string, ] var b: unique symbol = 123 var c: readonly t.MyClass<T>[] = 333 c?.test const COMPILER_PROVIDERS: Array<any[]> = null var a = { get method<T>(a) { }, } var a = [/\/\//, 123] if (/*rete*/123) {} if (a < (<number>b)) a } while ( // sdkfsld ss) { } var a: T[K] = 1213 switch (eww) { case 1222 } var a = 123 class MyClass<string> extends Mixin({test: 123}) { noed // ewewe a = '3' // ewew get(arg: string) { } } var a = test[333] function test({a = process.stdout}) {} // test var a = 1/3 /* test*/ type A = 42 test({ async a: test ? // test test: ee }) getSymbolIterator(3) in obj; const a = (): string => '123' list.reduce((flat: any[], item: T | T[]): T[] => { const flatItem = Array.isArray(item) ? flatten(item) : item; return (<T[]>flat).concat(flatItem); }, []); export function noProviderError(injector: ReflectiveInjector, key: ReflectiveKey): InjectionError { return injectionError(injector, key, function(keys: ReflectiveKey[]) { const first = stringify(keys[0].token); return `No provider for ${first}!${constructResolvingPath(keys)}`; }); } export class QueryList<T>/* implements Iterable<T> */ { public readonly dirty = true; } class A { a = (a: () => void) => { } } var a = ({a: () => 123}) enum A { } interface FooBar<T extends Record<string, any> = Record<string, any>> { foo: string; bar: number; } [].map(({num}, index) => { const key = `${num}` })
MateusGX/react-js-cron-mui
src/locale.ts
<reponame>MateusGX/react-js-cron-mui import { DefaultLocale } from './types' export const DEFAULT_LOCALE_EN: DefaultLocale = { everyText: 'todo', emptyMonths: 'todo mês', emptyMonthDays: 'todos os dias do mês', emptyMonthDaysShort: 'dia do mês', emptyWeekDays: 'todos os dias da semana', emptyWeekDaysShort: 'dia da semana', emptyHours: 'toda hora', emptyMinutes: 'todo minuto', emptyMinutesForHourPeriod: 'todo', yearOption: 'ano', monthOption: 'mês', weekOption: 'semana', dayOption: 'dia', hourOption: 'hora', minuteOption: 'minuto', rebootOption: 'reiniciar', prefixPeriod: 'Todo(a)', prefixMonths: 'em', prefixMonthDays: 'no dia', prefixWeekDays: 'no(a)', prefixWeekDaysForMonthAndYearPeriod: 'no(a)', prefixHours: 'às', prefixMinutes: ':', prefixMinutesForHourPeriod: 'em', suffixMinutesForHourPeriod: 'minutos', errorInvalidCron: 'Expressão CRON Inválida', clearButtonText: 'Limpar', weekDays: [ // Order is important, the index will be used as value 'Domingo', // Sunday must always be first, it's "0" 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado', ], months: [ // Order is important, the index will be used as value 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro', ], // Order is important, the index will be used as value altWeekDays: [ 'DOM', // Sunday must always be first, it's "0" 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SAB', ], // Order is important, the index will be used as value altMonths: [ 'JAN', 'FEV', 'MAR', 'ABR', 'MAI', 'JUN', 'JUL', 'AUG', 'SET', 'OUT', 'NOV', 'DEZ', ], }
MateusGX/react-js-cron-mui
src/Cron.tsx
<reponame>MateusGX/react-js-cron-mui<gh_stars>0 import React, { useState, useCallback, useEffect, useRef, useMemo } from 'react' import { Button } from '@material-ui/core' import { CronProps, PeriodType } from './types' import Period from './fields/Period' import MonthDays from './fields/MonthDays' import Months from './fields/Months' import Hours from './fields/Hours' import Minutes from './fields/Minutes' import WeekDays from './fields/WeekDays' import { classNames, setError, usePrevious } from './utils' import { DEFAULT_LOCALE_EN } from './locale' import { setValuesFromCronString, getCronStringFromValues } from './converter' import './styles.css' export default function Cron(props: CronProps) { const { clearButton = true, clearButtonProps = {}, clearButtonAction = 'fill-with-every', locale = DEFAULT_LOCALE_EN, value = '', setValue, displayError = true, onError, className, defaultPeriod = 'day', allowEmpty = 'for-default-value', humanizeLabels = true, humanizeValue = false, disabled = false, readOnly = false, leadingZero = false, shortcuts = [], clockFormat, ...selectProps } = props const internalValueRef = useRef<string>(value) const defaultPeriodRef = useRef<PeriodType>(defaultPeriod) const [period, setPeriod] = useState<PeriodType | string | undefined>() const [monthDays, setMonthDays] = useState<number[] | undefined>() const [months, setMonths] = useState<number[] | undefined>() const [weekDays, setWeekDays] = useState<number[] | undefined>() const [hours, setHours] = useState<number[] | undefined>() const [minutes, setMinutes] = useState<number[] | undefined>() const [error, setInternalError] = useState<boolean>(false) const [valueCleared, setValueCleared] = useState<boolean>(false) const previousValueCleared = usePrevious(valueCleared) const localeJSON = JSON.stringify(locale) useEffect( () => { setValuesFromCronString( value, setInternalError, onError, allowEmpty, internalValueRef, true, locale, shortcuts, setMinutes, setHours, setMonthDays, setMonths, setWeekDays, setPeriod ) }, // eslint-disable-next-line react-hooks/exhaustive-deps [] ) useEffect( () => { if (value !== internalValueRef.current) { setValuesFromCronString( value, setInternalError, onError, allowEmpty, internalValueRef, false, locale, shortcuts, setMinutes, setHours, setMonthDays, setMonths, setWeekDays, setPeriod ) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [value, internalValueRef, localeJSON, allowEmpty, shortcuts] ) useEffect( () => { // Only change the value if a user touched a field // and if the user didn't use the clear button if ( (period || minutes || months || monthDays || weekDays || hours || minutes) && !valueCleared && !previousValueCleared ) { const cron = getCronStringFromValues( period || defaultPeriodRef.current, months, monthDays, weekDays, hours, minutes, humanizeValue ) setValue(cron) internalValueRef.current = cron onError && onError(undefined) setInternalError(false) } else if (valueCleared) { setValueCleared(false) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [ period, monthDays, months, weekDays, hours, minutes, humanizeValue, valueCleared, ] ) const handleClear = useCallback( () => { setMonthDays(undefined) setMonths(undefined) setWeekDays(undefined) setHours(undefined) setMinutes(undefined) // When clearButtonAction is 'empty' let newValue = '' const newPeriod = period !== 'reboot' && period ? period : defaultPeriodRef.current if (newPeriod !== period) { setPeriod(newPeriod) } // When clearButtonAction is 'fill-with-every' if (clearButtonAction === 'fill-with-every') { const cron = getCronStringFromValues( newPeriod, undefined, undefined, undefined, undefined, undefined ) newValue = cron } setValue(newValue) internalValueRef.current = newValue setValueCleared(true) if (allowEmpty === 'never' && clearButtonAction === 'empty') { setInternalError(true) setError(onError, locale) } else { onError && onError(undefined) setInternalError(false) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [period, setValue, onError, clearButtonAction] ) const internalClassName = useMemo( () => classNames({ 'react-js-cron': true, 'react-js-cron-error': error && displayError, 'react-js-cron-disabled': disabled, 'react-js-cron-read-only': readOnly, [`${className}`]: !!className, [`${className}-error`]: error && displayError && !!className, [`${className}-disabled`]: disabled && !!className, [`${className}-read-only`]: readOnly && !!className, }), [className, error, displayError, disabled, readOnly] ) const { className: clearButtonClassNameProp, ...otherClearButtonProps } = clearButtonProps const clearButtonClassName = useMemo( () => classNames({ 'react-js-cron-clear-button': true, [`${className}-clear-button`]: !!className, [`${clearButtonClassNameProp}`]: !!clearButtonClassNameProp, }), [className, clearButtonClassNameProp] ) const otherClearButtonPropsJSON = JSON.stringify(otherClearButtonProps) const clearButtonNode = useMemo( () => { if (clearButton && !readOnly) { return ( <Button style={{marginLeft:'10px'}} className={clearButtonClassName} variant='contained' color='secondary' disabled={disabled} onClick={handleClear} > {locale.clearButtonText || DEFAULT_LOCALE_EN.clearButtonText} </Button> ) } return null }, // eslint-disable-next-line react-hooks/exhaustive-deps [ clearButton, readOnly, localeJSON, clearButtonClassName, disabled, otherClearButtonPropsJSON, handleClear, ] ) const periodForRender = period || defaultPeriodRef.current return ( <div className={internalClassName}> <Period value={periodForRender} setValue={setPeriod} locale={locale} className={className} disabled={disabled} readOnly={readOnly} shortcuts={shortcuts} {...selectProps} /> {periodForRender === 'reboot' ? ( clearButtonNode ) : ( <> {periodForRender === 'year' && ( <Months value={months} setValue={setMonths} locale={locale} className={className} humanizeLabels={humanizeLabels} disabled={disabled} readOnly={readOnly} period={periodForRender} {...selectProps} /> )} {(periodForRender === 'year' || periodForRender === 'month') && ( <MonthDays value={monthDays} setValue={setMonthDays} locale={locale} className={className} weekDays={weekDays} disabled={disabled} readOnly={readOnly} leadingZero={leadingZero} period={periodForRender} {...selectProps} /> )} {(periodForRender === 'year' || periodForRender === 'month' || periodForRender === 'week') && ( <WeekDays value={weekDays} setValue={setWeekDays} locale={locale} className={className} humanizeLabels={humanizeLabels} monthDays={monthDays} disabled={disabled} readOnly={readOnly} period={periodForRender} {...selectProps} /> )} <div> {periodForRender !== 'minute' && periodForRender !== 'hour' && ( <Hours value={hours} setValue={setHours} locale={locale} className={className} disabled={disabled} readOnly={readOnly} leadingZero={leadingZero} clockFormat={clockFormat} period={periodForRender} {...selectProps} /> )} {periodForRender !== 'minute' && ( <Minutes value={minutes} setValue={setMinutes} locale={locale} period={periodForRender} className={className} disabled={disabled} readOnly={readOnly} leadingZero={leadingZero} clockFormat={clockFormat} {...selectProps} /> )} {clearButtonNode} </div> </> )} </div> ) }
MateusGX/react-js-cron-mui
src/components/CustomSelect.tsx
import React, { useMemo, useCallback } from 'react' import { Select, MenuItem } from '@material-ui/core' import { CustomSelectProps } from '../types' import { DEFAULT_LOCALE_EN } from '../locale' import { classNames, sort } from '../utils' import { parsePartArray, partToString, formatValue } from '../converter' export default function CustomSelect(props: CustomSelectProps) { const { value, setValue, locale, className, humanizeLabels, disabled, readOnly, leadingZero, clockFormat, optionsList, unit, ...selectProps } = props const stringValue = useMemo(() => { if (value && Array.isArray(value)) { return value.map((value: number) => value.toString()) } return [] }, [value]) const options = useMemo( () => { if (optionsList) { return optionsList.map((option, index) => { const number = unit.min === 0 ? index : index + 1 return { value: number.toString(), label: option, } }) } return [...Array(unit.total)].map((e, index) => { const number = unit.min === 0 ? index : index + 1 return { value: number.toString(), label: formatValue( number, unit, humanizeLabels, leadingZero, clockFormat ), } }) }, // eslint-disable-next-line react-hooks/exhaustive-deps [optionsList, leadingZero, humanizeLabels, clockFormat] ) const localeJSON = JSON.stringify(locale) const renderTag = useCallback( (props) => { const value = props if (!value || Number(value[0]) === NaN) { return <></> } const parsedArray = parsePartArray(value, unit) const cronValue = partToString( parsedArray, unit, humanizeLabels, leadingZero, clockFormat ) const testEveryValue = cronValue.match(/^\*\/([0-9]+),?/) || [] return ( <div> {testEveryValue[1] ? `${locale.everyText || DEFAULT_LOCALE_EN.everyText} ${testEveryValue[1]}` : cronValue} </div> ) }, // eslint-disable-next-line react-hooks/exhaustive-deps [value, localeJSON, humanizeLabels, leadingZero, clockFormat] ) const simpleClick = useCallback( (event: any) => { let newValueOption: number[] = event.target.value; if (newValueOption.length == 0) { newValueOption.push(0); } newValueOption = Array.isArray(newValueOption) ? sort(newValueOption) : [newValueOption] const newValue: number[] = newValueOption if (newValue.length === unit.total) { setValue([]) } else { setValue(newValue) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [setValue, value] ) const internalClassName = useMemo( () => classNames({ 'react-js-cron-select': true, 'react-js-cron-custom-select': true, [`${className}-select`]: !!className, }), [className] ) return ( <Select multiple={true} open={readOnly ? false : undefined} value={stringValue} onChange={simpleClick} renderValue={renderTag} className={internalClassName} autoWidth={false} disabled={disabled} {...selectProps} > {options.map((obj) => ( <MenuItem key={obj.value} value={obj.value}> {obj.label} </MenuItem> ))} </Select> ) }
MateusGX/react-js-cron-mui
src/stories/index.stories.tsx
import React, { useState, useCallback, useEffect, useRef, useMemo } from 'react' import { TextField, Table, Radio, Switch, Button, FormControlLabel, RadioGroup, FormGroup, Input, TableHead, TableRow, TableCell, TableBody, Typography, TextFieldProps } from '@material-ui/core' import InfoIcon from '@material-ui/icons/Info'; import DividerWithText from '../components/DividerWithText' import Cron, { CronError, AllowEmpty, ClockFormat, PeriodType } from '../index' import { FRENCH_LOCALE, ENGLISH_VARIANT_LOCALE, NO_PREFIX_SUFFIX_LOCALE, } from './constants.stories' import { ClearButtonAction } from '../types' import './styles.stories.css' export default { title: 'ReactJS Cron', component: Demo, } export function Demo() { // const textFieldType = typeof TextField; const inputRef = useRef<TextFieldProps>() const defaultValue = '30 5 * * 1,6' const [value, setValue] = useState(defaultValue) const [textValue, setTextValue] = useState(''); const customSetValue = useCallback( (newValue: string) => { setValue(newValue) setTextValue(newValue); }, [setTextValue] ) const [error, onError] = useState<CronError>() return ( <div> <TextField value={textValue} inputRef={inputRef} onBlur={(event) => { setValue(event.target.value) }} // onChange={(event: any) => { customSetValue(event.target.value) }} // on // onPressEnter={() => { // setValue(inputRef.current?.input.value || '') // }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Double click on a dropdown option to automatically select / unselect a periodicity </span> </div> <p style={{ marginTop: 20 }}> Error: {error ? error.description : 'undefined'} </p> </div> ) } export function DynamicSettings() { const [displayInput, setDisplayInput] = useState<boolean>(true) const [changeValueonChange, setChangeValueonChange] = useState<boolean>(true) const [changeValueOnEnter, setChangeValueOnEnter] = useState<boolean>(true) const [readOnlyInput, setReadOnlyInput] = useState<boolean>(false) const [disabled, setDisabled] = useState<boolean>(false) const [readOnly, setReadOnly] = useState<boolean>(false) const [humanizeLabels, setHumanizeLabels] = useState<boolean>(true) const [humanizeValue, setHumanizeValue] = useState<boolean>(false) const [displayErrorText, setDisplayErrorText] = useState<boolean>(true) const [displayErrorStyle, setDisplayErrorStyle] = useState<boolean>(true) const [displayClearButton, setDisplayClearButton] = useState<boolean>(true) const [supportShortcuts, setSupportShortcuts] = useState<boolean>(true) const [removePrefixSuffix, setRemovePrefixSuffix] = useState<boolean>(false) const [customStyle, setCustomStyle] = useState<boolean>(false) const [allowEmpty, setAllowEmpty] = useState<AllowEmpty | string>('for-default-value') const [clockFormat, setClockFormat] = useState<ClockFormat | '' | string>('') const [locale, setLocale] = useState< 'english' | 'french' | 'english-variant' | string >('english') const [defaultPeriod, setDefaultPeriod] = useState<PeriodType | string>('day') const [defaultValue, setDefaultValue] = useState('@daily') const [leadingZero, setLeadingZero] = useState<boolean>(false) const [key, setKey] = useState('render') const inputRef = useRef<string>() const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() const [clearButtonAction, setClearButtonAction] = useState<ClearButtonAction | string>( 'fill-with-every' ) const transformedLocale = useMemo(() => { let newLocale switch (locale) { case 'french': newLocale = FRENCH_LOCALE break case 'english-variant': newLocale = ENGLISH_VARIANT_LOCALE break default: newLocale = {} break } if (removePrefixSuffix) { newLocale = { ...newLocale, ...NO_PREFIX_SUFFIX_LOCALE, } } return newLocale }, [locale, removePrefixSuffix]) useEffect( () => { if (displayInput && value !== null) { // inputRef.current = value; } }, // eslint-disable-next-line react-hooks/exhaustive-deps [displayInput] ) return ( <div> <FormGroup row className='demo-dynamic-settings'> <FormControlLabel label='Display input' control={ <Switch checked={displayInput} onChange={() => setDisplayInput((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Change input value on blur' control={ <Switch checked={changeValueonChange} onChange={() => setChangeValueonChange((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Change input value on enter' control={ <Switch checked={changeValueOnEnter} onChange={() => setChangeValueOnEnter((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Read-Only input' control={ <Switch checked={readOnlyInput} onChange={() => setReadOnlyInput((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Disabled' control={ <Switch checked={disabled} onChange={() => setDisabled((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Read-Only' control={ <Switch checked={readOnly} onChange={() => setReadOnly((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Humainze labels' control={ <Switch checked={humanizeLabels} onChange={() => setHumanizeLabels((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Humanize value' control={ <Switch checked={humanizeValue} onChange={() => setHumanizeValue((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Display error text' control={ <Switch checked={displayErrorText} onChange={() => setDisplayErrorText((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Display error style' control={ <Switch checked={displayErrorStyle} onChange={() => setDisplayErrorStyle((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Display clear button' control={ <Switch checked={displayClearButton} onChange={() => setDisplayClearButton((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Support shortcuts' control={ <Switch checked={supportShortcuts} onChange={() => setSupportShortcuts((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Remove prefix/suffix' control={ <Switch checked={removePrefixSuffix} onChange={() => setRemovePrefixSuffix((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Set custom style' control={ <Switch checked={customStyle} onChange={() => setCustomStyle((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Leading zero' control={ <Switch checked={leadingZero} onChange={() => setLeadingZero((prevValue) => !prevValue)} /> } /> <FormControlLabel label='Clock format' control={ <RadioGroup value={clockFormat} onChange={(e) => setClockFormat(e.target.value)} > <FormControlLabel control={<Radio />} value='' label='None' /> <FormControlLabel control={<Radio />} value='12-hour-clock' label='12-hour clock' /> <FormControlLabel control={<Radio />} value='24-hour-clock' label='24-hour-clock' /> </RadioGroup> } /> <FormControlLabel label='Locale' control={ <RadioGroup value={locale} onChange={(e) => setLocale(e.target.value)} > <FormControlLabel control={<Radio />} value='english' label='English' /> <FormControlLabel control={<Radio />} value='french' label='French' /> <FormControlLabel control={<Radio />} value='english-variant' label='English variant' /> </RadioGroup> } /> <FormControlLabel label='Clear button action' control={ <RadioGroup value={clearButtonAction} onChange={(e) => setClearButtonAction(e.target.value)} > <FormControlLabel control={<Radio />} value='empty' label='Empty' /> <FormControlLabel control={<Radio />} value='fill-with-every' label='Fill with every' /> </RadioGroup> } /> <FormControlLabel label='Empty value management *' control={ <RadioGroup value={allowEmpty} onChange={(e) => setAllowEmpty(e.target.value)} > <FormControlLabel control={<Radio />} value='for-default-value' label='For default value'></FormControlLabel> <FormControlLabel control={<Radio />} value='always' label='Always' /> <FormControlLabel control={<Radio />} value='never' label='Never' /> </RadioGroup> } /> <FormControlLabel label='Default value *' control={ <Input value={defaultValue} onChange={(e: any) => setDefaultValue(e.target.value)} /> } /> <FormControlLabel label='Default period **' control={ <RadioGroup value={defaultPeriod} onChange={(e) => setDefaultPeriod(e.target.value)} > <FormControlLabel control={<Radio />} value='year' label='Year' /> <FormControlLabel control={<Radio />} value='month' label='Month' /> <FormControlLabel control={<Radio />} value='week' label='Week' /> <FormControlLabel control={<Radio />} value='day' label='Day' /> <FormControlLabel control={<Radio />} value='hour' label='Hour' /> <FormControlLabel control={<Radio />} value='minute' label='Minute' /> <FormControlLabel control={<Radio />} value='reboot' label='Reboot' /> </RadioGroup> } /> <p>(*) Need to reset the component to see the changes</p> <p> (**) Need to reset the component and to have an empty default value to see the changes </p> </FormGroup> <div> <p>Value: {value}</p> <Button variant='contained' onClick={() => { customSetValue(defaultValue) setKey(Math.random().toString(36).substring(7)) }} > Reset cron component </Button> </div> {displayInput && ( <> <Input readOnly={readOnlyInput} onChange={(event: any) => { changeValueonChange && setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> </> )} <Cron key={key} value={value} setValue={customSetValue} onError={onError} disabled={disabled} readOnly={readOnly} humanizeLabels={humanizeLabels} humanizeValue={humanizeValue} displayError={displayErrorStyle} clearButton={displayClearButton} clearButtonAction={clearButtonAction} shortcuts={supportShortcuts} allowEmpty={allowEmpty} clockFormat={clockFormat === '' ? undefined : clockFormat} defaultPeriod={defaultPeriod} leadingZero={leadingZero} className={customStyle ? 'my-project-cron' : undefined} locale={transformedLocale} /> {displayErrorText && ( <p style={{ marginTop: 20 }}> Error: {error ? error.description : 'undefined'} </p> )} </div> ) } export function LocalInput() { const inputRef = useRef<string>() const defaultValue = '' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) return ( <div> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <div style={{ marginTop: 10 }}> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> The &quot;onChange&quot; event must be used instead of &quot;onChange&quot; to prevent a value change from the cron component </span> </div> <div style={{ marginTop: 10 }}> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Don&apos;t directly set the value of the Input with the prop &quot;value&quot;, you will not be able to edit it </span> </div> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} /> </div> ) } export function InputWithOnEnter() { const inputRef = useRef<string>() const defaultValue = '0 10 * * 1,3,5' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) return ( <div> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <div style={{ marginTop: 10 }}> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> You can also add &quot;onEnter&quot; support to set the value </span> </div> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} /> </div> ) } export function ReadOnlyInput() { const defaultValue = '0 10 * * 1,3,5' const [value, setValue] = useState(defaultValue) return ( <div> <Input readOnly value={value} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={setValue} /> </div> ) } export function DefaultValue() { const defaultValue = '*/7 */2 */3 * *' const [value, setValue] = useState(defaultValue) return ( <div> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <Cron value={value} setValue={setValue} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> The first value will always be used as default value </span> </div> </div> ) } export function DefaultPeriod() { const defaultValue = '' const defaultPeriod = 'year' const [value, setValue] = useState(defaultValue) return ( <div> <p>Default period: {defaultPeriod}</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <Cron value={value} setValue={setValue} defaultPeriod={defaultPeriod} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> The &quot;defaultPeriod&quot; prop only work for empty default value </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;defaultPeriod&quot; is &quot;day&quot; </span> </div> </div> ) } export function Disabled() { const defaultValue = '30 5 * * 1,6' const [value, setValue] = useState(defaultValue) return ( <div> <p>Disabled: true</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <Cron value={value} setValue={setValue} disabled /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;disabled&quot; is false </span> </div> </div> ) } export function ReadOnly() { const defaultValue = '30 5 * * 1,6' const [value, setValue] = useState(defaultValue) return ( <div> <p>Read only: true</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <Cron value={value} setValue={setValue} readOnly /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;readOnly&quot; is false </span> </div> </div> ) } export function HumanizeLabels() { const inputRef = useRef<string>() const defaultValue = '* * * * MON-WED,sat' const [value, setValue] = useState(defaultValue) const [error, onError] = useState<CronError>() const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) return ( <div> <p>Humanize labels: true</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;humanizeLabels&quot; is true </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Humanizes the labels in the cron component </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Works only for week days and months </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Can be used with &quot;locale&quot; prop and &quot;altMonths&quot; / &quot;altWeekDays&quot; properties in order to display translated labels </span> </div> </div> ) } export function HumanizeValue() { const inputRef = useRef<string>() const defaultValue = '* * * * MON-WED,sat' const [value, setValue] = useState(defaultValue) const [error, onError] = useState<CronError>() const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) return ( <div> <p>Humanize labels: false</p> <p>Humanize value: true</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} humanizeLabels={false} humanizeValue /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;humanizeValue&quot; is false </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> The prop &quot;humanizeValue&quot; cannot be used to prohibit used of valid string value like &quot;MON,WED&quot; </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If the prop &quot;humanizeValue&quot; is true, the component will automatically convert a valid number value to string </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If the prop &quot;humanizeValue&quot; is false, the component will automatically convert a valid string value to number </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> A valid string value can be in lowercase or uppercase </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Works only for week days and months </span> </div> </div> ) } export function HumanizeLabelsAndValue() { const inputRef = useRef<string>() const defaultValue = '* * * * MON-WED,sat' const [value, setValue] = useState(defaultValue) const [error, onError] = useState<CronError>() const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) return ( <div> <p>Humanize labels: true</p> <p>Humanize value: true</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} humanizeValue /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Humanizes in the cron component both the labels and the value </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Works only for week days and months </span> </div> </div> ) } export function LeadingZero() { const inputRef = useRef<string>() const defaultValue = '5 3 2-3,8 * *' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) return ( <div> <p>Leading zero: &quot;always&quot;</p> <p>Value: {value}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} leadingZero={true} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> You can set the prop to a boolean or an array [&quot;minutes&quot;, &quot;hours&quot;, &quot;month-days&quot;] </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;leadingZero&quot; is &quot;never&quot; </span> </div> </div> ) } export function TrackError() { const inputRef = useRef<string>() const defaultValue = '' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() return ( <div> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <div style={{ marginTop: 10 }}> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Write a bad cron expression to trigger an error after the &quot;onChange&quot; event </span> </div> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Use prop &quot;onError&quot; to be able to know when the value is invalid </span> </div> </div> ) } export function DisableErrorStyle() { const inputRef = useRef<string>() const defaultValue = '' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() return ( <div> <p>Display error: false</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} displayError={false} /> </div> ) } export function NoClearButton() { const defaultValue = '' const [value, setValue] = useState(defaultValue) return ( <div> <p>Clear button: false</p> <p>Value: {value}</p> <Cron clearButton={false} value={value} setValue={setValue} /> </div> ) } export function ClearButtonEmptyValue() { const clearButtonAction = 'empty' const defaultValue = '0 10 * * 1,3,5' const [value, setValue] = useState(defaultValue) return ( <div> <p>Clear button action: {clearButtonAction}</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <Cron value={value} setValue={setValue} clearButtonAction={clearButtonAction} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> The &quot;clearButtonAction&quot; prop allow you to empty the field or fill it with &quot;* * * * *&quot; </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;clearButtonAction&quot; is &quot;fill-with-every&quot; </span> </div> </div> ) } export function InvalidDefaultValue() { const defaultValue = '*/2 */2 */2 1-6 */6 * *' const [value, setValue] = useState(defaultValue) const [error, onError] = useState<CronError>() return ( <div> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Cron value={value} setValue={setValue} onError={onError} /> </div> ) } export function EmptyNeverAllowed() { const inputRef = useRef<string>() const defaultValue = '' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() return ( <div> <p>Allow empty: &quot;never&quot;</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} allowEmpty='never' /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;allowEmpty&quot; is &quot;for-default-value&quot; </span> </div> </div> ) } export function EmptyAlwaysAllowed() { const inputRef = useRef<string>() const defaultValue = '' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() return ( <div> <p>Allow empty: &quot;always&quot;</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} allowEmpty='always' /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;allowEmpty&quot; is &quot;for-default-value&quot; </span> </div> </div> ) } export function Shortcuts() { const inputRef = useRef<string>() const defaultValue = '@monthly' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() const columns = [ { dataIndex: 'name', key: 'name', }, { dataIndex: 'description', key: 'description', }, { dataIndex: 'value', key: 'value', }, ] const data = [ { key: '1', name: '@yearly (or @annually)', description: 'Run once a year at midnight of 1 January', value: '0 0 1 1 *', }, { key: '2', name: '@monthly', description: 'Run once a month at midnight of the first day of the month', value: '0 0 1 * *', }, { key: '3', name: '@weekly', description: 'Run once a week at midnight on Sunday morning', value: '0 0 * * 0', }, { key: '4', name: '@daily (or @midnight)', description: 'Run once a day at midnight', value: '0 0 * * *', }, { key: '5', name: '@hourly', description: 'Run once an hour at the beginning of the hour', value: '0 * * * *', }, { key: '6', name: '@reboot', description: 'Run at startup', value: '@reboot', }, ] return ( <div> <p>Shortcuts: true</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} shortcuts /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> If not set, the prop &quot;Shortcuts&quot; is [&quot;@yearly&quot;, &quot;@annually&quot;, &quot;@monthly&quot;, &quot;@weekly&quot;, &quot;@daily&quot;, &quot;@midnight&quot;, &quot;@hourly&quot;] </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Just pass true to activate all shortcuts including &quot;@reboot&quot; </span> </div> <Typography variant="h6" id="tableTitle" component="div"> Supported shortcuts </Typography> <Table style={{ marginTop: 20 }} > <TableHead> <TableRow> {columns.map((obj) => { return (<TableCell key={obj.key}>{obj.dataIndex}</TableCell>) })} </TableRow> </TableHead> <TableBody> {data.map(({ key, name, description, value }) => { return (<TableRow key={key}> <TableCell>{name}</TableCell> <TableCell>{description}</TableCell> <TableCell>{value}</TableCell> </TableRow>) })} </TableBody> </Table> </div> ) } export function TwelveHourClock() { const inputRef = useRef<string>() const defaultValue = '2 5,7,18 * * SUN' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() return ( <div> <p>Clock format: &quot;12-hour-clock&quot;</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} clockFormat='12-hour-clock' /> </div> ) } export function TwentyFourHourClock() { const inputRef = useRef<string>() const defaultValue = '2 5,7,18 * * SUN' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() return ( <div> <p>Clock format: &quot;24-hour-clock&quot;</p> <p>Default value: {defaultValue}</p> <p>Value: {value}</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} clockFormat='24-hour-clock' /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> This prop override the prop &quot;leadingZero&quot; for &quot;hours&quot; and &quot;minutes&quot; </span> </div> </div> ) } export function FrenchLocale() { const inputRef = useRef<string>() const defaultValue = '* * 1-2 2,8 1,3,6' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() return ( <div> <p>locale: FRENCH_LOCALE</p> <p>humanizeLabels: true (by default)</p> <p>Erreur: {error ? error.description : 'undefined'}</p> <p>Value: {value}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OU</DividerWithText> <Cron locale={FRENCH_LOCALE} value={value} setValue={customSetValue} onError={onError} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> The order of the &quot;locale&quot; properties &quot;weekDays&quot;, &quot;months&quot;, &quot;altMonths&quot; and &quot;altWeekDays&quot; is important! The index will be used as value </span> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Sunday must always be the first value of &quot;weekDays&quot; and &quot;altWeekDays&quot; property because it&apos;s &quot;0&quot; </span> </div> </div> ) } export function CustomENLocale() { const defaultValue = '30 14 22 * *' const [value, setValue] = useState(defaultValue) return ( <div> <p>locale: ENGLISH_VARIANT_LOCALE</p> <p>Value: {value}</p> <Cron locale={ENGLISH_VARIANT_LOCALE} value={value} setValue={setValue} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Not all translations need to be changed when using the prop &quot;locale&quot; </span> </div> </div> ) } export function NoPrefixAndSuffix() { const defaultValue = '30 14 22 * *' const [value, setValue] = useState(defaultValue) return ( <div> <p>locale: NO_PREFIX_SUFFIX_LOCALE</p> <p>Value: {value}</p> <Cron locale={NO_PREFIX_SUFFIX_LOCALE} value={value} setValue={setValue} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Using empty string &apos;&apos; for a prefix / suffix translation will remove the text </span> </div> </div> ) } export function CustomStyle() { const inputRef = useRef<string>() const defaultValue = '30 14 22 * *' const [value, setValue] = useState(defaultValue) const customSetValue = useCallback( (newValue: string) => { setValue(newValue) inputRef.current = newValue }, [inputRef] ) const [error, onError] = useState<CronError>() return ( <div> <p>className: my-project-cron</p> <p>clearButtonProps: &#123; type: &quot;default&quot; &#125;</p> <p>Error: {error ? error.description : 'undefined'}</p> <Input onChange={(event: any) => { setValue(event.target.value) }} /> <DividerWithText>OR</DividerWithText> <Cron value={value} setValue={customSetValue} onError={onError} className='my-project-cron' clearButtonProps={{ type: 'button', }} /> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Custom CSS example (See file &quot;styles.stories.css&quot;): </span> <ul> <li>Bold prefix and suffix</li> <li>Red prefix and suffix on error</li> <li>Bigger border radius for selects and clear button</li> <li>Gray backgroud for selected options</li> <li>Clear button type changed to &quot;default&quot;</li> </ul> </div> <div> <InfoIcon style={{ marginRight: 5 }} /> <span style={{ fontSize: 12 }}> Available classes when using the prop &quot;className&quot;: </span> <ul> <li>.my-project-cron</li> <li>.my-project-cron-error</li> <li>.my-project-cron-disabled</li> <li>.my-project-cron-read-only</li> <li>.my-project-cron-clear-button</li> <li>.my-project-cron-field</li> <li>.my-project-cron-period</li> <li>.my-project-cron-minutes</li> <li>.my-project-cron-hours</li> <li>.my-project-cron-months</li> <li>.my-project-cron-month-days</li> <li>.my-project-cron-week-days</li> <li>.my-project-cron-select</li> <li>.my-project-cron-select-dropdown</li> <li>.my-project-cron-select-dropdown-period</li> <li>.my-project-cron-select-dropdown-minutes</li> <li>.my-project-cron-select-dropdown-hours</li> <li>.my-project-cron-select-dropdown-months</li> <li>.my-project-cron-select-dropdown-month-days</li> <li>.my-project-cron-select-dropdown-week-days</li> </ul> </div> </div> ) }
MateusGX/react-js-cron-mui
src/converter.ts
<reponame>MateusGX/react-js-cron-mui<filename>src/converter.ts import { MutableRefObject } from 'react' import { UNITS, SUPPORTED_SHORTCUTS } from './constants' import { range, sort, dedup, setError } from './utils' import { Unit, PeriodType, LeadingZero, ClockFormat, SetInternalError, OnError, AllowEmpty, Locale, Shortcuts, SetValueNumbersOrUndefined, SetValuePeriod, } from './types' /** * Set values from cron string */ export function setValuesFromCronString( cronString: string, setInternalError: SetInternalError, onError: OnError, allowEmpty: AllowEmpty, internalValueRef: MutableRefObject<string>, firstRender: boolean, locale: Locale, shortcuts: Shortcuts, setMinutes: SetValueNumbersOrUndefined, setHours: SetValueNumbersOrUndefined, setMonthDays: SetValueNumbersOrUndefined, setMonths: SetValueNumbersOrUndefined, setWeekDays: SetValueNumbersOrUndefined, setPeriod: SetValuePeriod ) { onError && onError(undefined) setInternalError(false) let error = false // Handle empty cron string if (!cronString) { if ( allowEmpty === 'always' || (firstRender && allowEmpty === 'for-default-value') ) { return } error = true } if (!error) { // Shortcuts management if ( shortcuts && (shortcuts === true || shortcuts.includes(cronString as any)) ) { // Convert a shortcut to a valid cron string const shortcutObject = SUPPORTED_SHORTCUTS.find( (supportedShortcut) => supportedShortcut.name === cronString ) if (shortcutObject) { cronString = shortcutObject.value } } try { const cronParts = parseCronString(cronString) const period = getPeriodFromCronparts(cronParts) setPeriod(period) setMinutes(cronParts[0]) setHours(cronParts[1]) setMonthDays(cronParts[2]) setMonths(cronParts[3]) setWeekDays(cronParts[4]) } catch (err) { // Specific errors are not handle (yet) error = true } } if (error) { internalValueRef.current = cronString setInternalError(true) setError(onError, locale) } } /** * Get cron string from values */ export function getCronStringFromValues( period: PeriodType, months: number[] | undefined, monthDays: number[] | undefined, weekDays: number[] | undefined, hours: number[] | undefined, minutes: number[] | undefined, humanizeValue?: boolean ) { const newMonths = period === 'year' && months ? months : [] const newMonthDays = (period === 'year' || period === 'month') && monthDays ? monthDays : [] const newWeekDays = (period === 'year' || period === 'month' || period === 'week') && weekDays ? weekDays : [] const newHours = period !== 'minute' && period !== 'hour' && hours ? hours : [] const newMinutes = period !== 'minute' && minutes ? minutes : [] const parsedArray = parseCronArray( [newMinutes, newHours, newMonthDays, newMonths, newWeekDays], humanizeValue ) return cronToString(parsedArray) } /** * Returns the cron part array as a string. */ export function partToString( cronPart: number[], unit: Unit, humanize?: boolean, leadingZero?: LeadingZero, clockFormat?: ClockFormat ) { let retval = '' if (isFull(cronPart, unit) || cronPart.length === 0) { retval = '*' } else { const step = getStep(cronPart) if (step && isInterval(cronPart, step)) { if (isFullInterval(cronPart, unit, step)) { retval = `*/${step}` } else { retval = `${formatValue( getMin(cronPart), unit, humanize, leadingZero, clockFormat )}-${formatValue( getMax(cronPart), unit, humanize, leadingZero, clockFormat )}/${step}` } } else { retval = toRanges(cronPart) .map((range: number | number[]) => { if (Array.isArray(range)) { return `${formatValue( range[0], unit, humanize, leadingZero, clockFormat )}-${formatValue( range[1], unit, humanize, leadingZero, clockFormat )}` } return formatValue(range, unit, humanize, leadingZero, clockFormat) }) .join(',') } } return retval } /** * Format the value */ export function formatValue( value: number, unit: Unit, humanize?: boolean, leadingZero?: LeadingZero, clockFormat?: ClockFormat ) { let cronPartString = value.toString() const { type, alt, min } = unit const needLeadingZero = leadingZero && (leadingZero === true || leadingZero.includes(type as any)) const need24HourClock = clockFormat === '24-hour-clock' && (type === 'hours' || type === 'minutes') if ((humanize && type === 'week-days') || (humanize && type === 'months')) { cronPartString = alt![value - min] } else if (value < 10 && (needLeadingZero || need24HourClock)) { cronPartString = cronPartString.padStart(2, '0') } if (type === 'hours' && clockFormat === '12-hour-clock') { const suffix = value >= 12 ? 'PM' : 'AM' let hour: number | string = value % 12 || 12 if (hour < 10 && needLeadingZero) { hour = hour.toString().padStart(2, '0') } cronPartString = `${hour}${suffix}` } return cronPartString } /** * Parses a 2-dimentional array of integers as a cron schedule */ function parseCronArray(cronArr: number[][], humanizeValue?: boolean) { if (cronArr.length === 5) { return cronArr.map((partArr, idx) => { const unit = UNITS[idx] const parsedArray = parsePartArray(partArr, unit) return partToString(parsedArray, unit, humanizeValue) }) } throw new Error('Invalid cron array') } /** * Returns the cron array as a string */ function cronToString(parts: string[]) { return '0 ' + parts.join(' ') } /** * Find the period from cron parts */ function getPeriodFromCronparts(cronParts: number[][]): PeriodType { if (cronParts[3].length > 0) { return 'year' } else if (cronParts[2].length > 0) { return 'month' } else if (cronParts[4].length > 0) { return 'week' } else if (cronParts[1].length > 0) { return 'day' } else if (cronParts[0].length > 0) { return 'hour' } return 'minute' } /** * Parses a cron string to an array of parts */ function parseCronString(str: string) { if (typeof str !== 'string') { throw new Error('Invalid cron string') } const parts = str.replace(/\s+/g, ' ').trim().split(' ') if (parts.length === 5) { return parts.map((partStr, idx) => { return parsePartString(partStr, UNITS[idx]) }) } throw new Error('Invalid cron string format') } /** * Parses a string as a range of positive integers */ function parsePartString(str: string, unit: Unit) { if (str === '*' || str === '*/1') { return [] } const stringParts = str.split('/') if (stringParts.length > 2) { throw new Error(`Invalid value "${unit.type}"`) } const rangeString = replaceAlternatives(stringParts[0], unit.min, unit.alt) let parsedValues: number[] if (rangeString === '*') { parsedValues = range(unit.min, unit.max) } else { parsedValues = sort( dedup( fixSunday( rangeString .split(',') .map((range) => { return parseRange(range, str, unit) }) .flat(), unit ) ) ) const value = outOfRange(parsedValues, unit) if (typeof value !== 'undefined') { throw new Error(`Value "${value}" out of range for ${unit.type}`) } } const step = parseStep(stringParts[1], unit) const intervalValues = applyInterval(parsedValues, step) if (intervalValues.length === unit.total) { return [] } else if (intervalValues.length === 0) { throw new Error(`Empty interval value "${str}" for ${unit.type}`) } return intervalValues } /** * Replaces the alternative representations of numbers in a string */ function replaceAlternatives(str: string, min: number, alt?: string[]) { if (alt) { str = str.toUpperCase() for (let i = 0; i < alt.length; i++) { str = str.replace(alt[i], `${i + min}`) } } return str } /** * Replace all 7 with 0 as Sunday can be represented by both */ function fixSunday(values: number[], unit: Unit) { if (unit.type === 'week-days') { values = values.map(function (value) { if (value === 7) { return 0 } return value }) } return values } /** * Parses a range string */ function parseRange(rangeStr: string, context: string, unit: Unit) { const subparts = rangeStr.split('-') if (subparts.length === 1) { const value = parseInt(subparts[0], 10) if (isNaN(value)) { throw new Error(`Invalid value "${context}" for ${unit.type}`) } return [value] } else if (subparts.length === 2) { const minValue = parseInt(subparts[0], 10) const maxValue = parseInt(subparts[1], 10) if (maxValue <= minValue) { throw new Error( `Max range is less than min range in "${rangeStr}" for ${unit.type}` ) } return range(minValue, maxValue) } else { throw new Error(`Invalid value "${rangeStr}" for ${unit.type}`) } } /** * Finds an element from values that is outside of the range of unit */ function outOfRange(values: number[], unit: Unit) { const first = values[0] const last = values[values.length - 1] if (first < unit.min) { return first } else if (last > unit.max) { return last } return } /** * Parses the step from a part string */ function parseStep(step: string, unit: Unit) { if (typeof step !== 'undefined') { const parsedStep = parseInt(step, 10) if (isNaN(parsedStep) || parsedStep < 1) { throw new Error(`Invalid interval step value "${step}" for ${unit.type}`) } return parsedStep } } /** * Applies an interval step to a collection of values */ function applyInterval(values: number[], step?: number) { if (step) { const minVal = values[0] values = values.filter((value) => { return value % step === minVal % step || value === minVal }) } return values } /** * Validates a range of positive integers */ export function parsePartArray(arr: number[], unit: Unit) { const values = sort(dedup(fixSunday(arr, unit))) if (values.length === 0) { return values } const value = outOfRange(values, unit) if (typeof value !== 'undefined') { throw new Error(`Value "${value}" out of range for ${unit.type}`) } return values } /** * Returns true if range has all the values of the unit */ function isFull(values: number[], unit: Unit) { return values.length === unit.max - unit.min + 1 } /** * Returns the difference between first and second elements in the range */ function getStep(values: number[]) { if (values.length > 2) { const step = values[1] - values[0] if (step > 1) { return step } } } /** * Returns true if the range can be represented as an interval */ function isInterval(values: number[], step: number) { for (let i = 1; i < values.length; i++) { const prev = values[i - 1] const value = values[i] if (value - prev !== step) { return false } } return true } /** * Returns true if the range contains all the interval values */ function isFullInterval(values: number[], unit: Unit, step: number) { const min = getMin(values) const max = getMax(values) const haveAllValues = values.length === (max - min) / step + 1 if (min === unit.min && max + step > unit.max && haveAllValues) { return true } return false } /** * Returns the smallest value in the range */ function getMin(values: number[]) { return values[0] } /** * Returns the largest value in the range */ function getMax(values: number[]) { return values[values.length - 1] } /** * Returns the range as an array of ranges * defined as arrays of positive integers */ function toRanges(values: number[]) { const retval: (number[] | number)[] = [] let startPart: number | null = null values.forEach((value, index, self) => { if (value !== self[index + 1] - 1) { if (startPart !== null) { retval.push([startPart, value]) startPart = null } else { retval.push(value) } } else if (startPart === null) { startPart = value } }) return retval }
ColiseumSoft786/hemmam-ionic
src/pages/home/home.ts
import { Component } from '@angular/core'; import {LoadingController, NavController , ToastController} from 'ionic-angular'; import { DashboardPage } from '../dashboard/dashboard'; import { MenuController } from 'ionic-angular'; import 'rxjs/add/operator/map'; import {Http} from "@angular/http"; import {error} from "@angular/compiler/src/util"; import {Observable} from "rxjs"; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { data: any; events: any; public usernameLogin: string; public passwordLogin: string; private isUsernameValidLogin: boolean = true; private isPasswordValidLogin: boolean = true; public usernameRegister: string; public passwordRegister: string; public countryRegister: string; public emailRegister: string; public mobileRegister: string; public genderRegister: string; public nationalityRegister: string; public identificationtypeRegister: string; public idnumberRegister: string; public addresssRegister: string; public stateRegister: string; public educationLevelRegister: string; public majorRegister: string; public universityRegister: string; public graduationYearRegister: string; public workplaceRegister: string; public voulntrySideRegister: string; private isEmailValidRegister: boolean = true; private isUsernameValidRegister: boolean = true; private isPasswordValidRegister: boolean = true; private isCountryValidRegister: boolean = true; private isMobileValidRegister: boolean = true; private isNationalityValidRegister: boolean = true; private isIdnumberValidRegister: boolean = true; private isAddresssValidRegister: boolean = true; private isStateValidRegister: boolean = true; private isEducationLevelValidRegister: boolean = true; private isMajorValidRegister: boolean = true; private isUniversityValidRegister: boolean = true; private isGraduationYearValidRegister: boolean = true; private isWorkplaceValidRegister: boolean = true; private isVoulntrySideValidRegister: boolean = true; private regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; public selectedItem = "login"; constructor( public menuCtrl: MenuController , public navCtrl: NavController,private http:Http , private loadingCtrl: LoadingController , private toastCtrl: ToastController ) { this.menuCtrl.enable(false, 'logMenu'); if (localStorage.getItem("user") === null) { }else{ this.navCtrl.setRoot(DashboardPage); } this.data = { "segmentLogin" : "الدخول", "segmentRegister" : "تسجيل", "background" : "assets/images/background/39.jpg", "skip" : "تخطى", "logo" : "assets/logo of app.png", "boy" : "assets/icon/imoji_boy.png", "girl" : "assets/icon/imoji_girl.png", "login" : { "username" : " أدخل البريد الإلكتروني الخاص بك ", "password" : "<PASSWORD> ", "labelUsername" : "ال<PASSWORD> الإلكتر<PASSWORD>", "labelPassword" : "<PASSWORD> ", "forgotPassword" : "<PASSWORD>؟", "facebookLogin" : "تسجيل الدخول مع", "login" : "الدخول", "title" : "تسجيل الدخول إلى حسابك", "errorUser" : "لا يمكن أن يكون الحقل خاليًا", "errorPassword" : "<PASSWORD> أن يكون الحقل خاليًا" }, "register": { "title" : "تسجيل", "username" : "أدخل اسمك الكامل", "city" : "مسقط رأسك", "password" : "<PASSWORD> <PASSWORD> ", "email" : "عنوان بريدك الإلكتروني", "Mobile" : "أدخل هاتفك المحمول", "Nationality" : "أدخل جنسيتك", "Identificationtype" : "ادخل رقمك السري", "IdNumber" : "أدخل رقم الهوية الخاص بك", "Addresss" : "من أي بلد أنت؟", "State" : "اعزب أو متزوج", "EducationLevel" : "أدخل مستوى التعليم الخاص بك", "Major" : "أدخل تخصصك", "University" : "أدخل جامعتك", "GraduationYear" : "ادخل سنة التخرج", "Workplace" : "أدخل مكان عملك", "VoulntrySide" : "الجانب التطوعي", "register" : "تسجيل", "lableUsername" : "الاسم الكامل", "lablePassword" : "<PASSWORD> ", "lableEmail" : "البريد الإلكتروني", "lableMobile" : "هاتفك المحمول", "lableNationality" : "الجنسية", "lableIdentificationtype" : "نوع الهوية", "lableIdNumber" : "رقم الهوية", "lableAddresss" : "عنوان", "lableState" : "حالة", "lableEducationLevel" : "مستوى التعليم", "lableMajor" : "تخصص", "lableUniversity" : "جامعة", "lableGraduationYear" : "سنة التخرج", "lableWorkplace" : "مكان العمل", "lableVoulntrySide" : " الجانب التطوعي", "lablePersonalImage" : "صورة شخصية", "errorUser" : "لا يمكن أن يكون الحقل خاليًا", "errorPassword" : "<PASSWORD>", "errorEmail" : "عنوان البريد الإلكتروني غير صالح", "errorCountry" : "لا يمكن أن يكون الحقل خاليًا", "errorCity" : "لا يمكن أن يكون الحقل خاليًا" } }; this.events = { onLogin: function (params) { console.log("onLogin"); }, onRegister: function (params) { console.log("onRegister"); }, onSkip: function (params) { console.log("onSkip"); }, onFacebook: function (params) { console.log("onFacebook"); } }; } url : any; dataa: any; onEvent = (event: string): void => { if (event == "onLogin" ) { if (this.validateLogin()) { let datta = { useremail: this.usernameLogin, userpass: this.passwordLogin } console.log('clicked'); const loader = this.loadingCtrl.create({ content: " ... جلب البيانات", }); loader.present(); this.http.get('http://api.hemam.online/loginuser' ,{params: datta} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(dataa => { var result = dataa; this.dataa= dataa; loader.dismiss(); if (result != 0 ){ localStorage.setItem('user',JSON.stringify(result)); this.navCtrl.setRoot(DashboardPage); }else{ const toast = this.toastCtrl.create({ message: 'بيانات الاعتماد الخاصة بك ليست صحيحة', duration: 4000 }); toast.present(); } }, err => { const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); loader.dismiss(); }); } if (this.events[event]) { this.events[event]({ 'username' : this.usernameLogin, 'password' : <PASSWORD> }); } } else if (event == "onRegister") { if (this.validateRegister()) { console.log('clicked ======'); let datta = { usernameR : this. usernameRegister, passwordR : this. passwordRegister, countryR : this. countryRegister, emailR : this. emailRegister, mobileR : this. mobileRegister, genderR : this. genderRegister, nationalityR : this. nationalityRegister, identificationtypeR : this. identificationtypeRegister, idNumberR : this. idnumberRegister, addresssR : this. addresssRegister, stateR : this. stateRegister, educationLevelR : this. educationLevelRegister, majorR : this. majorRegister, universityR : this. universityRegister, graduationYearR : this. graduationYearRegister, workplaceR : this. workplaceRegister, voulntrySideR : this. voulntrySideRegister, } console.log('clicked'); const loader = this.loadingCtrl.create({ content: "... جلب البيانات", }); loader.present(); this.http.get('http://api.hemam.online/registeruser' ,{params: datta} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(dataa => { var result = dataa; this.dataa= dataa; loader.dismiss(); if (result == 1 ){ const toast = this.toastCtrl.create({ message: 'البريد الالكتروني موجود بالفعل', duration: 4000 }); toast.present(); }else{ localStorage.setItem('user',JSON.stringify(result)); this.navCtrl.setRoot(DashboardPage); } }, err => { const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); loader.dismiss(); }); } if (this.events[event]) { this.events[event]({ }); } } } validateLogin():boolean { this.isUsernameValidLogin = true; this.isPasswordValidLogin = true; if (!this.usernameLogin ||this.usernameLogin.length == 0) { this.isUsernameValidLogin = false; } if (!this.passwordLogin || this.passwordLogin.length == 0) { this.isPasswordValidLogin = false; } return this.isPasswordValidLogin && this.isUsernameValidLogin; } validateRegister():boolean { this.isEmailValidRegister = true; this.isUsernameValidRegister = true; this.isPasswordValidRegister = true; this.isCountryValidRegister = true; this.isMobileValidRegister = true; this.isNationalityValidRegister = true; this.isIdnumberValidRegister = true; this.isAddresssValidRegister = true; this.isStateValidRegister = true; this.isEducationLevelValidRegister = true; this.isMajorValidRegister = true; this.isUniversityValidRegister = true; this.isGraduationYearValidRegister = true; this.isWorkplaceValidRegister = true; this.isVoulntrySideValidRegister = true; if (!this.usernameRegister ||this.usernameRegister.length == 0) { this.isUsernameValidRegister = false; } if (!this.emailRegister ||this.emailRegister.length == 0) { this.isEmailValidRegister = false; } if (!this.passwordRegister || this.passwordRegister.length == 0) { this.isPasswordValidRegister = false; } if (!this.mobileRegister || this.mobileRegister.length == 0) { this.isMobileValidRegister = false; } // if (!this.genderRegister || this.genderRegister.length == 0) { // this.isgenderValidRegister = false; // } // if (!this.countryRegister || this.countryRegister.length == 0) { // this.isCountryValidRegister = false; // } if (!this.nationalityRegister || this.nationalityRegister.length == 0) { this.isNationalityValidRegister = false; } // if (!this.identificationtypeRegister || this.identificationtypeRegister.length == 0) { // this.isIdentificationtypeValidRegister = false; // } if (!this.idnumberRegister || this.idnumberRegister.length == 0) { this.isIdnumberValidRegister = false; } if (!this.addresssRegister || this.addresssRegister.length == 0) { this.isAddresssValidRegister = false; } if (!this.stateRegister || this.stateRegister.length == 0) { this.isStateValidRegister = false; } if (!this.educationLevelRegister || this.educationLevelRegister.length == 0) { this.isEducationLevelValidRegister = false; } if (!this.majorRegister || this.majorRegister.length == 0) { this.isMajorValidRegister = false; } if (!this.universityRegister || this.universityRegister.length == 0) { this.isUniversityValidRegister = false; } if (!this.graduationYearRegister || this.graduationYearRegister.length == 0) { this.isGraduationYearValidRegister = false; } if (!this.workplaceRegister || this.workplaceRegister.length == 0) { this.isWorkplaceValidRegister = false; } if (!this.voulntrySideRegister || this.voulntrySideRegister.length == 0) { this.isVoulntrySideValidRegister = false; } // this.isEmailValidRegister = this.regex.test(this.emailRegister); return this.isEmailValidRegister && this.isPasswordValidRegister && this.isUsernameValidRegister && this.isCountryValidRegister&& this.isMobileValidRegister && this.isNationalityValidRegister && this.isIdnumberValidRegister && this.isAddresssValidRegister && this.isStateValidRegister && this.isEducationLevelValidRegister && this.isMajorValidRegister && this.isUniversityValidRegister && this.isGraduationYearValidRegister && this.isWorkplaceValidRegister && this.isVoulntrySideValidRegister; } isEnabled(value:string): boolean { return this.selectedItem == value; } }
ColiseumSoft786/hemmam-ionic
src/pages/certificate/certificate.ts
import { Component, Input, ViewChild } from '@angular/core'; import { IonicPage, Content } from 'ionic-angular'; import {LoadingController , ToastController} from 'ionic-angular'; import 'rxjs/add/operator/map'; import {Http} from "@angular/http"; import { MenuController } from 'ionic-angular'; import { DashboardPage } from '../dashboard/dashboard'; import {Observable} from "rxjs"; /** * Generated class for the CertificatePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-certificate', templateUrl: 'certificate.html', }) export class CertificatePage{ data = { "header": "Catalogue", "status": "", "request": "", "items": [ { "id": 1, "title": "Black dualshock controller", "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "image": "assets/certificateicon.png", "expandItems": [ { "id": "1", "title": "Objective", "description": "Lorem ipsum", "image": "assets/certificateicon.png", "details": "$399.99" } ] } ] }; userdata:any; id:any; fetchdata:any; userinfo:any; constructor( public menuCtrl: MenuController ,private http:Http , private loadingCtrl: LoadingController , private toastCtrl: ToastController) { this.userdata = JSON.parse(localStorage.getItem('user')); this.id=this.userdata.id; let fetch = { userid:this.id }; const loader = this.loadingCtrl.create({ content: "... ارجوك انتظر", }); loader.present(); this.http.get('http://api.hemam.online/userdate' ,{params: fetch} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(fetchdata => { var fresult = fetchdata; this.fetchdata= fetchdata; this.data.status=this.userinfo; this.data.request=fresult.certificate_status; loader.dismiss(); if(fresult == 0){ console.log('oh no'); }else{ console.log('ok'); } }, err => { loader.dismiss(); const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); }); } certificaterequest(){ let fetch = { userid:this.id } const loader = this.loadingCtrl.create({ content: "... ارجوك انتظر", }); loader.present(); this.http.get('http://api.hemam.online/certificate_request' ,{params: fetch} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(data => { var result = data; this.data= data; console.log(result); loader.dismiss(); if(result == 0){ console.log('oh no'); }else{ const toast = this.toastCtrl.create({ message: 'تم إرسال الطلب بنجاح', duration: 4000 }); toast.present(); console.log('okk'); } }, err => { loader.dismiss(); const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); }); } @Input() events = { 'onItemClick': function (item: any) { console.log("onItemClick"); } }; @ViewChild(Content) content: Content; onEvent(event: string, item: any, e: any) { if (this.events[event]) { this.events[event](item); } } toggleGroup(group: any) { group.show = !group.show; } isGroupShown(group: any) { return group.show; } }
ColiseumSoft786/hemmam-ionic
src/pages/challenge/challenge.module.ts
import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ChallengePage } from './challenge'; import {Http, HttpModule} from "@angular/http"; @NgModule({ declarations: [ ChallengePage, ], imports: [ HttpModule, IonicPageModule.forChild(ChallengePage), ], }) export class ChallengePageModule {}
ColiseumSoft786/hemmam-ionic
src/pages/history/history.ts
<reponame>ColiseumSoft786/hemmam-ionic import { Component, Input, ViewChild, OnChanges } from '@angular/core'; import { IonicPage,NavController , Content } from 'ionic-angular'; import {LoadingController , ToastController} from 'ionic-angular'; import 'rxjs/add/operator/map'; import {Http} from "@angular/http"; import { MenuController } from 'ionic-angular'; import {Observable} from "rxjs"; /** * Generated class for the HistoryPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-history', templateUrl: 'history.html', }) export class HistoryPage implements OnChanges { data = { "items": [ { "groupName": "Pending", "dateTime": "", "items": [ { "id": "1", "name": "<NAME>", "task": "here is Task ", "status" : "Approde", "title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "shareIcon": "more", "image": "assets/images/avatar/24.jpg", "subtitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehe nderit in voluptate velit esse cillum dolore eu fugiat nulla pariatu" }, { "id": 2, "name": "<NAME>", "task": "here is Task ", "title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "shareIcon": "more", "image": "assets/images/avatar/10.jpg", "subtitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehe nderit in voluptate velit esse cillum dolore eu fugiat nulla pariatu" } ] }, { "groupName": "Approved", "dateTime": "June 26, 2018.", "items": [ { "id": 1, "task": "here is Task ", "name": "<NAME>", "title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "shareIcon": "more", "image": "assets/images/avatar/11.jpg", "subtitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehe nderit in voluptate velit esse cillum dolore eu fugiat nulla pariatu" }, { "id": 2, "name": "<NAME>", "title": "Lorem ipsum dolor sit amet.", "shareIcon": "more", "image": "assets/images/avatar/12.jpg", "subtitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehe nderit in voluptate velit esse cillum dolore eu fugiat nulla pariatu" } ] }, { "groupName": "Disaproved", "dateTime": "August 07, 2018.", "items": [ { "id": 1, "name": "<NAME>", "title": "Lorem ipsum dolor sit amet, consectetur.", "shareIcon": "more", "image": "assets/images/avatar/13.jpg", "subtitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehe nderit in voluptate velit esse cillum dolore eu fugiat nulla pariatu" }, { "id": 2, "name": "<NAME>", "title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.", "shareIcon": "more", "image": "assets/images/avatar/14.jpg", "subtitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehe nderit in voluptate velit esse cillum dolore eu fugiat nulla pariatu" } ] } ] }; events= { 'onItemClick': function (item: any) { console.log("onItemClick"); }, 'onShare': function (item: any) { console.log("onShare"); } }; slider = {}; id: any; userdata: any ; fetchdata: any; videoinfo : any; constructor( public menuCtrl: MenuController , public navCtrl: NavController,private http:Http , private loadingCtrl: LoadingController , private toastCtrl: ToastController) { this.userdata = JSON.parse(localStorage.getItem('user')); this.id=this.userdata.id; let fetch = { userid:this.id } const loader = this.loadingCtrl.create({ content: "... ارجوك انتظر", }); loader.present(); this.http.get('http://api.hemam.online/history' ,{params: fetch} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(fetchdata => { var fresult = fetchdata; this.fetchdata= fetchdata; this.videoinfo= fresult; console.log(this.videoinfo); loader.dismiss(); if(fresult == 0){ console.log('disabled'); }else{ console.log('sadsfsdfsdf'); } }, err => { loader.dismiss(); const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); }); } ngOnChanges(changes: { [propKey: string]: any }) { this.data = changes['data'].currentValue; } onEvent(event: string, item: any, e: any) { if (e) { e.stopPropagation(); } if (this.events[event]) { this.events[event](item); } } }
ColiseumSoft786/hemmam-ionic
src/pages/sponsor/sponsor.ts
import { Component, Input, ViewChild } from '@angular/core'; import { IonicPage, Content } from 'ionic-angular'; /** * Generated class for the SponsorPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-sponsor', templateUrl: 'sponsor.html', }) export class SponsorPage { data= { "items": [ { "id": 1, "icon": "ios-arrow-dropright", "iconText": "Watch now", "title": "Lorem ipsum dolor sitamet", "description": "Contrary to popular belief, Lorem Ipsum is not simply random text.", "image": "assets/logo_partners.png", "reviews": "4.12 (78 reviews)", "ratingStar": { "iconsStars": [ { "isActive": true, "iconActive": "icon-star", "iconInactive": "icon-star-outline" }, { "isActive": true, "iconActive": "icon-star", "iconInactive": "icon-star-outline" }, { "isActive": true, "iconActive": "icon-star", "iconInactive": "icon-star-outline" }, { "isActive": true, "iconActive": "icon-star", "iconInactive": "icon-star-outline" }, { "isActive": false, "iconActive": "icon-star", "iconInactive": "icon-star-outline" } ], } } ] }; events = { 'onItemClick': function (item: any) { console.log("onItemClick"); }, 'onRates': function (index: number) { } }; @ViewChild(Content) content: Content; slider = {}; constructor() { } // slideHasChanged(slider, index): void { // this.slider[index] = slider; // if (2 == slider._activeIndex) { // if (this.data.items) { // this.data.items.splice(index, 1); // } else { // this.data.splice(index, 1); // } // } // } onStarClass(items: any, index: number, e: any) { if (e) { e.stopPropagation(); } for (var i = 0; i < items.length; i++) { items[i].isActive = i <= index; } this.onEvent("onRates", index, e); }; onClickEvent(index): void { if (this.slider[index]) { this.slider[index].slidePrev(300); } } onEvent(event: string, item: any, e: any) { if (e) { e.stopPropagation(); } if (this.events[event]) { this.events[event](item); } } }
ColiseumSoft786/hemmam-ionic
src/pages/dashboard/dashboard.ts
import {Component, ViewChild} from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { HistoryPage } from '../history/history'; import { SponsorPage } from '../sponsor/sponsor'; import { FounderPage } from '../founder/founder'; import { LibraryPage } from '../library/library'; import { PartnerPage } from '../partner/partner'; import { ChallengePage } from '../challenge/challenge'; import { HomePage } from '../home/home'; import { CertificatePage } from '../certificate/certificate'; import {LoadingController , ToastController} from 'ionic-angular'; import 'rxjs/add/operator/map'; import {Http} from "@angular/http"; import { MenuController } from 'ionic-angular'; import 'rxjs/add/operator/catch'; import {FileTransfer, FileUploadOptions, FileTransferObject} from "@ionic-native/file-transfer"; import {File} from "@ionic-native/file"; import {Camera,CameraOptions} from "@ionic-native/camera"; import {Observable} from "rxjs"; /** * Generated class for the DashboardPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-dashboard', templateUrl: 'dashboard.html', }) export class DashboardPage { userdata: any ; id:any; test:any; constructor(public menuCtrl: MenuController ,private transfer: FileTransfer, private file: File,private camera: Camera, public navCtrl: NavController,private http:Http , private loadingCtrl: LoadingController , private toastCtrl: ToastController , public navParams: NavParams) { this.menuCtrl.enable(true, 'logMenu'); if (localStorage.getItem("user") === null) { this.navCtrl.setRoot(HomePage); }else{ this.userdata = JSON.parse(localStorage.getItem('user')); this.data.name=this.userdata.name; this.data.email=this.userdata.email; this.data.level=this.userdata.level_status; this.data.profile=this.userdata.personal_image; this.id=this.userdata.id; if(this.userdata.level_status == null){ this.test = '0'; }else{ this.test = '1' ; } console.log(this.test); } } refdata : any; reffetchdata:any; refresult:any; doRefresh(refresher) { let refdata = { userid:this.id } this.http.get('http://api.hemam.online/userdate' ,{params: refdata} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(data => { var refresult = data; this.reffetchdata = data; localStorage.setItem('user',JSON.stringify(refresult)); this.userdata=refresult; this.navCtrl.setRoot(DashboardPage); refresher.complete(); }, err => { refresher.complete(); const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); }); } // Gallery ============================================================================== myphoto:any; user: any; private fresh: boolean = false; changephoto(){ // This is working fine. its for image uplaod const options: CameraOptions = { quality: 70, destinationType: this.camera.DestinationType.DATA_URL, sourceType: this.camera.PictureSourceType.PHOTOLIBRARY, saveToPhotoAlbum:false }; this.camera.getPicture(options).then((imageData) => { // imageData is either a base64 encoded string or a file URI // If it's base64: this.myphoto = 'data:image/jpeg;base64,' + imageData; this.upload(); }, (err) => { // Handle error }); //this.navCtrl.resize(); } upload(){ let url = localStorage.getItem('server'); const loader = this.loadingCtrl.create({ content: "... جار التحميل", }); loader.present(); console.log(this.myphoto); //random int var timestamp = new Date().getUTCMilliseconds(); const fileTransfer: FileTransferObject = this.transfer.create(); let optionss: FileUploadOptions = { fileKey: 'photo', fileName: "myImage_"+timestamp+".jpg", chunkedMode: false, httpMethod: 'get', mimeType: "image/jpeg", headers: {} }; fileTransfer.upload(this.myphoto,'http://api.hemam.online/photoupdater?userid='+this.id,optionss) .then((data) => { this.updateuser(); loader.dismiss(); }, (err) => { // error console.log(err.getMessage); loader.dismiss(); }); } // close ===================================================================================================== updateuser(){ let refdata = { userid:this.id } this.http.get('http://api.hemam.online/userdate' ,{params: refdata} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(reffetchdata => { var refresult = reffetchdata; localStorage.setItem('user',JSON.stringify(refresult)); this.userdata=refresult; this.navCtrl.setRoot(DashboardPage); }, err => { const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); }); } data = { "image" : "E:\Xampp\htdocs\hemmam\hemmam_admin\web\assets\cn.png", "title": "", "profile" : "", "name" : "", "email": "" , "phone": "", "level": "", "category": "", "test": "", "items": [ { "id": 3, "category": "Interior design trends", "title": "Work It Baby: 14 Interior Design", "like": { "icon":"thumbs-up", "number": "4", "text": "Like", "isActive": true }, "comment": { "icon":"ios-chatbubbles", "number": "4", "text": "Comments", "isActive": false } } ] }; events = { 'onItemClick': function(item: any) { console.log("onItemClick"); }, 'onLike': function(item: any) { if (item && item.like) { if (item.like.isActive) { item.like.isActive = false; item.like.number--; } else { item.like.isActive= true; item.like.number++; }} }, 'onComment': function(item: any) { if (item && item.comment) { if (item.comment.isActive) { item.comment.isActive = false; item.comment.number--; } else { item.comment.isActive= true; item.comment.number++; } } } }; slider = {}; // slideHasChanged(slider, index): void { // this.slider[index] = slider; // if (2 == slider._activeIndex) { // if (this.data.items) { // this.data.items.splice(index, 1); // } else { // this.data.splice(index, 1); // } // } // } onClickEvent(index): void { if (this.slider[index]) { this.slider[index].slidePrev(300); } } onEvent(event: string, item: any, e: any) { if (e) { e.stopPropagation(); } if (this.events[event]) { this.events[event](item); } } gotohistory(){ this.navCtrl.push(HistoryPage); } gotosponser(){ this.navCtrl.push(SponsorPage); } gotopartner(){ this.navCtrl.push(PartnerPage); } gotofounder(){ this.navCtrl.push(FounderPage); } gotolibrary(){ this.navCtrl.push(LibraryPage); } fetchdata :any ; gotochallenge(){ this.navCtrl.push(ChallengePage); } gotohicertificate(){ this.navCtrl.push(CertificatePage); } }
ColiseumSoft786/hemmam-ionic
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { ListPage } from '../pages/list/list'; import { DashboardPage } from '../pages/dashboard/dashboard'; import { ChallengePage } from '../pages/challenge/challenge'; import { LibraryPage } from '../pages/library/library'; import { FounderPage } from '../pages/founder/founder'; import { HistoryPage } from '../pages/history/history'; import { CertificatePage } from '../pages/certificate/certificate'; import { PartnerPage } from '../pages/partner/partner'; import { SponsorPage } from '../pages/sponsor/sponsor'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { HttpModule} from "@angular/http"; import {FileTransfer} from "@ionic-native/file-transfer"; import { File } from '@ionic-native/file'; import {Camera} from "@ionic-native/camera"; import {Chooser} from "@ionic-native/chooser"; import {MediaCapture} from "@ionic-native/media-capture"; import {FileChooser} from "@ionic-native/file-chooser"; import { FileChooserAndroidProvider } from '../providers/file-chooser-android/file-chooser-android'; import {FilePath} from "@ionic-native/file-path"; import {Base64} from "@ionic-native/base64"; @NgModule({ declarations: [ MyApp, HomePage, DashboardPage, ListPage, ChallengePage, LibraryPage, HistoryPage, FounderPage, CertificatePage, PartnerPage, SponsorPage ], imports: [ BrowserModule, HttpModule, IonicModule.forRoot(MyApp), ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, DashboardPage, ListPage, HistoryPage, ChallengePage, LibraryPage, FounderPage, CertificatePage, PartnerPage, SponsorPage ], providers: [ StatusBar, SplashScreen, FileTransfer, File, Camera, Chooser, MediaCapture, FileChooser, FilePath, Base64, FileChooserAndroidProvider, {provide: ErrorHandler, useClass: IonicErrorHandler}, FileChooserAndroidProvider, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class AppModule {}
ColiseumSoft786/hemmam-ionic
src/app/app.component.ts
import { Component, ViewChild } from '@angular/core'; import { Nav, Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { ListPage } from '../pages/list/list'; import { DashboardPage } from '../pages/dashboard/dashboard'; import { HomePage } from '../pages/home/home'; import { ChallengePage } from '../pages/challenge/challenge'; import { HistoryPage } from '../pages/history/history'; import { FounderPage } from '../pages/founder/founder'; import { SponsorPage } from '../pages/sponsor/sponsor'; import { PartnerPage } from '../pages/partner/partner'; import { CertificatePage } from '../pages/certificate/certificate'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = ChallengePage; pages: Array<{title: string, component: any}>; constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) { this.initializeApp(); // used for an example of ngFor and navigation this.pages = [ { title: 'لوحة القيادة', component: DashboardPage }, ]; if (localStorage.getItem("user") === null) { this.rootPage = HomePage; }else{ this.rootPage = DashboardPage; } } logout(){ localStorage.clear(); this.nav.setRoot(HomePage); } initializeApp() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. this.statusBar.styleLightContent(); this.splashScreen.hide(); }); } openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); } }
ColiseumSoft786/hemmam-ionic
src/pages/sponsor/sponsor.module.ts
import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { SponsorPage } from './sponsor'; @NgModule({ declarations: [ SponsorPage, ], imports: [ IonicPageModule.forChild(SponsorPage), ], }) export class SponsorPageModule {}
ColiseumSoft786/hemmam-ionic
src/pages/founder/founder.module.ts
<gh_stars>0 import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { FounderPage } from './founder'; @NgModule({ declarations: [ FounderPage, ], imports: [ IonicPageModule.forChild(FounderPage), ], }) export class FounderPageModule {}
ColiseumSoft786/hemmam-ionic
src/pages/partner/partner.ts
<reponame>ColiseumSoft786/hemmam-ionic import { Component, Input, ViewChild } from '@angular/core'; import { IonicPage, Content } from 'ionic-angular'; /** * Generated class for the PartnerPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-partner', templateUrl: 'partner.html', }) export class PartnerPage { data = { "image" : "assets/partner/logo_partners.png", "image1" : "assets/partner/1.png", "image2" : "assets/partner/2.png", "image3" : "assets/partner/3.png", "image4" : "assets/partner/4.png", "image5" : "assets/partner/5.png", "image6" : "assets/partner/6.png", "image7" : "assets/partner/7.png", "image8" : "assets/partner/8.png", "image9" : "assets/partner/9.png", "image10" : "assets/partner/10.png", "image11" : "assets/partner/11.png", "image12" : "assets/partner/12.png", "image13" : "assets/partner/13.png", "image14" : "assets/partner/14.png", "image15" : "assets/partner/15.png", "image16" : "assets/partner/16.png", "image17" : "assets/partner/17.png", "image18" : "assets/partner/18.png", "image19" : "assets/partner/19.png", "image20" : "assets/partner/20.png", "image21" : "assets/partner/21.png", "image22" : "assets/partner/22.png", "image23" : "assets/partner/23.png", "image24" : "assets/partner/24.png", "image25" : "assets/partner/25.png", "image26" : "assets/partner/26.png", "title": "<NAME>", "subtitle": "Extreme coffee lover. Twitter maven. Internet practitioner. Beeraholic.", "category": "populary", "followers": "Followers", "valueFollowers": "439", "following": "Following", "valueFollowing": "297", "posts": "Posts", "valuePosts": "43", "items": [ { "id": 1, "category": "Prisma Labs", "title": "Prisma Photo Editor", "like": { "icon":"thumbs-up", "text": "Like", "isActive": true }, "comment": { "icon":"ios-chatbubbles", "number": "4", "text": "Comments", "isActive": false } }, { "id": 2, "category": "Apple watch", "title": "Built with your heart in mind", "like": { "icon":"thumbs-up", "text": "Like", "isActive": true }, "comment": { "icon":"ios-chatbubbles", "number": "4", "text": "Comments", "isActive": false } }, { "id": 3, "category": "Interior design trends", "title": "Work It Baby: 14 Interior Design", "like": { "icon":"thumbs-up", "text": "Like", "isActive": true }, "comment": { "icon":"ios-chatbubbles", "number": "4", "text": "Comments", "isActive": false } } ] }; constructor() { } }
ColiseumSoft786/hemmam-ionic
src/providers/file-chooser-android/file-chooser-android.ts
import {Injectable} from '@angular/core'; import {File, FileEntry, IFile} from "@ionic-native/file"; import {Base64} from "@ionic-native/base64"; import {FilePath} from "@ionic-native/file-path"; import {FileChooser} from "@ionic-native/file-chooser"; /* Generated class for the FileChooserAndroidProvider provider. See https://angular.io/guide/dependency-injection for more info on providers and Angular DI. */ @Injectable() export class FileChooserAndroidProvider { constructor(private base64: Base64, private filePath: FilePath, private file: File, private fileChooser: FileChooser) { } getFileInfo(): Promise<any> { return this.fileChooser.open().then((fileURI) => { return this.filePath.resolveNativePath(fileURI).then((filePath) => { return this.file.resolveLocalFilesystemUrl(filePath).then((fileEntry: FileEntry) => { return new Promise((resolve, reject) => { fileEntry.file(meta => resolve(meta), error => reject(error)); }); }).then((fileMeta: IFile) => { return new Promise((resolve, reject) => { return this.base64.encodeFile(filePath).then((base64Data) => { resolve({ fileData: base64Data, fileName: fileMeta.name, fileSize: fileMeta.size, fileType: fileMeta.type }) }).catch((error) => { reject(error); }) }) }); }); }); } }
ColiseumSoft786/hemmam-ionic
src/pages/certificate/certificate.module.ts
<filename>src/pages/certificate/certificate.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { CertificatePage } from './certificate'; @NgModule({ declarations: [ CertificatePage, ], imports: [ IonicPageModule.forChild(CertificatePage), ], }) export class CertificatePageModule {}
ColiseumSoft786/hemmam-ionic
src/pages/founder/founder.ts
import { Component, ViewChild } from '@angular/core'; import { IonicPage, Content, ActionSheetController } from 'ionic-angular'; /** * Generated class for the FounderPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-founder', templateUrl: 'founder.html', }) export class FounderPage { data = { "image1" : "assets/1.png", "image2" : "assets/2.png", "image3" : "assets/3.png", "image4" : "assets/4.png", "title": "<NAME>", "subtitle": "Extreme coffee lover. Twitter maven. Internet practitioner. Beeraholic.", "category": "populary", "followers": "Followers", "valueFollowers": "439", "following": "Following", "valueFollowing": "297", "posts": "Posts", "valuePosts": "43", "items": [ { "id": 1, "category": "Prisma Labs", "title": "Prisma Photo Editor", "like": { "icon":"thumbs-up", "text": "Like", "isActive": true }, "comment": { "icon":"ios-chatbubbles", "number": "4", "text": "Comments", "isActive": false } }, { "id": 2, "category": "Apple watch", "title": "Built with your heart in mind", "like": { "icon":"thumbs-up", "text": "Like", "isActive": true }, "comment": { "icon":"ios-chatbubbles", "number": "4", "text": "Comments", "isActive": false } }, { "id": 3, "category": "Interior design trends", "title": "Work It Baby: 14 Interior Design", "like": { "icon":"thumbs-up", "text": "Like", "isActive": true }, "comment": { "icon":"ios-chatbubbles", "number": "4", "text": "Comments", "isActive": false } } ] }; constructor() { } }
ColiseumSoft786/hemmam-ionic
src/pages/challenge/challenge.ts
import {Component} from '@angular/core'; import {IonicPage, NavController, NavParams, Platform} from 'ionic-angular'; import {LoadingController , ToastController} from 'ionic-angular'; import 'rxjs/add/operator/map'; import {Http, RequestOptions} from "@angular/http"; import { MenuController } from 'ionic-angular'; import { DashboardPage } from '../dashboard/dashboard'; import { HomePage } from '../home/home'; import {FileTransfer} from "@ionic-native/file-transfer"; import {File} from "@ionic-native/file"; import {Camera} from "@ionic-native/camera"; import {Observable} from "rxjs"; import { Chooser } from '@ionic-native/chooser'; import { MediaCapture } from '@ionic-native/media-capture'; import {FileChooser} from "@ionic-native/file-chooser"; import {FileChooserAndroidProvider} from "../../providers/file-chooser-android/file-chooser-android"; import {HttpHeaders} from "@angular/common/http"; /** * Generated class for the ChallengePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-challenge', templateUrl: 'challenge.html', }) export class ChallengePage { events = { "onSubmit": function(item: any) { console.log("onSubmit"); } }; challenge :any; firstName:any; task: any; lastName: any; address1: any; address2: any; city: any; zipCode: any; name: any; id:any; email: any; videolevel: any; userdata: any; fetchdata: any; ressult : any ; selected: any; challengeStatus:any; MyselectedChalenge:any; constructor(private fileChooserAndroid: FileChooserAndroidProvider,private fileChooser: FileChooser,private mediaCapture: MediaCapture,private chooser: Chooser,public platform: Platform,public navParams: NavParams,private transfer: FileTransfer, private file: File,private camera: Camera, public menuCtrl: MenuController , public navCtrl: NavController,private http:Http , private loadingCtrl: LoadingController , private toastCtrl: ToastController) { this.menuCtrl.enable(true, 'logMenu'); if (localStorage.getItem("user") === null) { this.navCtrl.setRoot(HomePage); }else{ this.userdata = JSON.parse(localStorage.getItem('user')); this.name=this.userdata.name; this.email=this.userdata.email; this.challengeStatus =this.userdata.challengestatus; // console.log(this.userdata); // console.log(this.userdata.challengestatus , '======'); this.id=this.userdata.id; if(this.userdata.level_status == null){ this.videolevel = 1 ; }else{ this.videolevel=this.userdata.level_status.id; } if(this.challengeStatus == 1){ this.fetchChallenges(); } // fetching Task let fetch = { userid:this.videolevel }; const loader = this.loadingCtrl.create({ content: " ... ارجوك انتظر", }); loader.present(); this.http.get('http://api.hemam.online/task' ,{params: fetch} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(fetchdata => { var fresult = fetchdata; this.fetchdata = fetchdata; this.ressult = fresult; loader.dismiss(); if(fresult == 0){ const toast = this.toastCtrl.create({ message: '* خطأ في الخادم ، يرجى إعادة المحاولة لاحقًا', duration: 4000 }); toast.present(); }else{ } },err => { loader.dismiss(); const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); this.navCtrl.setRoot(DashboardPage); }); // fetching Task close . } } empty :any ; fetchChallenges(){ let datta = { userid:this.id, }; const loader = this.loadingCtrl.create({ content: " ... ارجوك انتظر", }); loader.present(); this.http.get('http://api.hemam.online/fetchchallenge' ,{params: datta} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(dataa => { loader.dismiss(); this.MyselectedChalenge = dataa; if(dataa.length == 0){ this.empty = 1 ; }else{ this.empty = 0 ; } console.log(this.MyselectedChalenge); }); } public myphoto; public imgdata; public fileer: any; user: any; dataa: any; vid: any; public videoset: boolean = false; sendchallenge(){ if (this.task.length == 0) { const toast = this.toastCtrl.create({ message: 'بيانات الاعتماد الخاصة بك ليست صحيحة', duration: 4000 }); toast.present(); }else{ console.log("clicked submit btn"); let datta = { videotask: JSON.stringify(this.task), userid:this.id, level:this.videolevel, }; console.log(datta.videotask); const loader = this.loadingCtrl.create({ content: " ... جلب البيانات", }); loader.present(); this.http.get('http://api.hemam.online/sendchallenge' ,{params: datta} ).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(dataa => { var result = dataa; this.MyselectedChalenge = dataa[0]; this.challengeStatus = 1; let user = JSON.stringify(dataa[1]); localStorage.setItem('user',user); console.log(result); loader.dismiss(); if (result != 0 ){ const toast = this.toastCtrl.create({ message: 'تم تحميل الفيديو بنجاح ', duration: 4000 }); toast.present(); }else{ const toast = this.toastCtrl.create({ message: 'بيانات الاعتماد الخاصة بك ليست صحيحة', duration: 4000 }); toast.present(); } }, err => { loader.dismiss(); const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); }); } } private currentid; clickupload(id){ this.currentid = id; document.getElementById('uploadfile').click(); } uploadfromfile($event) : void{ this.fileer = $event.target.files[0]; if (this.fileer != null){ const loader = this.loadingCtrl.create({ content: "Loading...", }); loader.present(); let clientConfirmData = new FormData(); clientConfirmData.append('photo', this.fileer); // var headers = new Headers(); // headers.append('Content-Type', 'multipart/form-data' ); // const requestOptions = new RequestOptions({ headers: headers }); this.http.post('http://api.hemam.online/videosender?userid='+this.currentid,clientConfirmData).map(res => res.json()).catch(error => Observable.create(error.json())).subscribe(dataa => { console.log(JSON.stringify(dataa)); this.MyselectedChalenge = dataa; const toast = this.toastCtrl.create({ message: 'تم تحميل الفيديو بنجاح', duration: 5000 }); toast.present(); this.navCtrl.setRoot(DashboardPage); loader.dismiss(); },err => { loader.dismiss(); const toast = this.toastCtrl.create({ message: 'شيء ما خطأ. حاول مرة اخرى', duration: 4000 }); toast.present(); }); } } onEvent(event: string, e: any) { if (e) { e.stopPropagation(); } if (this.events[event]) { this.events[event](this.getItemData()); this.resetValue(); } } getItemData() { return { 'firstName': this.firstName, 'lastName':this.lastName, 'address1':this.address1, 'address2':this.address2, 'city':this.city, 'zipCode':this.zipCode }; } resetValue() { } }
Adatta1276/react-p5-wrapper
tests/__fixtures__/sketch.ts
<gh_stars>0 import p5 from "p5"; export function sketch(p5: p5) { p5.setup = () => p5.createCanvas(720, 400); p5.draw = () => { p5.background(127); p5.noStroke(); for (let i = 0; i < p5.height; i += 20) { p5.fill(129, 206, 15); p5.rect(0, i, p5.width, 10); p5.fill(255); p5.rect(i, 0, 10, p5.height); } }; }
Adatta1276/react-p5-wrapper
tests/index.test.tsx
<reponame>Adatta1276/react-p5-wrapper import React from "react"; import { render } from "@testing-library/react"; import P5Wrapper from "../src/index"; import { sketch } from "./__fixtures__/sketch"; describe("P5Wrapper", () => { it("renders the component", () => { const { container: wrapper, asFragment } = render( <P5Wrapper sketch={sketch} attributes={{}} /> ); const canvas = wrapper.querySelector("canvas"); expect(canvas).toBeInstanceOf(HTMLCanvasElement); expect(canvas.className).toBe("p5Canvas"); expect(asFragment()).toMatchSnapshot(); }); });
highfi13g/docs
components/sublanding/ArticleCard.tsx
<filename>components/sublanding/ArticleCard.tsx import { ArticleGuide } from 'components/context/ProductSubLandingContext' import { Label } from '@primer/components' type Props = { card: ArticleGuide typeLabel: string } export const ArticleCard = ({ card, typeLabel }: Props) => { return ( <div data-testid="article-card" className="d-flex col-12 col-md-4 pr-0 pr-md-6 pr-lg-8"> <a className="no-underline d-flex flex-column py-3 border-bottom" href={card.href}> <h4 className="h4 color-fg-default mb-1" dangerouslySetInnerHTML={{ __html: card.title }} /> <div className="h6 text-uppercase" data-testid="article-card-type"> {typeLabel} </div> <p className="color-fg-muted my-3" dangerouslySetInnerHTML={{ __html: card.intro }} /> {card.topics.length > 0 && ( <div> {card.topics.map((topic) => { return ( <Label key={topic} data-testid="article-card-topic" variant="small" sx={{ bg: 'accent.emphasis', mr: 1 }} > {topic} </Label> ) })} </div> )} </a> </div> ) }
nick-laqua-dragon/backstage
packages/core-components/src/layout/Sidebar/index.ts
/* * Copyright 2020 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export { Sidebar, SidebarExpandButton } from './Bar'; export { SidebarSubmenuItem } from './SidebarSubmenuItem'; export { SidebarSubmenu } from './SidebarSubmenu'; export type { SidebarSubmenuProps } from './SidebarSubmenu'; export type { SidebarSubmenuItemProps, SidebarSubmenuItemDropdownItem, } from './SidebarSubmenuItem'; export type { SidebarClassKey } from './Bar'; export { SidebarPage, SidebarPinStateContext } from './Page'; export type { SidebarPinStateContextType, SidebarPageClassKey } from './Page'; export { SidebarDivider, SidebarItem, SidebarSearchField, SidebarSpace, SidebarSpacer, SidebarScrollWrapper, } from './Items'; export type { SidebarItemClassKey } from './Items'; export { IntroCard, SidebarIntro } from './Intro'; export type { SidebarIntroClassKey } from './Intro'; export { SIDEBAR_INTRO_LOCAL_STORAGE, SidebarContext, sidebarConfig, } from './config'; export type { SidebarContextType } from './config';
nick-laqua-dragon/backstage
plugins/permission-react/src/components/PermissionedRoute.tsx
<gh_stars>0 /* * Copyright 2021 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React, { ComponentProps, ReactElement } from 'react'; import { Route } from 'react-router'; import { useApp } from '@backstage/core-plugin-api'; import { usePermission } from '../hooks'; import { Permission } from '@backstage/plugin-permission-common'; /** * Returns a React Router Route which only renders the element when authorized. If unathorized, the Route will render a * NotFoundErrorPage (see {@link @backstage/core-app-api#AppComponents}). * @public */ export const PermissionedRoute = ({ permission, resourceRef, errorComponent, ...props }: ComponentProps<typeof Route> & { permission: Permission; resourceRef?: string; errorComponent?: ReactElement | null; }) => { const permissionResult = usePermission(permission, resourceRef); const app = useApp(); const { NotFoundErrorPage } = app.getComponents(); let shownElement: ReactElement | null | undefined = errorComponent === undefined ? <NotFoundErrorPage /> : errorComponent; if (permissionResult.loading) { shownElement = null; } else if (permissionResult.allowed) { shownElement = props.element; } return <Route {...props} element={shownElement} />; };
nick-laqua-dragon/backstage
plugins/permission-node/src/integration/createPermissionIntegrationRouter.ts
/* * Copyright 2021 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import express, { Response, Router } from 'express'; import { z } from 'zod'; import { AuthorizeResult, PermissionCondition, PermissionCriteria, } from '@backstage/plugin-permission-common'; import { PermissionRule } from '../types'; import { createGetRule, isAndCriteria, isNotCriteria, isOrCriteria, } from './util'; const permissionCriteriaSchema: z.ZodSchema< PermissionCriteria<PermissionCondition> > = z.lazy(() => z.union([ z.object({ anyOf: z.array(permissionCriteriaSchema) }), z.object({ allOf: z.array(permissionCriteriaSchema) }), z.object({ not: permissionCriteriaSchema }), z.object({ rule: z.string(), params: z.array(z.unknown()), }), ]), ); const applyConditionsRequestSchema = z.object({ resourceRef: z.string(), resourceType: z.string(), conditions: permissionCriteriaSchema, }); /** * A request to load the referenced resource and apply conditions in order to * finalize a conditional authorization response. * * @public */ export type ApplyConditionsRequest = { resourceRef: string; resourceType: string; conditions: PermissionCriteria<PermissionCondition>; }; /** * The result of applying the conditions, expressed as a definitive authorize * result of ALLOW or DENY. * * @public */ export type ApplyConditionsResponse = { result: AuthorizeResult.ALLOW | AuthorizeResult.DENY; }; const applyConditions = <TResource>( criteria: PermissionCriteria<PermissionCondition>, resource: TResource, getRule: (name: string) => PermissionRule<TResource, unknown>, ): boolean => { if (isAndCriteria(criteria)) { return criteria.allOf.every(child => applyConditions(child, resource, getRule), ); } else if (isOrCriteria(criteria)) { return criteria.anyOf.some(child => applyConditions(child, resource, getRule), ); } else if (isNotCriteria(criteria)) { return !applyConditions(criteria.not, resource, getRule); } return getRule(criteria.rule).apply(resource, ...criteria.params); }; /** * Create an express Router which provides an authorization route to allow integration between the * permission backend and other Backstage backend plugins. Plugin owners that wish to support * conditional authorization for their resources should add the router created by this function * to their express app inside their `createRouter` implementation. * * @remarks * * To make this concrete, we can use the Backstage software catalog as an example. The catalog has * conditional rules around access to specific _entities_ in the catalog. The _type_ of resource is * captured here as `resourceType`, a string identifier (`catalog-entity` in this example) that can * be provided with permission definitions. This is merely a _type_ to verify that conditions in an * authorization policy are constructed correctly, not a reference to a specific resource. * * The `rules` parameter is an array of {@link PermissionRule}s that introduce conditional * filtering logic for resources; for the catalog, these are things like `isEntityOwner` or * `hasAnnotation`. Rules describe how to filter a list of resources, and the `conditions` returned * allow these rules to be applied with specific parameters (such as 'group:default/team-a', or * 'backstage.io/edit-url'). * * The `getResource` argument should load a resource by reference. For the catalog, this is an * {@link @backstage/catalog-model#EntityRef}. For other plugins, this can be any serialized format. * This is used to construct the `createPermissionIntegrationRouter`, a function to add an * authorization route to your backend plugin. This route will be called by the `permission-backend` * when authorization conditions relating to this plugin need to be evaluated. * @public */ export const createPermissionIntegrationRouter = <TResource>({ resourceType, rules, getResource, }: { resourceType: string; rules: PermissionRule<TResource, any>[]; getResource: (resourceRef: string) => Promise<TResource | undefined>; }): Router => { const router = Router(); const getRule = createGetRule(rules); router.post( '/.well-known/backstage/permissions/apply-conditions', express.json(), async ( req, res: Response< | { result: Omit<AuthorizeResult, AuthorizeResult.CONDITIONAL>; } | string >, ) => { const parseResult = applyConditionsRequestSchema.safeParse(req.body); if (!parseResult.success) { return res.status(400).send(`Invalid request body.`); } const { data: body } = parseResult; if (body.resourceType !== resourceType) { return res .status(400) .send(`Unexpected resource type: ${body.resourceType}.`); } const resource = await getResource(body.resourceRef); if (!resource) { return res .status(400) .send(`Resource for ref ${body.resourceRef} not found.`); } return res.status(200).json({ result: applyConditions(body.conditions, resource, getRule) ? AuthorizeResult.ALLOW : AuthorizeResult.DENY, }); }, ); return router; };
nick-laqua-dragon/backstage
plugins/analytics-module-ga/src/apis/implementations/AnalyticsApi/GoogleAnalytics.ts
<reponame>nick-laqua-dragon/backstage /* * Copyright 2021 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import ReactGA from 'react-ga'; import { AnalyticsApi, AnalyticsContextValue, AnalyticsEventAttributes, AnalyticsEvent, } from '@backstage/core-plugin-api'; import { Config } from '@backstage/config'; type CustomDimensionOrMetricConfig = { type: 'dimension' | 'metric'; index: number; source: 'context' | 'attributes'; key: string; }; /** * Google Analytics API provider for the Backstage Analytics API. */ export class GoogleAnalytics implements AnalyticsApi { private readonly cdmConfig: CustomDimensionOrMetricConfig[]; /** * Instantiate the implementation and initialize ReactGA. */ private constructor({ cdmConfig, trackingId, scriptSrc, testMode, debug, }: { cdmConfig: CustomDimensionOrMetricConfig[]; trackingId: string; scriptSrc?: string; testMode: boolean; debug: boolean; }) { this.cdmConfig = cdmConfig; // Initialize Google Analytics. ReactGA.initialize(trackingId, { testMode, debug, gaAddress: scriptSrc, titleCase: false, }); } /** * Instantiate a fully configured GA Analytics API implementation. */ static fromConfig(config: Config) { // Get all necessary configuration. const trackingId = config.getString('app.analytics.ga.trackingId'); const scriptSrc = config.getOptionalString('app.analytics.ga.scriptSrc'); const debug = config.getOptionalBoolean('app.analytics.ga.debug') ?? false; const testMode = config.getOptionalBoolean('app.analytics.ga.testMode') ?? false; const cdmConfig = config .getOptionalConfigArray('app.analytics.ga.customDimensionsMetrics') ?.map(c => { return { type: c.getString('type') as CustomDimensionOrMetricConfig['type'], index: c.getNumber('index'), source: c.getString( 'source', ) as CustomDimensionOrMetricConfig['source'], key: c.getString('key'), }; }) ?? []; // Return an implementation instance. return new GoogleAnalytics({ trackingId, scriptSrc, cdmConfig, testMode, debug, }); } /** * Primary event capture implementation. Handles core navigate event as a * pageview and the rest as custom events. All custom dimensions/metrics are * applied as they should be (set on pageview, merged object on events). */ captureEvent({ context, action, subject, value, attributes, }: AnalyticsEvent) { const customMetadata = this.getCustomDimensionMetrics(context, attributes); if (action === 'navigate' && context.extension === 'App') { // Set any/all custom dimensions. if (Object.keys(customMetadata).length) { ReactGA.set(customMetadata); } ReactGA.pageview(subject); return; } ReactGA.event({ category: context.extension || 'App', action, label: subject, value, ...customMetadata, }); } /** * Returns an object of dimensions/metrics given an Analytics Context and an * Event Attributes, e.g. { dimension1: "some value", metric8: 42 } */ private getCustomDimensionMetrics( context: AnalyticsContextValue, attributes: AnalyticsEventAttributes = {}, ) { const customDimensionsMetrics: { [x: string]: string | number | boolean } = {}; this.cdmConfig.forEach(config => { const value = config.source === 'context' ? context[config.key] : attributes[config.key]; // Never pass a non-numeric value on a metric. if (config.type === 'metric' && typeof value !== 'number') { return; } // Only set defined values. if (value !== undefined) { customDimensionsMetrics[`${config.type}${config.index}`] = value; } }); return customDimensionsMetrics; } }
Neurone/ethers.js
src.ts/_version.ts
export const version = "4.0.47";
valentynpatsera/metacomponents
types/index.d.ts
<filename>types/index.d.ts<gh_stars>0 interface Metacomponent { tag: string; meta?: ImportMeta; text?: string; styles?: Styles; props?: Partial<HTMLInputElement>; attrs?: Attrs; state?: any; methods?: Methods; events?: Events; channels?: Channels; hooks?: Hooks; children?: Array<Metacomponent | MetacomponentConfig | false | null | undefined>; } interface ImportMeta { url: string; } interface ChannelOptions { scope?: string | string[]; } interface MetacomponentApi { emitCustomEvent(name: string, data?: any): boolean; emitMessage(name: string, data?: any, options?: ChannelOptions): boolean; click(): void; focus(): void; blur(): void; } interface MetacomponentConfig { path: string; base?: string; args?: Parameters<any>; } type CSSProps = Partial<Record<keyof CSSStyleDeclaration, string | number>>; interface Attrs { style?: CSSProps; [attr: string]: string | number | boolean | undefined | CSSProps; } type MetacomponentInstance = Required<Metacomponent & MetacomponentApi>; interface Methods { [method: string]: (this: MetacomponentInstance, ...args) => any; } interface Events { [event: string]: (this: MetacomponentInstance, event?: any) => void; } interface Channels { [channel: string]: (this: MetacomponentInstance, data?: any) => void; } interface Hooks { init(this: MetacomponentInstance): void; } interface PseudoFunction { arg: string; rule: PseudoStyles; } interface PseudoStyles extends CSSProps { hover?: PseudoStyles; focus?: PseudoStyles; checked?: PseudoStyles; active?: PseudoStyles; disabled?: PseudoStyles; link?: PseudoStyles; visited?: PseudoStyles; first?: PseudoStyles; last?: PseudoStyles; before?: PseudoStyles; after?: PseudoStyles; placeholder?: PseudoStyles; nth?: PseudoFunction; not?: PseudoFunction; } interface CssAnimation { name: string; props: string; keyframes: { [key: string]: CSSProps; }; } interface Styles extends PseudoStyles { animations?: CssAnimation[]; }
uzelac92/jsPDF-AutoTable
test/testWidthCalculator.ts
const assert = require('assert') import { resizeColumns } from '../src/widthCalculator' import { Column } from '../src/models' describe('calculator', () => { describe('columns resizer', () => { it('shrink: one column - no min', () => { const col1 = new Column('col1', null, 0) col1.width = 700 col1.wrappedWidth = 700 const resizeWidth = resizeColumns([col1], -700, () => 0) assert.equal(col1.width, 0, 'width') assert.equal(resizeWidth, 0, 'resizeWidth') }) it('shrink: one column - min', () => { const col1 = new Column('col1', null, 0) col1.width = 700 col1.wrappedWidth = 700 col1.minWidth = 200 const resizeWidth = resizeColumns([col1], -600, (col) => col.minWidth) assert.equal(col1.width, 200, 'width') assert.equal(resizeWidth, -100, 'resizeWidth') }) it('shrink: two columns - no min', () => { const w1 = 1200, w2 = 400, r = -500 const col1 = new Column('col1', null, 0) col1.width = w1 col1.wrappedWidth = w1 const col2 = new Column('col2', null, 1) col2.width = w2 col2.wrappedWidth = w2 const resizeWidth = resizeColumns([col1, col2], r, () => 0) assert.equal(col1.width, w1 + r * (w1 / (w1 + w2)), 'col1 width') assert.equal(col2.width, w2 + r * (w2 / (w1 + w2)), 'col2 width') assert.equal(resizeWidth, 0, 'resizeWidth') }) it('shrink: two columns - min', () => { const w1 = 1200, w2 = 400, r = -500 const col1 = new Column('col1', null, 0) col1.width = w1 col1.wrappedWidth = w1 col1.minWidth = 900 const col2 = new Column('col2', null, 1) col2.width = w2 col2.wrappedWidth = w2 col2.minWidth = 100 const resizeWidth = resizeColumns([col1, col2], r, (col) => col.minWidth) assert.equal(col1.width, 900, 'col1 width') assert.equal(col2.width, 200, 'col2 width') assert.equal(resizeWidth, 0, 'resizeWidth') }) // this case will test if the space distribution is consistent for equal columns (important) it('shrink: consistent distribution', () => { const w1 = 1200, w2 = 400, r = -500 const col1 = new Column('col1', null, 0) col1.width = w1 col1.wrappedWidth = w1 col1.minWidth = 350 const col2 = new Column('col2', null, 0) col2.width = w2 col2.wrappedWidth = w2 col2.minWidth = 350 const col3 = new Column('col3', null, 0) col3.width = w1 col3.wrappedWidth = w1 col3.minWidth = 350 const col4 = new Column('col4', null, 0) col4.width = w2 col4.wrappedWidth = w2 col4.minWidth = 350 let resizeWidth = resizeColumns( [col1, col2, col3, col4], r, (col) => col.minWidth ) assert.equal(resizeWidth, 0, 'resizeWidth') assert.equal(col1.width, col3.width, 'col1 = col3') assert.equal(col2.width, col4.width, 'col2 = col4') resizeWidth = resizeColumns( [col1, col2, col4, col3], r, (col) => col.minWidth ) assert.equal(resizeWidth, 0, 'resizeWidth') assert.equal(col1.width, col3.width, 'col1 = col3') assert.equal(col2.width, col4.width, 'col2 = col4') }) it('grow: two columns - no min', () => { const w1 = 50, w2 = 60, r = 1000 const col1 = new Column('col1', null, 0) col1.width = w1 col1.wrappedWidth = w1 const col2 = new Column('col2', null, 1) col2.width = w2 col2.wrappedWidth = w2 const resizeWidth = resizeColumns([col1, col2], r, () => 0) assert.equal( Math.round(col1.width), Math.round(w1 + r * (w1 / (w1 + w2))), 'col3 width' ) assert.equal( Math.round(col2.width), Math.round(w2 + r * (w2 / (w1 + w2))), 'col2 width' ) assert.equal(resizeWidth, 0, 'resizeWidth') }) it('grow: three columns - col1 min', () => { const w1 = 50, w2 = 60, w3 = 70, r = 1000 const col1 = new Column('col1', null, 0) col1.width = w1 col1.wrappedWidth = w1 col1.minWidth = 500 const col2 = new Column('col2', null, 1) col2.width = w2 col2.wrappedWidth = w2 const col3 = new Column('col3', null, 1) col3.width = w3 col3.wrappedWidth = w3 const resizeWidth = resizeColumns( [col1, col2, col3], r, (col) => col.minWidth ) assert.equal(col1.width, 500, 'col1 width') assert.equal( Math.round(col2.width), Math.round(w2 + (r - col1.minWidth + w1) * (w2 / (w2 + w3))), 'col2 width' ) assert.equal( Math.round(col3.width), Math.round(w3 + (r - col1.minWidth + w1) * (w3 / (w2 + w3))), 'col3 width' ) assert.equal(resizeWidth, 0, 'resizeWidth') }) }) })
uzelac92/jsPDF-AutoTable
src/tableCalculator.ts
import { DocHandler, jsPDFDocument } from './documentHandler' import { Cell, Column, Row, Section, StylesProps, Table } from './models' import { calculateWidths } from './widthCalculator' import { CellInput, ColumnInput, defaultStyles, getTheme, RowInput, Styles, ThemeName, } from './config' import { assign } from './polyfills' import { TableInput } from './inputParser' export function createTable(jsPDFDoc: jsPDFDocument, input: TableInput) { const doc = new DocHandler(jsPDFDoc) const content = parseContent(input, doc.scaleFactor()) const table = new Table(input, content) calculateWidths(doc, table) doc.applyStyles(doc.userStyles) return table } function parseContent(input: TableInput, sf: number) { const content = input.content const columns = createColumns(content.columns) // If no head or foot is set, try generating it with content from columns if (content.head.length === 0) { const sectionRow = generateSectionRow(columns, 'head') if (sectionRow) content.head.push(sectionRow) } if (content.foot.length === 0) { const sectionRow = generateSectionRow(columns, 'foot') if (sectionRow) content.foot.push(sectionRow) } const theme = input.settings.theme const styles = input.styles return { columns, head: parseSection('head', content.head, columns, styles, theme, sf), body: parseSection('body', content.body, columns, styles, theme, sf), foot: parseSection('foot', content.foot, columns, styles, theme, sf), } } function parseSection( sectionName: Section, sectionRows: RowInput[], columns: Column[], styleProps: StylesProps, theme: ThemeName, scaleFactor: number ): Row[] { const rowSpansLeftForColumn: { [key: string]: { left: number; times: number } } = {} const result = sectionRows.map((rawRow, rowIndex) => { let skippedRowForRowSpans = 0 const cells: { [key: string]: Cell } = {} let colSpansAdded = 0 let columnSpansLeft = 0 for (const column of columns) { if ( rowSpansLeftForColumn[column.index] == null || rowSpansLeftForColumn[column.index].left === 0 ) { if (columnSpansLeft === 0) { let rawCell if (Array.isArray(rawRow)) { rawCell = rawRow[column.index - colSpansAdded - skippedRowForRowSpans] } else { rawCell = rawRow[column.dataKey] } let cellInputStyles = {} if (typeof rawCell === 'object' && !Array.isArray(rawCell)) { cellInputStyles = rawCell?.styles || {} } const styles = cellStyles( sectionName, column, rowIndex, theme, styleProps, scaleFactor, cellInputStyles ) const cell = new Cell(rawCell, styles, sectionName) // dataKey is not used internally no more but keep for // backwards compat in hooks cells[column.dataKey] = cell cells[column.index] = cell columnSpansLeft = cell.colSpan - 1 rowSpansLeftForColumn[column.index] = { left: cell.rowSpan - 1, times: columnSpansLeft, } } else { columnSpansLeft-- colSpansAdded++ } } else { rowSpansLeftForColumn[column.index].left-- columnSpansLeft = rowSpansLeftForColumn[column.index].times skippedRowForRowSpans++ } } return new Row(rawRow, rowIndex, sectionName, cells) }) return result } function generateSectionRow( columns: Column[], section: Section ): RowInput | null { const sectionRow: { [key: string]: CellInput } = {} columns.forEach((col) => { if (col.raw != null) { const title = getSectionTitle(section, col.raw) if (title != null) sectionRow[col.dataKey] = title } }) return Object.keys(sectionRow).length > 0 ? sectionRow : null } function getSectionTitle(section: Section, column: ColumnInput) { if (section === 'head') { if (typeof column === 'object') { return column.header || column.title || null } else if (typeof column === 'string' || typeof column === 'number') { return column } } else if (section === 'foot' && typeof column === 'object') { return column.footer } return null } function createColumns(columns: ColumnInput[]) { return columns.map((input, index) => { let key if (typeof input === 'object') { key = input.dataKey ?? input.key ?? index } else { key = index } return new Column(key, input, index) }) } function cellStyles( sectionName: Section, column: Column, rowIndex: number, themeName: ThemeName, styles: StylesProps, scaleFactor: number, cellInputStyles: Partial<Styles> ) { const theme = getTheme(themeName) let sectionStyles if (sectionName === 'head') { sectionStyles = styles.headStyles } else if (sectionName === 'body') { sectionStyles = styles.bodyStyles } else if (sectionName === 'foot') { sectionStyles = styles.footStyles } const otherStyles = assign( {}, theme.table, theme[sectionName], styles.styles, sectionStyles ) const columnStyles = styles.columnStyles[column.dataKey] || styles.columnStyles[column.index] || {} const colStyles = sectionName === 'body' ? columnStyles : {} const rowStyles = sectionName === 'body' && rowIndex % 2 === 0 ? assign({}, theme.alternateRow, styles.alternateRowStyles) : {} const defaultStyle = defaultStyles(scaleFactor) const themeStyles = assign( {}, defaultStyle, otherStyles, rowStyles, colStyles ) return assign(themeStyles, cellInputStyles) }
uzelac92/jsPDF-AutoTable
src/HookData.ts
<gh_stars>1000+ import { DocHandler, jsPDFDocument } from './documentHandler' import { Table, Cell, Row, Column, Settings, Pos } from './models' export class HookData { table: Table pageNumber: number pageCount: number // Deprecated, use pageNumber instead settings: Settings doc: jsPDFDocument cursor: Pos | null constructor(doc: DocHandler, table: Table, cursor: Pos | null) { this.table = table this.pageNumber = table.pageNumber this.pageCount = this.pageNumber this.settings = table.settings this.cursor = cursor this.doc = doc.getDocument() } } export class CellHookData extends HookData { cell: Cell row: Row column: Column section: 'head' | 'body' | 'foot' constructor( doc: DocHandler, table: Table, cell: Cell, row: Row, column: Column, cursor: Pos | null ) { super(doc, table, cursor) this.cell = cell this.row = row this.column = column this.section = row.section } }
uzelac92/jsPDF-AutoTable
test/testHtmlParser.ts
<reponame>uzelac92/jsPDF-AutoTable import { parseHtml } from '../src/htmlParser' import { DocHandler } from '../src/documentHandler' import { loadJspdf } from './common' const assert = require('assert') const jsdom = require('jsdom') const dom = new jsdom.JSDOM('') const jsPDF = loadJspdf() describe('html parser', () => { it('full table', () => { const doc = new DocHandler(new jsPDF()) const table = dom.window.document.createElement('table') let section = table.createTBody() let row = section.insertRow() let cell1 = row.insertCell() cell1.innerHTML = '<p>test</p>' let cell2 = row.insertCell() cell2.innerHTML = '<p>test</p>' section = table.createTHead() row = section.insertRow() cell1 = row.insertCell() cell1.innerHTML = '<p>test</p>' section = table.createTFoot() row = section.insertRow() cell1 = row.insertCell() cell1.innerHTML = '<p>test</p>' const res = parseHtml(doc, table, dom.window) assert(res, 'Should have result') assert(res.head[0].length, 'Should have head cell') assert.equal(res.body[0].length, 2, 'Should have two body cells') assert(res.foot[0].length, 'Should have foot cell') }) it('cloned table', () => { const doc = new DocHandler(new jsPDF()) const table = dom.window.document.createElement('table') let section = table.createTBody() let row = section.insertRow() let cell1 = row.insertCell() cell1.innerHTML = '<p>test</p>' let cell2 = row.insertCell() cell2.innerHTML = '<p>test</p>' section = table.createTHead() row = section.insertRow() cell1 = row.insertCell() cell1.innerHTML = '<p>test</p>' section = table.createTFoot() row = section.insertRow() cell1 = row.insertCell() cell1.innerHTML = '<p>test</p>' const res = parseHtml(doc, table.cloneNode(true), dom.window) assert(res, 'Should have result') assert(res.head[0].length, 'Should have head cell') assert.equal(res.body[0].length, 2, 'Should have two body cells') assert(res.foot[0].length, 'Should have foot cell') }) it('hidden content', () => { const doc = new DocHandler(new jsPDF()) const table = dom.window.document.createElement('table') let section = table.createTBody() let row = section.insertRow() let cell1 = row.insertCell() cell1.style.display = 'none' cell1.innerHTML = '<p>test</p>' let cell2 = row.insertCell() cell2.innerHTML = '<p>test</p>' section = table.createTHead() row = section.insertRow() cell1 = row.insertCell() cell1.style.display = 'none' cell1.innerHTML = '<p>test</p>' section = table.createTFoot() row = section.insertRow() cell1 = row.insertCell() cell1.style.display = 'none' cell1.innerHTML = '<p>test</p>' const res = parseHtml(doc, table, dom.window) assert(res, 'Should have result') assert(res.head.length === 0, 'Should have no head cells') assert(res.body.length === 1, 'Should have one body cell') assert(res.foot.length === 0, 'Should have no foot cells') }) it('empty table', () => { const doc = new DocHandler(new jsPDF()) const table = dom.window.document.createElement('table') const res = parseHtml(doc, table, dom.window) assert(res, 'Should have result') assert(res.head.length === 0, 'Should have no head cells') assert(res.body.length === 0, 'Should have no body cells') assert(res.foot.length === 0, 'Should have no foot cells') }) it('autoTableHtmlToJson', () => { ;(global as any).window = dom.window ;(global as any).HTMLTableElement = dom.window.HTMLTableElement const table = dom.window.document.createElement('table') let body = table.createTBody() let brow = body.insertRow() brow.insertCell().textContent = 'body' brow.insertCell().textContent = 'body 2' let head = table.createTHead() let hrow = head.insertRow() hrow.insertCell().textContent = 'head' hrow.insertCell().outerHTML = '<th>th</th>' const doc = new jsPDF() const res = doc.autoTableHtmlToJson(table) assert.equal(res.data[0].length, 2, 'Should have body cell') assert.equal(res.columns.length, 2, 'Should have columns cell') assert.equal(res.data[0][0].content, 'body', 'Should have body content') assert.equal(res.columns[0], 'head', 'Should have head content') }) })
uzelac92/jsPDF-AutoTable
src/common.ts
<gh_stars>1000+ import { DocHandler } from './documentHandler' import { Pos, Table } from './models' import { Color, MarginPaddingInput, Styles } from './config' type Text = string | string[] export function getStringWidth( text: Text, styles: Partial<Styles>, doc: DocHandler ) { doc.applyStyles(styles, true) const textArr: string[] = Array.isArray(text) ? text : [text] const widestLineWidth = textArr .map((text) => doc.getTextWidth(text)) .reduce((a, b) => Math.max(a, b), 0) return widestLineWidth } export function addTableBorder( doc: DocHandler, table: Table, startPos: Pos, cursor: Pos ) { const lineWidth = table.settings.tableLineWidth const lineColor = table.settings.tableLineColor doc.applyStyles({ lineWidth, lineColor }) const fillStyle = getFillStyle(lineWidth, false) if (fillStyle) { doc.rect( startPos.x, startPos.y, table.getWidth(doc.pageSize().width), cursor.y - startPos.y, fillStyle ) } } export function getFillStyle(lineWidth: number, fillColor: Color) { const drawLine = lineWidth > 0 const drawBackground = fillColor || fillColor === 0 if (drawLine && drawBackground) { return 'DF' // Fill then stroke } else if (drawLine) { return 'S' // Only stroke (transparent background) } else if (drawBackground) { return 'F' // Only fill, no stroke } else { return null } } export type MarginPadding = { top: number right: number bottom: number left: number } export function parseSpacing( value: MarginPaddingInput | undefined, defaultValue: number ): MarginPadding { value = value || defaultValue if (Array.isArray(value)) { if (value.length >= 4) { return { top: value[0], right: value[1], bottom: value[2], left: value[3], } } else if (value.length === 3) { return { top: value[0], right: value[1], bottom: value[2], left: value[1], } } else if (value.length === 2) { return { top: value[0], right: value[1], bottom: value[0], left: value[1], } } else if (value.length === 1) { value = value[0] } else { value = defaultValue } } if (typeof value === 'object') { if (typeof value.vertical === 'number') { value.top = value.vertical value.bottom = value.vertical } if (typeof value.horizontal === 'number') { value.right = value.horizontal value.left = value.horizontal } return { left: value.left ?? defaultValue, top: value.top ?? defaultValue, right: value.right ?? defaultValue, bottom: value.bottom ?? defaultValue, } } if (typeof value !== 'number') { value = defaultValue } return { top: value, right: value, bottom: value, left: value } }
uzelac92/jsPDF-AutoTable
src/autoTableText.ts
<reponame>uzelac92/jsPDF-AutoTable<gh_stars>1000+ import { jsPDFDocument } from './documentHandler' /** * Improved text function with halign and valign support * Inspiration from: http://stackoverflow.com/questions/28327510/align-text-right-using-jspdf/28433113#28433113 */ export default function ( text: string | string[], x: number, y: number, styles: TextStyles, doc: jsPDFDocument ) { styles = styles || {} const FONT_ROW_RATIO = 1.15 const k = doc.internal.scaleFactor const fontSize = doc.internal.getFontSize() / k const splitRegex = /\r\n|\r|\n/g let splitText: string | string[] = '' let lineCount = 1 if ( styles.valign === 'middle' || styles.valign === 'bottom' || styles.halign === 'center' || styles.halign === 'right' ) { splitText = typeof text === 'string' ? text.split(splitRegex) : text lineCount = splitText.length || 1 } // Align the top y += fontSize * (2 - FONT_ROW_RATIO) if (styles.valign === 'middle') y -= (lineCount / 2) * fontSize * FONT_ROW_RATIO else if (styles.valign === 'bottom') y -= lineCount * fontSize * FONT_ROW_RATIO if (styles.halign === 'center' || styles.halign === 'right') { let alignSize = fontSize if (styles.halign === 'center') alignSize *= 0.5 if (splitText && lineCount >= 1) { for (let iLine = 0; iLine < splitText.length; iLine++) { doc.text( splitText[iLine], x - doc.getStringUnitWidth(splitText[iLine]) * alignSize, y ) y += fontSize * FONT_ROW_RATIO } return doc } x -= doc.getStringUnitWidth(text) * alignSize } if (styles.halign === 'justify') { doc.text(text, x, y, { maxWidth: styles.maxWidth || 100, align: 'justify', }) } else { doc.text(text, x, y) } return doc } export interface TextStyles { valign?: 'middle' | 'bottom' | 'top' halign?: 'justify' | 'center' | 'right' | 'left' maxWidth?: number }
uzelac92/jsPDF-AutoTable
src/polyfills.ts
<reponame>uzelac92/jsPDF-AutoTable /* eslint-disable @typescript-eslint/no-unused-vars */ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign export function assign<T, U, V, W, X>( target: T, s: U, s1?: V, s2?: W, s3?: X ): T & U & V & W & X { if (target == null) { throw new TypeError('Cannot convert undefined or null to object') } const to = Object(target) for (let index = 1; index < arguments.length; index++) { // eslint-disable-next-line prefer-rest-params const nextSource = arguments[index] if (nextSource != null) { // Skip over if undefined or null for (const nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey] } } } } return to }
uzelac92/jsPDF-AutoTable
test/testEllipsize.ts
<reponame>uzelac92/jsPDF-AutoTable<gh_stars>1000+ const assert = require('assert') import { ellipsize } from '../src/widthCalculator' import { DocHandler } from '../src/documentHandler' import { loadJspdf } from './common' const jsPDF = loadJspdf() describe('ellipsize', () => { it('ellipsize string', () => { const doc = new DocHandler(new jsPDF()) const text = ['lorem ipsum'] let str = ellipsize(text, 0, {}, doc, '...')[0] assert(str.length < 5, `Should be reduced in length`) assert(str.endsWith('...'), `Should end with ...`) str = ellipsize(text, 100, {}, doc, '...')[0] assert.equal(str.length, 11, `Should not be reduced`) }) it('ellipsize string array', () => { const doc = new DocHandler(new jsPDF()) const text = ['lorem ipsum', 'lorem ipsum ipsum'] let str = ellipsize(text, 0, {}, doc, '...') assert(str[0].length < 5, `Should be reduced in length`) assert(str[1].length < 5, `Should be reduced in length`) assert(str[0].endsWith('...'), `Should end with ...`) assert(str[1].endsWith('...'), `Should end with ...`) str = ellipsize(text, 100, {}, doc, '...') assert.equal(str[0].length, 11, `Should not be reduced`) assert.equal(str[1].length, 17, `Should not be reduced`) }) })
uzelac92/jsPDF-AutoTable
src/inputValidator.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ import { DocHandler } from './documentHandler' import { HookData } from './HookData' import { UserOptions } from './config' export default function ( doc: DocHandler, global: UserOptions, document: UserOptions, current: UserOptions ) { for (const options of [global, document, current] as any) { if (options && typeof options !== 'object') { console.error( 'The options parameter should be of type object, is: ' + typeof options ) } if (typeof options.extendWidth !== 'undefined') { options.tableWidth = options.extendWidth ? 'auto' : 'wrap' console.error( 'Use of deprecated option: extendWidth, use tableWidth instead.' ) } if (typeof options.margins !== 'undefined') { if (typeof options.margin === 'undefined') options.margin = options.margins console.error('Use of deprecated option: margins, use margin instead.') } if (options.startY && typeof options.startY !== 'number') { console.error('Invalid value for startY option', options.startY) delete options.startY } if ( !options.didDrawPage && (options.afterPageContent || options.beforePageContent || options.afterPageAdd) ) { console.error( 'The afterPageContent, beforePageContent and afterPageAdd hooks are deprecated. Use didDrawPage instead' ) options.didDrawPage = function (data: HookData) { doc.applyStyles(doc.userStyles) if (options.beforePageContent) options.beforePageContent(data) doc.applyStyles(doc.userStyles) if (options.afterPageContent) options.afterPageContent(data) doc.applyStyles(doc.userStyles) if (options.afterPageAdd && data.pageNumber > 1) { ;(data as any).afterPageAdd(data) } doc.applyStyles(doc.userStyles) } } ;[ 'createdHeaderCell', 'drawHeaderRow', 'drawRow', 'drawHeaderCell', ].forEach((name) => { if (options[name]) { console.error( `The "${name}" hook has changed in version 3.0, check the changelog for how to migrate.` ) } }) ;[ ['showFoot', 'showFooter'], ['showHead', 'showHeader'], ['didDrawPage', 'addPageContent'], ['didParseCell', 'createdCell'], ['headStyles', 'headerStyles'], ].forEach(([current, deprecated]) => { if (options[deprecated]) { console.error( `Use of deprecated option ${deprecated}. Use ${current} instead` ) options[current] = options[deprecated] } }) ;[ ['padding', 'cellPadding'], ['lineHeight', 'rowHeight'], 'fontSize', 'overflow', ].forEach(function (o) { const deprecatedOption = typeof o === 'string' ? o : o[0] const style = typeof o === 'string' ? o : o[1] if (typeof options[deprecatedOption] !== 'undefined') { if (typeof options.styles[style] === 'undefined') { options.styles[style] = options[deprecatedOption] } console.error( 'Use of deprecated option: ' + deprecatedOption + ', use the style ' + style + ' instead.' ) } }) for (const styleProp of [ 'styles', 'bodyStyles', 'headStyles', 'footStyles', ]) { checkStyles(options[styleProp] || {}) } const columnStyles = options['columnStyles'] || {} for (const key of Object.keys(columnStyles)) { checkStyles(columnStyles[key] || {}) } } } function checkStyles(styles: any) { if (styles.rowHeight) { console.error( 'Use of deprecated style rowHeight. It is renamed to minCellHeight.' ) if (!styles.minCellHeight) { styles.minCellHeight = styles.rowHeight } } else if (styles.columnWidth) { console.error( 'Use of deprecated style columnWidth. It is renamed to cellWidth.' ) if (!styles.cellWidth) { styles.cellWidth = styles.columnWidth } } }
uzelac92/jsPDF-AutoTable
examples/typescript/index.ts
import jsPDF from 'jspdf' import autoTable from 'jspdf-autotable' const head = [['ID', 'Country', 'Index', 'Capital']] const data = [ [1, 'Finland', 7.632, 'Helsinki'], [2, 'Norway', 7.594, 'Oslo'], [3, 'Denmark', 7.555, 'Copenhagen'], [4, 'Iceland', 7.495, 'Reykjavík'], [5, 'Switzerland', 7.487, 'Bern'], [9, 'Sweden', 7.314, 'Stockholm'], [73, 'Belarus', 5.483, 'Minsk'], ] const doc = new jsPDF() autoTable(doc, { head: head, body: data, didDrawCell: (data) => { console.log(data.column.index) }, }) doc.save('table.pdf')
uzelac92/jsPDF-AutoTable
src/inputParser.ts
<reponame>uzelac92/jsPDF-AutoTable import { UserOptions, ColumnInput, RowInput, CellInput } from './config' import { parseHtml } from './htmlParser' import { assign } from './polyfills' import { parseSpacing } from './common' import { DocHandler, jsPDFDocument } from './documentHandler' import validateOptions from './inputValidator' import { StyleProp, StylesProps, CellHook, PageHook, Settings, HookProps, } from './models' interface ContentInput { body: RowInput[] head: RowInput[] foot: RowInput[] columns: ColumnInput[] } export interface TableInput { id: string | number | undefined settings: Settings styles: StylesProps hooks: HookProps content: ContentInput } export function parseInput(d: jsPDFDocument, current: UserOptions): TableInput { const doc = new DocHandler(d) const document = doc.getDocumentOptions() const global = doc.getGlobalOptions() validateOptions(doc, global, document, current) const options = assign({}, global, document, current) let win: Window | undefined if (typeof window !== 'undefined') { win = window } const styles = parseStyles(global, document, current) const hooks = parseHooks(global, document, current) const settings = parseSettings(doc, options) const content = parseContent(doc, options, win) return { id: current.tableId, content, hooks, styles, settings, } } function parseStyles( gInput: UserOptions, dInput: UserOptions, cInput: UserOptions ) { const styleOptions: StylesProps = { styles: {}, headStyles: {}, bodyStyles: {}, footStyles: {}, alternateRowStyles: {}, columnStyles: {}, } for (const prop of Object.keys(styleOptions) as StyleProp[]) { if (prop === 'columnStyles') { const global = gInput[prop] const document = dInput[prop] const current = cInput[prop] styleOptions.columnStyles = assign({}, global, document, current) } else { const allOptions = [gInput, dInput, cInput] const styles = allOptions.map((opts) => opts[prop] || {}) styleOptions[prop] = assign({}, styles[0], styles[1], styles[2]) } } return styleOptions } function parseHooks( global: UserOptions, document: UserOptions, current: UserOptions ) { const allOptions = [global, document, current] const result = { didParseCell: [] as CellHook[], willDrawCell: [] as CellHook[], didDrawCell: [] as CellHook[], didDrawPage: [] as PageHook[], } for (const options of allOptions) { if (options.didParseCell) result.didParseCell.push(options.didParseCell) if (options.willDrawCell) result.willDrawCell.push(options.willDrawCell) if (options.didDrawCell) result.didDrawCell.push(options.didDrawCell) if (options.didDrawPage) result.didDrawPage.push(options.didDrawPage) } return result } function parseSettings(doc: DocHandler, options: UserOptions): Settings { const margin = parseSpacing(options.margin, 40 / doc.scaleFactor()) const startY = getStartY(doc, options.startY) ?? margin.top let showFoot: 'everyPage' | 'lastPage' | 'never' if (options.showFoot === true) { showFoot = 'everyPage' } else if (options.showFoot === false) { showFoot = 'never' } else { showFoot = options.showFoot ?? 'everyPage' } let showHead: 'everyPage' | 'firstPage' | 'never' if (options.showHead === true) { showHead = 'everyPage' } else if (options.showHead === false) { showHead = 'never' } else { showHead = options.showHead ?? 'everyPage' } const useCss = options.useCss ?? false const theme = options.theme || (useCss ? 'plain' : 'striped') const horizontalPageBreak: boolean = options.horizontalPageBreak ? true : false const horizontalPageBreakRepeat = options.horizontalPageBreakRepeat ?? null return { includeHiddenHtml: options.includeHiddenHtml ?? false, useCss, theme, startY, margin, pageBreak: options.pageBreak ?? 'auto', rowPageBreak: options.rowPageBreak ?? 'auto', tableWidth: options.tableWidth ?? 'auto', showHead, showFoot, tableLineWidth: options.tableLineWidth ?? 0, tableLineColor: options.tableLineColor ?? 200, horizontalPageBreak, horizontalPageBreakRepeat, } } function getStartY(doc: DocHandler, userStartY: number | false | undefined) { const previous = doc.getLastAutoTable() const sf = doc.scaleFactor() const currentPage = doc.pageNumber() let isSamePageAsPreviousTable = false if (previous && previous.startPageNumber) { const endingPage = previous.startPageNumber + previous.pageNumber - 1 isSamePageAsPreviousTable = endingPage === currentPage } if (typeof userStartY === 'number') { return userStartY } else if (userStartY == null || userStartY === false) { if (isSamePageAsPreviousTable && previous?.finalY != null) { // Some users had issues with overlapping tables when they used multiple // tables without setting startY so setting it here to a sensible default. return previous.finalY + 20 / sf } } return null } function parseContent(doc: DocHandler, options: UserOptions, window?: Window) { let head = options.head || [] let body = options.body || [] let foot = options.foot || [] if (options.html) { const hidden = options.includeHiddenHtml if (window) { const htmlContent = parseHtml(doc, options.html, window, hidden, options.useCss) || {} head = htmlContent.head || head body = htmlContent.body || head foot = htmlContent.foot || head } else { console.error('Cannot parse html in non browser environment') } } const columns = options.columns || parseColumns(head, body, foot) return { columns, head, body, foot, } } function parseColumns(head: RowInput[], body: RowInput[], foot: RowInput[]) { const firstRow: RowInput = head[0] || body[0] || foot[0] || [] const result: ColumnInput[] = [] Object.keys(firstRow) .filter((key) => key !== '_element') .forEach((key) => { let colSpan = 1 let input: CellInput if (Array.isArray(firstRow)) { input = firstRow[parseInt(key)] } else { input = firstRow[key] } if (typeof input === 'object' && !Array.isArray(input)) { colSpan = input?.colSpan || 1 } for (let i = 0; i < colSpan; i++) { let id if (Array.isArray(firstRow)) { id = result.length } else { id = key + (i > 0 ? `_${i}` : '') } const rowResult: ColumnInput = { dataKey: id } result.push(rowResult) } }) return result }
uzelac92/jsPDF-AutoTable
test/testInputParser.ts
import { loadJspdf } from './common' import { createTable } from '../src/tableCalculator' import { parseInput } from '../src/inputParser' const assert = require('assert') const jsPDF = loadJspdf() describe('input parser', () => { it('non browser', () => { const d = new jsPDF() const input = parseInput(d, { html: '#table' }) const res = createTable(d, input) assert(res.body.length === 0, 'Should have empty result') }) it('array input', () => { const d = new jsPDF() const input = parseInput(d, { head: [['test', 'test']], body: [ ['test', 'test'], ['test', 'test'], ], }) const table = createTable(d, input) assert(table, 'Has table') assert.equal(table.head.length, 1) assert.equal(table.body.length, 2) assert.equal(table.foot.length, 0) assert.equal(Object.keys(table.head[0].cells).length, 2) assert.equal(table.head[0].cells[0].text, 'test') assert(table.head[0].cells[0].minWidth > 0) }) it('minReadableWidth', () => { const d = new jsPDF() const input = parseInput(d, { head: [['aaaa', 'aa', 'aaa']], body: [['a', 'a', 'a']], }) const table = createTable(d, input) const cols = table.columns assert(table.body[0].cells[0].minReadableWidth > 0) assert(cols[0].minReadableWidth > cols[1].minReadableWidth) assert(cols[1].minReadableWidth < cols[2].minReadableWidth) }) it('object input', () => { const d = new jsPDF() const input = parseInput(d, { head: [ { id: 'ID', name: 'Name', email: 'Email', city: 'City', expenses: 'Expenses', }, ], }) const table = createTable(d, input) assert.equal(table.head[0].cells['id'].text, 'ID') assert.equal(table.head[0].cells[0].text, 'ID') }) it('object input', () => { const d = new jsPDF() const input = parseInput(d, { head: [[{ content: 'test' }, 'test 2']], body: [ ['body', 'test'], ['test', 'test'], ], }) const table = createTable(d, input) assert.equal(table.head[0].cells[0].text, 'test') assert.equal(table.head[0].cells[1].text, 'test 2') assert.equal(table.body[0].cells[0].text, 'body') }) it('rowspan input', () => { const d = new jsPDF() const input = parseInput(d, { body: [[{ content: 'test', rowSpan: 2 }, 'one'], ['two']], }) const table = createTable(d, input) assert.equal(table.body[0].cells[0].text, 'test') assert.equal(table.body[1].cells[0], null) assert.equal(table.body[0].cells[1].text, 'one') assert.equal(table.body[1].cells[1].text, 'two') }) it('rowspan input two', () => { const d = new jsPDF() const input = parseInput(d, { body: [['one', { content: 'test', rowSpan: 2 }], ['two']], }) const table = createTable(d, input) assert.equal(table.body[0].cells[0].text, 'one') assert.equal(table.body[0].cells[1].text, 'test') assert.equal(table.body[1].cells[0].text, 'two') assert.equal(table.body[1].cells[1], null) }) })
uzelac92/jsPDF-AutoTable
test/testRunning.ts
import { loadJspdf } from './common' const jsPDF = loadJspdf() import autoTable, { autoTable as autoTableType } from '../src/main' const assert = require('assert') describe('runner', () => { it('prototype', () => { const doc = new jsPDF() doc.autoTable({ body: [['cell']] }) assert(true) }) it('export', () => { const doc = new jsPDF() autoTable(doc, { body: [['cell']] }) assert(true) }) it('nodejs', () => { (global as any).window = {} const jsPDFNode = require('jspdf/dist/jspdf.node').jsPDF delete (global as any).window const doc = new jsPDFNode() autoTable(doc, { body: [['cell']] }) assert(true) }) it('add page in hook', () => { const doc = new jsPDF() autoTable(doc, { body: [['test']], willDrawCell: () => { doc.addPage() }, }) assert.equal(doc.internal.getCurrentPageInfo().pageNumber, 2) }) it('previous typing', () => { const doc = new jsPDF() ;((doc as any).autoTable as autoTableType)({ body: [['test']], }) assert(true) }) })
beenotung/stencil-virtual-scroll
src/components/virtual-scroll-list/virtual-scroll-list.tsx
import { Watch, Element, State, Prop, Component, h } from '@stencil/core'; import { VNode, ChildType } from '@stencil/core/internal/index'; /** * the parent should the style of this component, including * - width * - height * - display * */ @Component({ tag: 'virtual-scroll-list', styleUrl: 'virtual-scroll-list.scss', scoped: true, }) export class VirtualScrollList { @Element() host!: HTMLElement; @State() container?: HTMLElement; @Prop({ mutable: true }) itemCount!: number; @Prop() renderItem!: (i: number) => ChildType | Promise<ChildType> | ChildType[] | Promise<ChildType[]> | Promise<ChildType>[]; @Prop({ mutable: true }) itemWidth!: number; @Prop({ mutable: true }) estimatedItemHeight!: number; @Prop({ mutable: true }) itemHeights!: number[]; @State() scrollTop: number = 0; @State() totalHeight = 1; @Watch('itemHeights') @Watch('estimatedItemHeight') updateTotalHeight() { let totalHeight = 0; for (let i = 0; i < this.itemCount; i++) { totalHeight += this.itemHeights[i] || this.estimatedItemHeight; } this.totalHeight = totalHeight; } scrollListener = (_ev: Event) => { this.scrollTop = this.host.scrollTop; }; connectedCallback() { this.host.addEventListener('scroll', this.scrollListener); this.updateTotalHeight(); } disconnectedCallback() { this.host.removeEventListener('scroll', this.scrollListener); } getFirstRowInView(scrollTop: number) { let accHeight = 0; let i = 0; let n = this.itemCount; let heights = this.itemHeights; let estimatedItemHeight = this.estimatedItemHeight; for (; i < n; i++) { let itemHeight = heights[i] || estimatedItemHeight; if (scrollTop >= accHeight + itemHeight) { break; } accHeight += itemHeight; } return { firstRow: i, accHeight }; } render() { let W = this.host.clientWidth; let H = this.host.clientHeight; let heights = this.itemHeights; let estimatedItemHeight = this.estimatedItemHeight; let N = this.itemCount; let scrollTop = this.scrollTop; let children: VNode[] = []; let accHeight = 0; for (let i = 0; i < N; i++) { let itemHeight = heights[i] || estimatedItemHeight; if (scrollTop > accHeight + itemHeight) { accHeight += itemHeight; continue; // this item is above the viewport } if (scrollTop + H < accHeight) { break; // this item is below the viewport } let x = 0; let y = accHeight; children.push(<div class='item' style={{ transform: `translate(${x}px,${y}px)`, width: this.itemWidth + 'px', height: itemHeight + 'px', }}> {this.renderItem(i)} </div>); accHeight += itemHeight; } return [ <div // to capture scroll action class="scroller" style={{ height: this.totalHeight + 'px', width: W + 'px', }} />, <div // to display payload class="item-container" style={{ // paddingTop: this.scrollTop - offsetTop + 'px', height: this.totalHeight + 'px', left: -W + 'px', }} ref={el => (this.container = el)} > {children} </div>, ]; } }
beenotung/stencil-virtual-scroll
src/components/virtual-scroll/virtual-scroll.tsx
<filename>src/components/virtual-scroll/virtual-scroll.tsx import { Watch, Element, State, Prop, Component, h, VNode } from '@stencil/core'; import { ChildType } from '@stencil/core/internal'; /** * the parent should the style of this component, including * - width * - height * - display * */ @Component({ tag: 'virtual-scroll', styleUrl: 'virtual-scroll.scss', scoped: true, }) export class VirtualScroll { @Element() host!: HTMLElement; @State() container?: HTMLElement; @Prop({ mutable: true }) tick?: any; @Prop({ mutable: true }) itemCount!: number; @Prop() renderItem!: (i: number) => ChildType | Promise<ChildType> | ChildType[] | Promise<ChildType[]> | Promise<ChildType>[]; @Prop({ mutable: true }) itemWidth?: number; @Prop({ mutable: true }) itemHeight?: number; @Prop() autoDetectSize?: boolean; @Prop() sameSize?: boolean; @State() detectedSize = false; @State() scrollTop: number = 0; scrollListener = (_ev: Event) => { this.scrollTop = this.host.scrollTop; }; @Watch('itemCount') @Watch('renderItem') @Watch('itemWidth') @Watch('itemHeight') handlePropUpdate() { this.detectedSize = false; } connectedCallback() { this.host.addEventListener('scroll', this.scrollListener); } disconnectedCallback() { this.host.removeEventListener('scroll', this.scrollListener); } renderMeasure() { requestAnimationFrame(() => (this.tick = {})); return <div ref={el => (this.container = el)}>{this.renderItem(0)}</div>; } getItemDimension(): { itemWidth: number; itemHeight: number } | undefined { let itemWidth = this.itemWidth; let itemHeight = this.itemHeight; if (itemWidth && itemHeight) { return { itemWidth, itemHeight }; } // obtain dimension from the dom if (!this.container) { return; } if (this.sameSize) { // obtain dimension from the first child let child = this.container.firstElementChild; if (!child) { return; } itemWidth = child.clientWidth; itemHeight = child.clientHeight; } else { // obtain max dimension from all children itemWidth = 0; itemHeight = 0; this.container.childNodes.forEach(child => { if (child instanceof HTMLElement) { itemWidth = Math.max(itemWidth!, child.clientWidth); itemHeight = Math.max(itemHeight!, child.clientHeight); } }); } if (itemWidth && itemHeight) { if (this.autoDetectSize && !this.detectedSize) { requestAnimationFrame(() => { this.detectedSize = true; }); } return { itemWidth, itemHeight }; } // no children or child size is not establish yet return; } render() { let itemDimension = this.getItemDimension(); if (!itemDimension) { return this.renderMeasure(); } let { itemWidth, itemHeight } = itemDimension; let scrollTop = this.scrollTop; let W = this.host.clientWidth; let H = this.host.clientHeight; let N = this.itemCount; let nCol = Math.floor(W / itemWidth); // total number of row for all items, for scrollbar height let totalNRow = Math.ceil(N / nCol); let nRowBefore = Math.floor(scrollTop / itemHeight); // amount of non visible heights of first row above the viewport let offsetTop = scrollTop % itemHeight; // amount of rows in viewport let nRow = Math.ceil((H + offsetTop) / itemHeight); let children: VNode[] = []; main: for (let iRow = nRowBefore; iRow < nRowBefore + nRow; iRow++) { for (let iCol = 0; iCol < nCol; iCol++) { let i = iRow * nCol + iCol; if (i >= N) break main; let x = itemWidth * iCol; let y = itemHeight * iRow; children.push(<div class='item' style={{ transform: `translate(${x}px,${y}px)`, width: itemWidth + 'px', height: itemHeight + 'px', }}> {this.renderItem(i)} </div>); } } return [ <div // to capture scroll action class="scroller" style={{ height: totalNRow * itemHeight + 'px', width: W + 'px', }} />, <div // to display payload class="item-container" style={{ height: totalNRow * itemHeight + 'px', left: -W + 'px', }} ref={el => (this.container = el)} > {children} </div>, ]; } }
beenotung/stencil-virtual-scroll
src/components.d.ts
/* eslint-disable */ /* tslint:disable */ /** * This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import { HTMLStencilElement, JSXBase } from "@stencil/core/internal"; import { ChildType } from "@stencil/core/internal"; import { ChildType as ChildType1 } from "@stencil/core/internal/index"; export namespace Components { interface StencilVirtualScrollDemo { } interface VirtualScroll { "autoDetectSize"?: boolean; "itemCount": number; "itemHeight"?: number; "itemWidth"?: number; "renderItem": (i: number) => ChildType | Promise<ChildType> | ChildType[] | Promise<ChildType[]> | Promise<ChildType>[]; "sameSize"?: boolean; "tick"?: any; } interface VirtualScrollDemo { } interface VirtualScrollList { "estimatedItemHeight": number; "itemCount": number; "itemHeights": number[]; "itemWidth": number; "renderItem": (i: number) => ChildType | Promise<ChildType> | ChildType[] | Promise<ChildType[]> | Promise<ChildType>[]; } interface VirtualScrollListDemo { } } declare global { interface HTMLStencilVirtualScrollDemoElement extends Components.StencilVirtualScrollDemo, HTMLStencilElement { } var HTMLStencilVirtualScrollDemoElement: { prototype: HTMLStencilVirtualScrollDemoElement; new (): HTMLStencilVirtualScrollDemoElement; }; interface HTMLVirtualScrollElement extends Components.VirtualScroll, HTMLStencilElement { } var HTMLVirtualScrollElement: { prototype: HTMLVirtualScrollElement; new (): HTMLVirtualScrollElement; }; interface HTMLVirtualScrollDemoElement extends Components.VirtualScrollDemo, HTMLStencilElement { } var HTMLVirtualScrollDemoElement: { prototype: HTMLVirtualScrollDemoElement; new (): HTMLVirtualScrollDemoElement; }; interface HTMLVirtualScrollListElement extends Components.VirtualScrollList, HTMLStencilElement { } var HTMLVirtualScrollListElement: { prototype: HTMLVirtualScrollListElement; new (): HTMLVirtualScrollListElement; }; interface HTMLVirtualScrollListDemoElement extends Components.VirtualScrollListDemo, HTMLStencilElement { } var HTMLVirtualScrollListDemoElement: { prototype: HTMLVirtualScrollListDemoElement; new (): HTMLVirtualScrollListDemoElement; }; interface HTMLElementTagNameMap { "stencil-virtual-scroll-demo": HTMLStencilVirtualScrollDemoElement; "virtual-scroll": HTMLVirtualScrollElement; "virtual-scroll-demo": HTMLVirtualScrollDemoElement; "virtual-scroll-list": HTMLVirtualScrollListElement; "virtual-scroll-list-demo": HTMLVirtualScrollListDemoElement; } } declare namespace LocalJSX { interface StencilVirtualScrollDemo { } interface VirtualScroll { "autoDetectSize"?: boolean; "itemCount": number; "itemHeight"?: number; "itemWidth"?: number; "renderItem": (i: number) => ChildType | Promise<ChildType> | ChildType[] | Promise<ChildType[]> | Promise<ChildType>[]; "sameSize"?: boolean; "tick"?: any; } interface VirtualScrollDemo { } interface VirtualScrollList { "estimatedItemHeight": number; "itemCount": number; "itemHeights": number[]; "itemWidth": number; "renderItem": (i: number) => ChildType | Promise<ChildType> | ChildType[] | Promise<ChildType[]> | Promise<ChildType>[]; } interface VirtualScrollListDemo { } interface IntrinsicElements { "stencil-virtual-scroll-demo": StencilVirtualScrollDemo; "virtual-scroll": VirtualScroll; "virtual-scroll-demo": VirtualScrollDemo; "virtual-scroll-list": VirtualScrollList; "virtual-scroll-list-demo": VirtualScrollListDemo; } } export { LocalJSX as JSX }; declare module "@stencil/core" { export namespace JSX { interface IntrinsicElements { "stencil-virtual-scroll-demo": LocalJSX.StencilVirtualScrollDemo & JSXBase.HTMLAttributes<HTMLStencilVirtualScrollDemoElement>; "virtual-scroll": LocalJSX.VirtualScroll & JSXBase.HTMLAttributes<HTMLVirtualScrollElement>; "virtual-scroll-demo": LocalJSX.VirtualScrollDemo & JSXBase.HTMLAttributes<HTMLVirtualScrollDemoElement>; "virtual-scroll-list": LocalJSX.VirtualScrollList & JSXBase.HTMLAttributes<HTMLVirtualScrollListElement>; "virtual-scroll-list-demo": LocalJSX.VirtualScrollListDemo & JSXBase.HTMLAttributes<HTMLVirtualScrollListDemoElement>; } } }
beenotung/stencil-virtual-scroll
src/components/stencil-virtual-scroll-demo/stencil-virtual-scroll-demo.tsx
<gh_stars>1-10 import { Component, Host, h, State } from '@stencil/core'; @Component({ tag: 'stencil-virtual-scroll-demo', styleUrl: 'stencil-virtual-scroll-demo.css', shadow: true, }) export class StencilVirtualScrollDemo { @State() mode = 'none'; renderItem(props: { name: string, desc: string }) { return <p> <b>{props.name}</b> <span> ({props.desc})</span> <br /> {this.mode === props.name ? <button onClick={() => this.mode = 'none'}>Hide Demo</button> : <button onClick={() => this.mode = props.name}>Show Demo</button> } </p>; } renderDemo() { if (this.mode === 'virtual-scroll') { return <div class='demo'> <virtual-scroll-demo /> </div>; } if (this.mode === 'virtual-scroll-list') { return <div class='demo'> <virtual-scroll-list-demo /> </div>; } } render() { return ( <Host> <h1> stencil-virtual-scroll Demo </h1> {this.renderItem({ name: 'virtual-scroll', desc: 'fixed-size cells in grid view' })} {this.renderItem({ name: 'virtual-scroll-list', desc: 'vary-height items in list view' })} {this.renderDemo()} </Host> ); } }
beenotung/stencil-virtual-scroll
src/components/virtual-scroll-list-demo/virtual-scroll-list-demo.tsx
<gh_stars>1-10 import { Component, h, Host } from '@stencil/core'; const N = 100; const width = 450; const height = 50; const heights = Array(N).fill(height) .map(height => Math.floor(height * (1 + Math.random() * 2))); const colors = [ 'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple', ]; @Component({ tag: 'virtual-scroll-list-demo', styleUrl: 'virtual-scroll-list-demo.css', scoped: true, }) export class VirtualScrollListDemo { renderItem(i: number) { let color = colors[i % colors.length]; let height = heights[i]; return <div style={{ width: width + 'px', height: height + 'px', outline: '1px solid ' + color, position: 'relative', }}> <div style={{ position: 'absolute', top: '0', left: '0', }}>{i}</div> <div style={{ position: 'absolute', top: '0', right: '0', }}>{i}</div> <div style={{ position: 'absolute', bottom: '0', left: '0', }}>{i}</div> <div style={{ position: 'absolute', bottom: '0', right: '0', }}>{i}</div> </div>; } render() { return ( <Host> before <virtual-scroll-list itemCount={N} renderItem={i => this.renderItem(i)} itemWidth={width} itemHeights={heights} estimatedItemHeight={height} style={{ display: 'block', width: '100%', height: '450px', maxHeight: '80vh', outline: 'blue solid 1px', }} /> after </Host> ); } }