repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/user-login-model.ts
export interface OCOrganizationResponse { name?: string; username?: string; type?: string; email: string; customData?: any; } export class UserLoginModel { email: string; password: string; isChecked: boolean; } export interface OCNativeSignup { password: string; } export interface OCNativeCustomSignup extends OCNativeSignup { account: OCOrganizationResponse; organization: OCOrganizationResponse; } export interface OCNativeDefaultSignup extends OCNativeSignup { uname: string; email: string; company: string; password: string; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-rating/oc-rating.component.spec.ts
<reponame>mukesh-openchannel/angular-template-libraries import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcRatingComponent } from './oc-rating.component'; import { NgbModule, NgbRating } from '@ng-bootstrap/ng-bootstrap'; import { By } from '@angular/platform-browser'; import { MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcRatingComponent', () => { let component: OcRatingComponent; let fixture: ComponentFixture<OcRatingComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcRatingComponent, MockSvgIconComponent], imports: [NgbModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcRatingComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show rating and review data', () => { component.rating = 5; component.reviewCount = 10; component.label = 'reviews'; fixture.detectChanges(); const ratingInfo = fixture.debugElement.query(By.css('span')).nativeElement; expect(ratingInfo.textContent).toContain('5.0 (10 reviews)'); }); it('should render correct template depending on type', () => { component.type = 'single-star'; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('.oc-rating-single'))).toBeTruthy(); component.type = 'multi-star'; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('.oc-rating-multi'))).toBeTruthy(); }); it('should call onChange, when ngb-rating emits rateChange', () => { const newRating = 5; const onChangeFunc = jest.fn(); component.registerOnChange(onChangeFunc); component.type = 'multi-star'; fixture.detectChanges(); const ngbRatingDE = fixture.debugElement.query(By.directive(NgbRating)); ngbRatingDE.triggerEventHandler('rateChange', newRating); expect(onChangeFunc).toHaveBeenCalledWith(newRating); expect(component.rating).toBe(newRating); }); it('should not call onChange, when onRateChange called with rating < 0', () => { const oldRating = component.rating; const onChangeFunc = jest.fn(); component.registerOnChange(onChangeFunc); component.type = 'multi-star'; fixture.detectChanges(); component.onRateChange(-1); expect(onChangeFunc).not.toHaveBeenCalled(); expect(component.rating).toBe(oldRating); }); it('should call onTouched, when ngb-rating emits leave', () => { const onTouchedFunc = jest.fn(); component.registerOnTouched(onTouchedFunc); component.type = 'multi-star'; fixture.detectChanges(); const ngbRatingDE = fixture.debugElement.query(By.directive(NgbRating)); ngbRatingDE.triggerEventHandler('leave', {}); expect(onTouchedFunc).toHaveBeenCalled(); }); it('ngb-rating readonly property should depend on disabled component property', () => { component.type = 'multi-star'; fixture.detectChanges(); const ngbRating = fixture.debugElement.query(By.directive(NgbRating)).componentInstance; component.setDisabledState(false); fixture.detectChanges(); expect(ngbRating.readonly).toBeFalsy(); component.setDisabledState(true); fixture.detectChanges(); expect(ngbRating.readonly).toBeTruthy(); }); it('writeValue should set rating component property', () => { const newRating = 5; component.type = 'multi-star'; fixture.detectChanges(); const ngbRating = fixture.debugElement.query(By.directive(NgbRating)).componentInstance; component.writeValue(newRating); fixture.detectChanges(); expect(ngbRating.rate).toBe(newRating); }); it('should set labelClass to label', () => { const labelClass = 'custom-label-class'; component.labelClass = labelClass; component.type = 'single-star'; fixture.detectChanges(); const label = fixture.debugElement.query(By.css('.oc-rating-single__label')); expect(label.properties.className).toContain(labelClass); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/properties.model.ts
export interface OcPropertyModel { propertyId: string; value: any; }
mukesh-openchannel/angular-template-libraries
src/formComponent.stories.ts
<reponame>mukesh-openchannel/angular-template-libraries import { AppFormField, AppFormModel, DropdownAdditionalField, DropdownFormField, FileDetails, OcFormComponent, OcFormComponentsModule, FileUploaderService, } from '@openchannel/angular-common-components/src/lib/form-components'; import { moduleMetadata } from '@storybook/angular'; import { Observable, of } from 'rxjs'; import { EmbedVideoService } from 'ngx-embed-video'; import { HttpClientModule, HttpResponse, HttpUploadProgressEvent } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { storyMockProviderAppSearchService } from 'src/dropdown-multi-app.stories'; import { ERROR_MESSAGES_STORY_PROVIDER } from './utils.model'; class StubFileUploadDownloadService extends FileUploaderService { videoData: FileDetails = { uploadDate: 214213, fileId: 'fileId', name: 'test1.jpg', contentType: 'type', size: 123123, isPrivate: false, mimeCheck: 'PASSED', fileUrl: 'https://youtu.be/DGQwd1_dpuc', isError: false, fileUploadProgress: 100, virusScan: { started: 1457710762784, finished: 1457710769567, status: 'CLEAN', foundViruses: [], }, fileIconUrl: '', }; constructor() { super(); } fileUploadRequest( file: FormData, isPrivate: boolean, hash?: string[], ): Observable<HttpResponse<FileDetails> | HttpUploadProgressEvent> { return of(new HttpResponse({ body: this.videoData })); } fileDetailsRequest(fileId: string): Observable<FileDetails> { return of(this.videoData); } } class FileServiceStub extends FileUploaderService { constructor() { super(); } fileUploadRequest(file: FormData, isPrivate: boolean, hash?: string[]): Observable<any> { return new Observable(); } fileDetailsRequest(fileId: string): Observable<any> { return new Observable(); } } const modules = { imports: [OcFormComponentsModule, HttpClientModule, BrowserAnimationsModule], providers: [ EmbedVideoService, storyMockProviderAppSearchService, { provide: FileUploaderService, useClass: StubFileUploadDownloadService }, { provide: FileUploaderService, useClass: FileServiceStub }, ERROR_MESSAGES_STORY_PROVIDER, ], }; export default { title: 'Form Group Component [BEM]', component: OcFormComponent, decorators: [moduleMetadata(modules)], argTypes: { formSubmitted: { action: 'Form Data' }, formDataUpdated: { action: 'Form Data Updates' } }, }; const FormGroupComponent = (args: OcFormComponent) => ({ component: OcFormComponent, moduleMetadata: modules, props: args, }); export const FormWithTestData = FormGroupComponent.bind({}); FormWithTestData.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { id: 'name', label: 'name', description: 'test', defaultValue: null, type: 'text', required: null, attributes: { maxChars: 20, required: true, minChars: 10, }, options: null, fields: null, }, { id: 'role', label: 'role', description: '', defaultValue: 'user', type: 'dropdownList', required: null, attributes: { required: true }, options: ['admin', 'user', 'test'], fields: null, }, { id: 'aboutme', label: 'aboutme', description: '', defaultValue: null, type: 'richText', required: null, attributes: { maxChars: 150, required: null, minChars: 10, }, options: null, fields: null, }, { id: 'skills', label: 'skills', description: 'skills', defaultValue: ['angular'], type: 'tags', required: null, attributes: { minCount: 1, maxCount: 5, required: true, }, options: ['angular', 'react', 'react native', 'spring'], fields: null, }, ], }, }; export const FormWithRequiredOnly = FormGroupComponent.bind({}); FormWithRequiredOnly.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { id: 'name', label: 'name', description: 'test', defaultValue: null, type: 'text', required: null, attributes: { maxChars: null, required: true, minChars: null, }, options: null, fields: null, }, { id: 'role', label: 'role', description: '', defaultValue: null, type: 'dropdownList', required: null, attributes: { required: true }, options: ['admin', 'user', 'test'], fields: null, }, { id: 'aboutme', label: 'aboutme', description: '', defaultValue: null, type: 'richText', required: null, attributes: { maxChars: null, required: null, minChars: null, }, options: null, fields: null, }, { id: 'skills', label: 'skills', description: 'skills', defaultValue: ['angular'], type: 'tags', required: null, attributes: { minCount: null, maxCount: null, required: true, }, options: null, fields: null, }, ], }, showButton: false, }; export const FormWithNumberInput = FormGroupComponent.bind({}); FormWithNumberInput.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { max: 25, min: 5, required: null, }, category: 'CUSTOM', defaultValue: null, description: '', id: 'test-number', isOpen: false, isValid: true, label: 'Test number', placeholder: null, type: 'number', }, ], }, }; export const FormWithCheckboxComponent = FormGroupComponent.bind({}); FormWithCheckboxComponent.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, }, category: 'CUSTOM', defaultValue: true, description: 'Terms of service', id: 'test-checkbox', isOpen: false, isValid: true, label: 'Test Checkbox', placeholder: null, type: 'checkbox', }, ], }, }; export const FormWithEmailComponent = FormGroupComponent.bind({}); FormWithEmailComponent.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, }, category: 'CUSTOM', defaultValue: null, description: '', id: 'test-email', isOpen: false, isValid: true, deleteable: false, label: 'Test email', placeholder: 'enter email', type: 'emailAddress', }, ], }, }; export const FormWithUrlComponent = FormGroupComponent.bind({}); FormWithUrlComponent.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, }, category: 'CUSTOM', defaultValue: null, description: null, id: 'test-url-component', isOpen: false, isValid: true, deleteable: false, label: 'Test URL component', placeholder: 'Enter your link here..', type: 'websiteUrl', }, ], }, }; export const FormWithColorComponent = FormGroupComponent.bind({}); FormWithColorComponent.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, }, category: 'CUSTOM', defaultValue: null, description: null, id: 'test-color-component', isOpen: false, isValid: true, deleteable: false, label: 'Test Color Component', placeholder: 'Choose your color', type: 'color', }, ], }, }; export const FormWithBooleanTags = FormGroupComponent.bind({}); FormWithBooleanTags.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, maxCount: null, minCount: null, }, options: ['true', 'false'], category: 'CUSTOM', defaultValue: null, description: null, id: 'test-boolean-tags', isOpen: false, isValid: true, deleteable: false, label: 'Test Boolean tags', placeholder: null, type: 'booleanTags', }, ], }, }; export const FormWithNumberTags = FormGroupComponent.bind({}); FormWithNumberTags.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, maxCount: 2, minCount: 1, }, options: ['1', '3', '45'], category: 'CUSTOM', defaultValue: [], description: null, id: 'test-number-tags', isOpen: false, isValid: true, deleteable: false, label: 'Test number tags', placeholder: null, type: 'numberTags', }, ], }, }; export const FormWithDateAndDateTime = FormGroupComponent.bind({}); FormWithDateAndDateTime.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, }, category: 'CUSTOM', defaultValue: null, description: null, id: 'test-date-picker', isOpen: false, isValid: true, deleteable: false, label: 'Test Date picker', placeholder: null, type: 'date', }, { attributes: { required: true, }, category: 'CUSTOM', defaultValue: 1602489693553, description: null, id: 'test-datetime-picker', isOpen: false, isValid: true, deleteable: false, label: 'Test date-time picker', placeholder: null, type: 'datetime', }, ], }, }; export const FormWithVideoUrlComponent = FormGroupComponent.bind({}); FormWithVideoUrlComponent.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, }, category: 'CUSTOM', defaultValue: 'https://www.youtube.com/watch?v=DGQwd1_dpuc', description: null, id: 'test-video-url-comp', isOpen: false, isValid: true, deleteable: false, label: 'Test videoUrl component', placeholder: null, type: 'videoUrl', }, ], }, }; export const FormWithMultiSelect = FormGroupComponent.bind({}); FormWithMultiSelect.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, maxCount: 3, minCount: 2, }, options: ['One', 'Two', 'Three', 'Five'], category: 'CUSTOM', defaultValue: [], description: null, id: 'multi-select-test', isOpen: false, isValid: true, deleteable: false, label: 'Multi Select test', placeholder: null, type: 'multiselectList', }, ], }, }; export const FormWithMultiAppDropdown = FormGroupComponent.bind({}); FormWithMultiAppDropdown.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { required: true, maxCount: 3, minCount: 2, }, options: ['601ab171d0c0c60baf65433e', '601ab170d0c0c60baf654326'], category: 'CUSTOM', defaultValue: [], description: null, id: 'multi-app-dropdown', isOpen: false, isValid: true, deleteable: false, label: 'Multi App Dropdown', placeholder: null, type: 'multiApp', }, ], }, }; export const FormWithMultiCheckboxes = FormGroupComponent.bind({}); FormWithMultiCheckboxes.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { subType: 'checkbox', required: true, maxCount: 3, minCount: 2, }, options: ['aaa', 'bb'], category: 'CUSTOM', defaultValue: [], description: null, id: 'multi-checkbox', isOpen: false, isValid: true, deleteable: false, label: 'Multi checkboxes', placeholder: null, type: 'multiselectList', }, ], }, }; export const FormWithDynamicFieldArray = FormGroupComponent.bind({}); FormWithDynamicFieldArray.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { maxCount: 3, minCount: 1, ordering: 'append', required: true, rowLabel: 'field1', }, required: null, rowLabel: null, category: 'CUSTOM', defaultValue: null, description: '', id: 'test-dynamic-field-array', isOpen: false, isValid: true, label: 'Test Dynamic field array', placeholder: null, fields: [ { attributes: { maxChars: null, minChars: null, required: null, }, category: 'CUSTOM', defaultValue: null, description: 'some description', id: 'field1', isOpen: false, isValid: true, label: 'field1', placeholder: 'write some text', type: 'text', }, { id: 'long-text-example', label: 'Long Text Example', type: 'longText', placeholder: 'Write your text here...', category: 'CUSTOM', defaultValue: null, attributes: { maxChars: 200, required: null, minChars: 2, }, }, ], type: 'dynamicFieldArray', }, ], }, showButton: true, buttonPosition: 'left', }; export const FormWithDynamicFieldArraySecondLvl = FormGroupComponent.bind({}); FormWithDynamicFieldArraySecondLvl.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { maxCount: null, minCount: null, ordering: 'append', required: null, rowLabel: 'field1', }, required: null, rowLabel: null, category: 'CUSTOM', defaultValue: null, description: '', id: 'test-dynamic-field-array', isOpen: false, isValid: true, label: 'Test Dynamic field array', placeholder: null, fields: [ { attributes: { maxChars: null, minChars: null, required: null, }, category: 'CUSTOM', defaultValue: null, description: 'some description', id: 'field1', isOpen: false, isValid: true, label: 'field1', placeholder: 'write some text', type: 'text', }, { id: 'long-text-example', label: 'Long Text Example', type: 'longText', placeholder: 'Write your text here...', category: 'CUSTOM', defaultValue: null, attributes: { maxChars: 200, required: null, minChars: 2, }, }, { attributes: { maxCount: null, minCount: null, ordering: 'prepend', required: null, rowLabel: null, }, required: null, rowLabel: null, category: 'CUSTOM', defaultValue: null, description: '', id: 'test-dynamic-field-array-2', isOpen: false, isValid: true, label: 'Test Dynamic field array 2', placeholder: null, fields: [ { attributes: { maxChars: null, minChars: null, required: null, }, category: 'CUSTOM', defaultValue: null, description: 'some description', id: 'field1', isOpen: false, isValid: true, label: 'field1', placeholder: 'write some text', type: 'text', }, ], type: 'dynamicFieldArray', }, ], type: 'dynamicFieldArray', }, ], }, }; export const FormWithDynamicFieldArrayThirdLvl = FormGroupComponent.bind({}); FormWithDynamicFieldArrayThirdLvl.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { attributes: { maxCount: null, minCount: null, ordering: 'append', required: null, rowLabel: null, }, required: null, rowLabel: null, category: 'CUSTOM', defaultValue: null, description: '', id: 'test-dynamic-field-array', isOpen: false, isValid: true, label: 'Test Dynamic field array', placeholder: null, fields: [ { attributes: { maxChars: null, minChars: null, required: null, }, category: 'CUSTOM', defaultValue: null, description: 'some description', id: 'field1', isOpen: false, isValid: true, label: 'field1', placeholder: 'write some text', type: 'text', }, { id: 'long-text-example', label: 'Long Text Example', type: 'longText', placeholder: 'Write your text here...', category: 'CUSTOM', defaultValue: null, attributes: { maxChars: 200, required: null, minChars: 2, }, }, { attributes: { maxCount: null, minCount: null, ordering: 'append', required: null, rowLabel: null, }, required: null, rowLabel: null, category: 'CUSTOM', defaultValue: null, description: '', id: 'test-dynamic-field-array-2', isOpen: false, isValid: true, label: 'Test Dynamic field array 2', placeholder: null, fields: [ { attributes: { maxChars: null, minChars: null, required: null, }, category: 'CUSTOM', defaultValue: null, description: 'some description', id: 'field2', isOpen: false, isValid: true, label: 'field2', placeholder: 'write some text', type: 'text', }, { attributes: { maxCount: null, minCount: 1, ordering: 'append', required: false, rowLabel: null, }, required: null, rowLabel: null, category: 'CUSTOM', defaultValue: null, description: '', id: 'test-dynamic-field-array-3', isOpen: false, isValid: true, label: 'Test Dynamic field array 3', placeholder: null, fields: [ { id: 'long-text-example2', label: 'Long Text Example2', type: 'longText', placeholder: 'Write your text here...', category: 'CUSTOM', defaultValue: null, attributes: { maxChars: 200, required: null, minChars: 2, }, }, ], type: 'dynamicFieldArray', }, ], type: 'dynamicFieldArray', }, ], type: 'dynamicFieldArray', }, ], }, }; export const FormWithUpdatedRichTextEditor = FormGroupComponent.bind({}); FormWithUpdatedRichTextEditor.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { id: 'rich-text-editor', label: 'Rich Text Editor', description: '', defaultValue: null, type: 'richText', required: null, attributes: { maxChars: 100, required: true, minChars: 10, }, options: null, }, ], }, }; export const FormWithFileUpload = FormGroupComponent.bind({}); FormWithFileUpload.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { id: 'file-upload', label: 'File Upload', description: '', defaultValue: null, type: 'multiFile', required: null, attributes: {}, options: null, }, { id: 'file-upload-1', label: 'private single File Upload', description: '', defaultValue: null, type: 'privateSingleFile', required: null, attributes: {}, options: null, }, { id: 'file-upload-2', label: 'private multi File Upload', description: '', defaultValue: null, type: 'multiPrivateFile', required: null, attributes: {}, options: null, }, ], }, }; export const FormWithRadioButtonList = FormGroupComponent.bind({}); FormWithRadioButtonList.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { id: 'role', label: 'Role', description: '', defaultValue: 'user', type: 'dropdownList', required: null, attributes: { required: true, subType: 'radioButton' }, options: ['admin', 'user', 'test'], fields: null, }, ], }, }; export const WizardForm = FormGroupComponent.bind({}); WizardForm.args = { formJsonData: { appTypeId: 'dfa-field', label: 'Wizard App Type', description: null, createdDate: 1612460763356, fields: [ { id: 'name', label: 'Name', type: 'text', attributes: { maxChars: null, required: true, minChars: null }, }, { id: 'customData.description', label: 'description', type: 'richText', attributes: { maxChars: null, required: null, minChars: null, group: '' }, }, { id: 'customData.contact-information', label: 'Contact information', description: 'Here is description!', type: 'fieldGroup', attributes: {}, }, { id: 'customData.contact-1', label: 'contact 1', description: 'Description of contact', type: 'text', attributes: { maxChars: null, required: true, minChars: null, group: 'contact-information' }, }, { id: 'customData.contact-2', label: 'contact 2', description: '', type: 'longText', attributes: { maxChars: null, required: true, minChars: null, group: 'contact-information' }, }, { id: 'customData.images', label: 'Images', description: '', type: 'fieldGroup', attributes: {}, }, { id: 'customData.images-1', label: 'Images 1', description: '', type: 'singleImage', attributes: { width: null, required: true, hash: null, accept: null, height: null, group: 'images', }, }, { id: 'customData.images-2', label: 'Images 2', description: '', type: 'singleFile', attributes: { required: true, hash: null, accept: null, group: 'images' }, }, { id: 'customData.personal-data', label: 'Personal Data', description: '', type: 'fieldGroup', attributes: {}, }, { id: 'customData.personal-1', label: 'Personal 1', description: '', type: 'color', attributes: { required: null, group: 'personal-data' }, }, { id: 'customData.personal-2', label: 'Personal 2', description: '', type: 'emailAddress', attributes: { required: true, group: 'personal-data' }, }, { id: 'customData.personal-3', label: 'Personal 3', description: '', type: 'richText', attributes: { maxChars: null, required: true, minChars: null, group: 'personal-data' }, }, { id: 'customData.general-test-field', label: 'General test field', description: '', defaultValue: [], type: 'tags', attributes: { minCount: null, maxCount: null, required: true, group: '' }, }, ], }, displayType: 'wizard', buttonPosition: 'justify', maxStepsToShow: 3, enableTextTruncation: true, }; export const PricingForm = FormGroupComponent.bind({}); const multiPricingField: DropdownAdditionalField = { id: 'currency', label: 'Pricing', type: 'dropdownList', defaultValue: 'EUR', options: ['USD', 'EUR'], attributes: { subType: 'additionalField', subTypeSettings: { additionalFieldId: 'price', additionalFieldAttributesByDropdownValue: { USD: { min: 10, max: 20, }, EUR: { min: 30, max: 40, }, }, }, }, }; const priceField: AppFormField = { id: 'price', type: 'number', label: 'Price', attributes: { required: true, formHideRow: true, }, }; const trialField: AppFormField = { id: 'trial', label: 'Trial period (in days)', type: 'number', attributes: { min: 0, }, }; const billingPeriodField: AppFormField = { id: 'billingPeriod', label: 'Billing period', type: 'dropdownList', defaultValue: 'monthly', options: ['daily', 'weekly', 'monthly', 'annually'], attributes: { transformText: 'titleCase', }, }; const billingPeriodUnitField: AppFormField = { id: 'billingPeriodUnit', label: 'Billing period unit', type: 'number', defaultValue: 1, }; const licenseField: AppFormField = { id: 'license', type: 'dropdownList', label: 'License', defaultValue: 'single', options: ['single', 'group'], attributes: { subType: 'radioButton', componentLayout: 'horizontal', transformText: 'titleCase', }, }; const multiCommissionField: DropdownAdditionalField = { id: 'commissionType', label: 'Commission', type: 'dropdownList', defaultValue: '%', options: ['%'], attributes: { subType: 'additionalField', subTypeSettings: { additionalFieldId: 'commission', additionalFieldAttributesByDropdownValue: {}, }, }, }; const commissionField: AppFormField = { id: 'commission', type: 'number', label: 'Commission', attributes: { formHideRow: true, min: 1, } }; const dropdownFormField: DropdownFormField = { id: 'pricingForm', type: 'dropdownForm', attributes: { dropdownSettings: { dropdownField: { id: 'type', label: 'Type', type: 'dropdownList', defaultValue: 'free', options: ['free', 'single', 'recurring', 'all fields'], attributes: { required: true, transformText: 'titleCase', }, }, dropdownForms: { free: [], single: [ multiPricingField, priceField, trialField, ], recurring: [ multiPricingField, priceField, trialField, billingPeriodField, billingPeriodUnitField, ], 'all fields': [ multiPricingField, priceField, trialField, billingPeriodField, billingPeriodUnitField, licenseField, multiCommissionField, commissionField, ] }, }, }, }; const mainForm: AppFormModel = { fields: [dropdownFormField], }; PricingForm.args = { formJsonData: mainForm, }; export const PricingFormDFA = FormGroupComponent.bind({}); const pricingFormDfaField = { id: 'model', type: 'dynamicFieldArray', defaultValue: [ { pricingForm: { type: 'free', }, }, { pricingForm: { type: 'single', trial: 45, price: 15, }, }, { pricingForm: { type: 'recurring', trial: 30, price: 2.5, }, }, ], fields: [dropdownFormField], attributes: { ordering: 'append', }, }; PricingFormDFA.args = { formJsonData: { fields: [pricingFormDfaField] }, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/management-components/oc-management-components.module.ts
<reponame>mukesh-openchannel/angular-template-libraries import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { OcInviteModalComponent } from './oc-invite-modal/oc-invite-modal.component'; import { OcMenuUserGridComponent } from './oc-menu-user-grid/oc-menu-user-grid.component'; import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { OcFormComponentsModule } from '@openchannel/angular-common-components/src/lib/form-components'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; @NgModule({ declarations: [OcInviteModalComponent, OcMenuUserGridComponent], imports: [CommonModule, OcFormComponentsModule, OcCommonLibModule, InfiniteScrollModule, NgbModule], exports: [OcInviteModalComponent, OcMenuUserGridComponent], }) export class OcManagementComponentsModule {}
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/file-upload-download.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { HttpRequestService } from './http-request-services'; import { mergeMap } from 'rxjs/operators'; import { ConfigService } from './config.service'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { FileDetailsResponse } from '../model/api/file-details-model'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting and modifying User Account model.<br> * * Endpoints:<br> * * POST 'v2/files/uploadToken'<br> * * GET 'v2/userAccounts/this'<br> * * POST '{marketUrl}/v2/files' * * GET '/v2/files/byIdOrUrl' * * GET '/v2/files/download' * * GET {fileUrl} */ @Injectable({ providedIn: 'root', }) export class FileUploadDownloadService { constructor( public httpRequest: HttpRequestService, private http: HttpClient, private configService: ConfigService, private apiPaths: OcApiPaths, ) {} /** * * Description: Get Token and upload file to open channel * * @param {FormData} file - File from formData * @param {boolean} isPrivate * @param {string[]} hash - (optional) file hash * @returns {Observable<any>} `Observable<any>` * * ### Example: * * `uploadToOpenChannel({file},true, ['na0s78hd09a8shd90ahsd'])` */ uploadToOpenChannel(file: FormData, isPrivate: boolean, hash?: string[]): Observable<any> { return this.getToken().pipe(mergeMap(res => this.prepareUploadReq(res.token, file, isPrivate, hash))); } /** * * Description: Prepare upload request and upload file * * @param {any} token - Token for channel * @param {FormData} file - File from formData * @param {boolean} isPrivate * @param {string[]} hash - (optional) file hash * @returns {Observable<any>} `Observable<any>` * * ### Example: * * `prepareUploadReq('0a897shd0897ahs09d8has9d7',{file},true, ['na0s78hd09a8shd90ahsd'])` */ prepareUploadReq(token, file: FormData, isPrivate: boolean, hash?: string[]): Observable<any> { let httpParams = new OcHttpParams(); if (isPrivate) { httpParams = httpParams.set('isPrivate', `${isPrivate}`); } if (hash?.length > 0) { httpParams = httpParams.set('hash', hash.join(',')); } return this.configService.getMarketUrl().pipe( mergeMap(marketUrl => { return this.http.post(`${marketUrl}/${this.apiPaths.files}`, file, { headers: new HttpHeaders({ 'Upload-Token': `${token}` }), params: httpParams, reportProgress: true, observe: 'events', }); }), ); } /** * * Description: Get token for a channel * * @returns {Observable<any>} `Observable<any>` * * ### Example: * * `getToken();` */ getToken(): Observable<any> { return this.httpRequest.post(`${this.apiPaths.files}/uploadToken`, null); } /** * * Description: Get file details * * @param {string} fileId, * @param {HttpHeaders} headers * @returns {Observable<FileDetailsResponse>} `Observable<FileDetailsResponse>` * * ### Example: * * `downloadFileDetails('ha98s7dh8a7shd87');` */ downloadFileDetails(fileId: string, headers: HttpHeaders = new HttpHeaders()): Observable<FileDetailsResponse> { return this.httpRequest.get(`${this.apiPaths.files}/byIdOrUrl?fileIdOrUrl=${fileId}`, { headers }); } /** * * Description: Download file from provided URL * * @param {string} fileUrl * @returns {Observable<any>} `Observable<any>` * * ### Example: * * `downloadFileFromUrl('/image.jpg');` */ downloadFileFromUrl(fileUrl: string): Observable<any> { return this.http.get(fileUrl, { responseType: 'blob' }); } /** * * Description: Get file URL * * @param {string} fileId * @returns {Observable<any>} `Observable<any>` * * ### Example: * * `getFileUrl('/image.jpg');` */ getFileUrl(fileId: string): Observable<any> { return this.httpRequest.get(`${this.apiPaths.files}/download?fileId=${fileId}`); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/invite-user.model.ts
export interface AbstractInviteModel { email?: string; expireDate?: number; expireSeconds?: number; createdDate?: number; subject?: string; body?: string; name?: string; type?: string; customData?: any; token?: string; lastSent?: number; roles?: string[]; permissions?: string[]; } export interface InviteUserModel extends AbstractInviteModel { userInviteId?: string; userInviteTemplateId?: string; userId?: string; userAccountId?: string; } export interface InviteDeveloperModel extends AbstractInviteModel { developerInviteId?: string; developerInviteTemplateId?: string; developerId?: string; developerAccountId?: string; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/developer-account.service.ts
<gh_stars>0 import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpRequestService } from './http-request-services'; import { DeveloperAccount } from '../model/api/developer-account.model'; import { DeveloperAccountModel } from '../model/api/developer.model'; import { Page } from '../model/api/page.model'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting and modifying User Account model.<br> * * Endpoints:<br> * * GET 'v2/developerAccounts/all'<br> * * GET 'v2/developerAccounts/this'<br> * * PATCH 'v2/developerAccounts/this'<br> * * DELETE 'v2/developerAccounts/this'<br> * * PATCH 'v2/developerAccounts/{developerAccountId}'<br> * * DELETE 'v2/developerAccounts/{developerAccountId}'<br> */ @Injectable({ providedIn: 'root', }) export class DeveloperAccountService { constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Get developer account data * * @returns {Observable<DeveloperAccount>} `Observable<DeveloperAccount>` * * ### Example * * `getAccount();` */ getAccount(): Observable<DeveloperAccount> { return this.httpService.get(`${this.apiPaths.developerAccounts}/this`); } /** * * Description: Update developer account fields * * @param {Partial<DeveloperAccount>} body - Data to update * @returns {Observable<DeveloperAccount>} `Observable<DeveloperAccount>` * * ### Example * * `getAccount({name: 'Developer'});` */ updateAccountFields(body: Partial<DeveloperAccount>): Observable<DeveloperAccount> { return this.httpService.patch(`${this.apiPaths.developerAccounts}/this`, body); } /** * * Description: Update developer account to specific user * * @param {string} developerAccountId * @param {string} skipTypeValidation * @param {Partial<DeveloperAccount>} body * @returns {Observable<DeveloperAccount>} `Observable<DeveloperAccount>` * * ### Example * * `updateAccountFieldsForAnotherUser('ga<PASSWORD>', false, {name: 'Developer'});` */ updateAccountFieldsForAnotherUser(developerAccountId: string, skipTypeValidation: boolean, body: Partial<DeveloperAccount>): Observable<DeveloperAccount> { const mainUrl = `${this.apiPaths.developerAccounts}/${encodeURIComponent(developerAccountId)}`; const params = new OcHttpParams().append('skipTypeValidators', String(skipTypeValidation)); return this.httpService.patch(mainUrl, body, { params }); } /** * * Description: Get list of developer accounts with pagination * * @param {number} page - (optional) Current page index. Starts from >= 1. * @param {number} limit - (optional) Count Developer Accounts into response. Starts from >= 1. * @param {string} sort - (optional) Sort Developer Accounts by specific field. * @param {string} filter - (optional) Your specific search filter. * @returns {Observable<Page<DeveloperAccountModel>>} `Observable<Page<DeveloperAccountModel>>` * * ### Example * * `getDeveloperAccounts(1, 10, "{"name": 1}", "{"name": {"$in":["first", "second"]}}");` */ getDeveloperAccounts(pageNumber?: number, limit?: number, sort?: string, query?: string): Observable<Page<DeveloperAccountModel>> { const mainUrl = `${this.apiPaths.developerAccounts}/all`; const params = new OcHttpParams() .append('pageNumber', String(pageNumber)) .append('limit', String(limit)) .append('sort', sort) .append('query', query); return this.httpService.get(mainUrl, { params }); } /** * * Description: Find developer account by id and delete * * @param {string} developerAccountId * @returns {Observable<any>} `Observable<any>` * * ### Example * * `deleteDeveloperAccount('97agsd986ags9d86g');` */ deleteDeveloperAccount(developerAccountId: string): Observable<any> { return this.httpService.delete(`${this.apiPaths.developerAccounts}/${encodeURIComponent(developerAccountId)}`); } /** * * Description: Delete current developer account * * @returns {Observable<any>} `Observable<any>` * * ### Example * * `deleteCurrentDeveloperAccount();` */ deleteCurrentDeveloperAccount(): Observable<any> { return this.httpService.delete(`${this.apiPaths.developerAccounts}/this`); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-app-get-started/oc-app-get-started.component.spec.ts
<filename>projects/angular-common-components/src/lib/market-components/oc-app-get-started/oc-app-get-started.component.spec.ts<gh_stars>0 import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcAppGetStartedComponent } from './oc-app-get-started.component'; import { By } from '@angular/platform-browser'; import { MockButtonComponent, MockHeadingTagDirective } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcAppGetStartedComponent', () => { let component: OcAppGetStartedComponent; let fixture: ComponentFixture<OcAppGetStartedComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcAppGetStartedComponent, MockButtonComponent, MockHeadingTagDirective], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcAppGetStartedComponent); component = fixture.componentInstance; component.getStartedButtonText = 'Get Started'; component.getStartedHeader = 'Test Get Started'; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show search', () => { component.getStartedType = 'search'; fixture.detectChanges(); const header: HTMLHeadingElement = fixture.debugElement.query(By.css('h1')).nativeElement; expect(header.textContent).toContain('Test Get Started'); }); it('should show home', () => { component.getStartedType = 'home'; component.getStartedDescription = 'This is only test description'; component.getStartedImage = 'https://stage1-philips-market-test.openchannel.io/assets/angular-common-components/item-1.png'; fixture.detectChanges(); const description: HTMLParagraphElement = fixture.debugElement.query(By.css('p')).nativeElement; const image: HTMLImageElement = fixture.debugElement.query(By.css('img')).nativeElement; expect(description.textContent).toContain('This is only test description'); expect(image.src).toBeTruthy(); }); it('should emit click on Button component', () => { component.getStartedType = 'search'; jest.spyOn(component.getStarted, 'emit'); fixture.detectChanges(); const button = fixture.debugElement.query(By.css('oc-button')).nativeElement; button.click(); expect(component.getStarted.emit).toHaveBeenCalledTimes(1); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-form-modal/oc-form-modal.component.ts
<reponame>mukesh-openchannel/angular-template-libraries<gh_stars>0 import { Component, Input, TemplateRef } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { FormGroup } from '@angular/forms'; import { AppFormModel } from '../model/app-form-model'; import { ErrorMessageFormId } from '@openchannel/angular-common-components/src/lib/common-components'; /** * Form modal component. Represents form in modal window and all related logic. * * @example <oc-form-modal [modalTitle]="Custom title" * [formJsonData]="{ * formId: 'test', * name: 'test', * createdDate: 1599982592157, * fields: [ * { * id: 'role', * label: 'role', * description: '', * defaultValue: 'user', * type: 'dropdownList', * required: null, * attributes: {required: true}, * options: ['admin', 'user', 'test'], * } * ] * }" * [confirmButton]="cButtonTemplateRef" * [rejectButton]="rButtonTemplateRef" * > */ @Component({ selector: 'oc-form-modal', templateUrl: './oc-form-modal.component.html', styleUrls: ['./oc-form-modal.component.css'], }) export class OcFormModalComponent { /** * Title of modal window */ @Input() modalTitle: string; /** * Metadata for form builder */ @Input() formJsonData: AppFormModel; /** * Confirm button template ref. Use it if you want to change deafault confirmation button. */ @Input() confirmButton: TemplateRef<any>; /** * Reject button template ref. Use it if you want to change deafault reject button. */ @Input() rejectButton: TemplateRef<any>; /** Current form ID. Used for modifying error messages. Look: {@link ErrorMessageFormId} */ @Input() formId: ErrorMessageFormId = null; /** * Angular form group * @private */ private formGroup: FormGroup; /** * Data for form * @private */ private formData: any; /** * Modal window instance * @private */ private modal: NgbActiveModal; constructor(modal: NgbActiveModal) { this.modal = modal; } /** * Function for dismiss modal window */ dismiss(): void { this.modal.dismiss(); } /** * Set new form to a variable * @param {FormGroup} createdForm */ setCreatedForm(createdForm: FormGroup): void { this.formGroup = createdForm; } /** * Set data to form * @param {any} data */ setDataFromForm(data: any): void { this.formData = data; } /** * Function that executes on click to confirmation button */ onClickConfirmButton(): void { if (this.formGroup) { this.formGroup.markAllAsTouched(); if (this.formGroup.valid && this.formData) { this.modal.close(this.formData); } } } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/app-type-model.ts
export interface AppTypeOptionModelResponse { value: string; } export interface AppTypeFieldModelResponse { id: string; label: string; type: string; attributes?: any; description?: string; fields?: AppTypeFieldModelResponse[]; defaultValue?: any; placeholder?: string; options?: AppTypeOptionModelResponse[] | string[]; specialType?: string; } export interface AppTypeModelResponse { appTypeId: string; label?: string; description?: string; createdDate: any; fields?: AppTypeFieldModelResponse[]; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-dropdown/oc-dropdown.component.spec.ts
<gh_stars>0 import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcDropdownComponent } from './oc-dropdown.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; describe('OcDropdownComponent', () => { let component: OcDropdownComponent; let fixture: ComponentFixture<OcDropdownComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcDropdownComponent], imports: [NgbModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcDropdownComponent); component = fixture.componentInstance; fixture.detectChanges(); component.options = [ { label: 'Select 1', value: 'select1' }, { label: 'Select 2', value: 'select2' }, { label: 'Select 3', value: 'select3' }, ]; }); it('should create', () => { expect(component).toBeTruthy(); }); it('should change and emit selected value', () => { const dropdownSelect = fixture.nativeElement.querySelector('#dropdownManual'); jest.spyOn(component.selectedChange, 'emit'); dropdownSelect.click(); fixture.detectChanges(); const dropdownButtonSelected = fixture.nativeElement.querySelectorAll('.dropdown-item')[0]; dropdownButtonSelected.click(); expect(component.selected).toEqual({ label: 'Select 1', value: 'select1' }); expect(component.selectedChange.emit).toHaveBeenCalledWith({ label: 'Select 1', value: 'select1' }); }); it('should change a title', () => { component.title = 'Some title of'; component.selected = { label: 'Select 1', value: 'select1' }; const dropdownSelect = fixture.nativeElement.querySelector('#dropdownManual'); fixture.detectChanges(); expect(dropdownSelect.textContent).toContain('Some title of Select 1'); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/meta-tag.model.ts
import { MetaDefinition } from '@angular/platform-browser'; /** * Custom meta tag implementation. * Content for this meta can be filled from the specific response data. * Used only for config: {@link PageMetaTags} * * @example * const customDescriptionMetaTag: CustomMetaDefinition = { * name: 'og:description', * content: 'Your default description text', * definitionPath: 'app.customData.description' * }; */ export interface CustomMetaDefinition extends MetaDefinition { /** Path for getting content from {@link OCMetaTagService.tempPageData} object. */ definitionPath: string; } /** * Includes specific array of meta tags for page. * Will be applied when router link starts with {@link routerLinkStartsWith}. * Used in config {@link MetaTagsPageConfig}. * * @example * const loginPageMetaTags: PageMetaTags = { * routerLinkStartsWith: '/login', * metaTags: [ * { name: 'description', content: 'My custom description' }, * { name: 'og:image', content: 'https://my.image.com/login.svg' }, * ] * } */ export interface PageMetaTags { routerLinkStartsWith: string | null; metaTags: OCMetaTagConfigType[]; } /** * Main meta tags configuration for all pages.<br> * Used in: {@link OCMetaTagService#getMetaTagsConfig}. * * @example * const metaTags: MetaTagsPageConfig = { * defaultMetaTags: [ * { name: 'author', content: 'Default author name' }, * { name: 'description', content: 'Default page description' }, * { name: 'generator', content: 'Default generator' }, * { name: 'og:url', definitionPath: 'windowUrl' }, * { name: 'og:title', content: '(social platforms) Default title' }, * { name: 'og:image', content: '(social platforms) Default image URL' }, * { name: 'og:description', content: '(social platforms) Default page description' }, * ], * pages: [ * { * routerLinkStartsWith: '/', // custom meta tags for home page. * metaTags: [ * { name: 'description', content: 'OpenChannel' }, * { name: 'og:title', content: 'OpenChannel' }, * { name: 'og:image', content: 'OpenChannel' }, * { name: 'og:description', content: 'OpenChannel' }, * ], * }, * { * routerLinkStartsWith: '/details', // custom meta tags for app details page. * metaTags: [ * { name: 'description', content: 'Your default summary text', definitionPath: 'app.customData.summary' }, * { name: 'og:title', content: 'Your default name text', definitionPath: 'app.name' }, * { name: 'og:image', content: 'Your default image url', definitionPath: 'app.customData.logo' }, * { name: 'og:description', content: 'Your default description text', definitionPath: 'app.customData.description' }, * ], * }, * ], * }; */ export interface MetaTagsPageConfig { /** Default meta tags (all pages). Can be override configs from {@link MetaTagsPageConfig#pages} */ defaultMetaTags: OCMetaTagConfigType[]; /** Specific meta tags for pages */ pages: PageMetaTags[]; } export type OCMetaTagConfigType = MetaDefinition | CustomMetaDefinition;
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/pipe/ellipsis.pipe.ts
<reponame>mukesh-openchannel/angular-template-libraries<gh_stars>0 import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'ellipsis', }) export class EllipsisPipe implements PipeTransform { transform(value: string, limit: number = 25, ellipsis: string = '...'): string { return value.length > limit ? value.substr(0, limit) + ellipsis : value; } }
mukesh-openchannel/angular-template-libraries
src/dropdown.stories.ts
<filename>src/dropdown.stories.ts import { OcCommonLibModule, OcDropdownComponent } from '@openchannel/angular-common-components/src/lib/common-components'; import { moduleMetadata } from '@storybook/angular'; import { AngularSvgIconModule } from 'angular-svg-icon'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; const modules = { imports: [OcCommonLibModule, AngularSvgIconModule.forRoot(), NgbModule], }; export default { title: 'Dropdown [BEM]', component: OcDropdownComponent, decorators: [moduleMetadata(modules)], }; const DropdownComponent = (args: OcDropdownComponent) => ({ component: OcDropdownComponent, moduleMetadata: modules, props: args, }); export const DefaultDropdownLabel = DropdownComponent.bind({}); DefaultDropdownLabel.args = { selected: { label: 'popular', }, options: [ { label: 'popular', }, { label: 'newest', }, { label: 'featured', }, ], };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-multi-select-checkbox-list/oc-multi-select-checkbox-list.component.spec.ts
<filename>projects/angular-common-components/src/lib/form-components/oc-multi-select-checkbox-list/oc-multi-select-checkbox-list.component.spec.ts import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcMultiSelectCheckboxListComponent } from './oc-multi-select-checkbox-list.component'; import { MockCheckboxComponent } from '../../../mock/mock'; import { By } from '@angular/platform-browser'; describe('OcMultiSelectCheckboxListComponent', () => { let component: OcMultiSelectCheckboxListComponent; let fixture: ComponentFixture<OcMultiSelectCheckboxListComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcMultiSelectCheckboxListComponent, MockCheckboxComponent], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcMultiSelectCheckboxListComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('show all items', () => { component.itemsArray = ['A', 'B']; fixture.detectChanges(); expect(findItemById('A')).toBeDefined(); expect(findItemById('B')).toBeDefined(); }); it('init default values', () => { component.itemsArray = ['A', 'B', 'C']; component.defaultItemsArray = ['B']; jest.spyOn(component.selectedItemsOutput, 'emit'); fixture.detectChanges(); expect(component.selectedItemsOutput.emit).toHaveBeenCalledWith(['B']); }); it('select an item', () => { component.itemsArray = ['A', 'B', 'C']; jest.spyOn(component.selectedItemsOutput, 'emit'); fixture.detectChanges(); expect(component.selectedItemsOutput.emit).toHaveBeenCalledWith([]); findItemById('B-text').click(); fixture.detectChanges(); expect(component.selectedItemsOutput.emit).toHaveBeenCalledWith(['B']); }); function findItemById(itemId: string): any { return fixture.debugElement.query(By.css(`#multi-checkbox-item-${itemId}`))?.nativeElement; } });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/oc-reset-password/oc-reset-password.component.ts
<filename>projects/angular-common-components/src/lib/auth-components/oc-reset-password/oc-reset-password.component.ts<gh_stars>0 import { Component, EventEmitter, Input, Output } from '@angular/core'; import { ComponentsUserResetPassword } from '../models/auth-types.model'; import { ErrorMessageFormId, HeadingTag } from '@openchannel/angular-common-components/src/lib/common-components'; /** * A reset password component. A form, which allows user to change his account password. * Contains of a header, password field and navigation links. */ @Component({ selector: 'oc-reset-password', templateUrl: './oc-reset-password.component.html', styleUrls: ['./oc-reset-password.component.css'], }) export class OcResetPasswordComponent { /** * A source path for company logo. * @type {string}. */ @Input() companyLogoUrl: string; /** * A variable which determines whether to show or hide button text. * Shows button text if it has no active process. * @type {boolean}. */ @Input() process: boolean; /** * Login url for those users who already has an account. * @type {string}. */ @Input() loginUrl: string; /** * Signup url for those users who has no account yet. * @type {string}. */ @Input() signupUrl: string; /** * The user password model for signup. * @type {ComponentsUserResetPassword}. */ @Input() resetModel: ComponentsUserResetPassword = new ComponentsUserResetPassword(); /** * Event emitter that submits form. * Uses ResetPasswordForm. * @type {*}. */ @Output() readonly buttonClick: EventEmitter<any> = new EventEmitter<any>(); /** * Heading tag of title * @type {HeadingTag}. * @example. * 'h2'. */ @Input() headingTag: HeadingTag = 'h1'; /** Current form ID. Used for modifying error messages. Look: {@link ErrorMessageFormId} */ formId: ErrorMessageFormId = 'resetPassword'; /** * Submits a reset password form. * Marks all fields as touched. * Then emits the valid value of the form. */ submitForm(form: any): void { if (!form.valid || this.process) { form.control.markAllAsTouched(); this.buttonClick.emit(false); } else { this.buttonClick.emit(true); } } /** * Calls when form model changes. * Checks form errors and validators. */ onchange(form: any): void { if (form.form.controls.newPassword.errors && form.form.controls.newPassword.errors.serverErrorValidator) { form.form.controls.newPassword.setErrors(null); } } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-tag-element/oc-tag-element.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcTagElementComponent } from './oc-tag-element.component'; import { By } from '@angular/platform-browser'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcTagElementComponent', () => { let component: OcTagElementComponent; let fixture: ComponentFixture<OcTagElementComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcTagElementComponent, MockSvgIconComponent], imports: [HttpClientTestingModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcTagElementComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show tag data', () => { component.title = 'Test Tag'; component.closeMarker = true; fixture.detectChanges(); const closeMarker: HTMLOrSVGElement = fixture.debugElement.query(By.css('svg-icon')).nativeElement; const tagTitle: HTMLDivElement = fixture.debugElement.query(By.css('.tag-element__text')).nativeElement; expect(closeMarker).toBeTruthy(); expect(tagTitle.textContent).toContain('Test Tag'); }); it('should emit a value', () => { component.title = 'Test Tag'; component.closeMarker = true; fixture.detectChanges(); const closeMarker: HTMLImageElement = fixture.debugElement.query(By.css('svg-icon')).nativeElement; jest.spyOn(component.clickEmitter, 'emit'); closeMarker.click(); expect(component.clickEmitter.emit).toHaveBeenCalledWith('Test Tag'); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/portal-components/public-api.ts
<filename>projects/angular-common-components/src/lib/portal-components/public-api.ts<gh_stars>0 export * from './oc-chart/oc-chart.component'; export * from './oc-app-table/oc-app-table.component'; export * from './oc-portal-components.module'; /** Models */ export * from './models/app-listing.model'; export * from './models/oc-chart.model';
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/pipe/html-tags-replacer.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'replaceHtmlTags', }) export class HtmlTagsReplacerPipe implements PipeTransform { transform(value: string): string { if (typeof value === 'string' && value.match(/<[^>]*>/g)) { const tmp = document.createElement('div'); tmp.innerHTML = value; return tmp.textContent || tmp.innerText || ''; } return value; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-color/oc-color.component.ts
<filename>projects/angular-common-components/src/lib/form-components/oc-color/oc-color.component.ts import { Component, forwardRef, Input } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; /** * Component represents input for color data. User can choose a color from the color picker palette. * Or color value can be written into the input field. Component has demonstration square for chosen color. * Also this component supports `Abstract Control` format, so it can work with `ngModel` or `formControl`. */ @Component({ selector: 'oc-color', templateUrl: './oc-color.component.html', styleUrls: ['./oc-color.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => OcColorComponent), multi: true, }, ], }) export class OcColorComponent implements ControlValueAccessor { /** Set value from AbstractControl, like `ngModel` or `formControl` */ @Input() set value(val: string) { this.colorValue = val; this.onChange(this.colorValue); } /** Set `disable` state for color input. User can not interact with this component */ @Input() disabled: boolean = false; /** Placeholder text for input field */ @Input() placeholder: string = ''; /** * Set position for the color picker button. * @default: 'bottom-left' */ @Input() colorPickerPosition: 'auto' | 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' = 'bottom-left'; /** Chosen color value */ colorValue: string; /** Toggle Open or Close of the color picker dialog */ toggleDialog: boolean = false; /** * Sending data to the formControl when * color is chosen */ onValueChange(): void { this.onChange(this.colorValue); } /** * Register touch action */ onFocus(): void { this.onTouched(); } /** * Calls this function with new value. When user wrote something in the component * It needs to know that new data has been entered in the control. */ registerOnChange(onChange: (value: any) => void): void { this.onChange = onChange; } /** * Calls this function when user left chosen component. * It needs for validation */ registerOnTouched(onTouched: () => void): void { this.onTouched = onTouched; } /** * (Optional) * the method will be called by the control when the [disabled] state changes. */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } /** * this method will be called by the control to pass the value to our component. * It is used if the value is changed through the code outside * (setValue or changing the variable that ngModel is tied to), * as well as to set the initial value. */ writeValue(obj: any): void { this.colorValue = obj; } private onTouched = () => { // nothing to do }; private onChange: (value: any) => void = () => { // nothing to do }; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-app-gallery/oc-app-gallery.component.ts
import { Component, EventEmitter, Input, Output, TemplateRef } from '@angular/core'; import { FullAppData, HeadingTag } from '@openchannel/angular-common-components/src/lib/common-components'; import { get } from 'lodash'; @Component({ selector: 'oc-app-gallery', templateUrl: './oc-app-gallery.component.html', styleUrls: ['./oc-app-gallery.component.css'], }) export class OcAppGalleryComponent { /** * The array of the apps what will be shown in this component. * * Default: empty */ @Input() appsArr: FullAppData[] = []; /** * Message that will be shown if the array of apps is empty. * * Default: empty string */ @Input() noAppMessage: string = ''; /** * Title for the more apps link. */ @Input() moreAppsTitle: string = 'More'; /** * Title for the app list preview. Main title of the component. */ @Input() appGalleryTitle: string = ''; /** * Description for the app list preview. Will appear under title. */ @Input() appGalleryDescription: string = ''; /** * Path to the custom icon for a link to the more apps to show. * * Default: arrow icon. */ @Input() routerIcon: string = 'assets/angular-common-components/arrow.svg'; /** * Custom template for the app card to show. * If not applied - default app card will be shown. */ @Input() customAppCardTemplate: TemplateRef<FullAppData>; /** * Router link for the navigation to page with more apps. * @example * '/apps/all' * ['/apps', appsCategory] */ @Input() seeAllUrl: string | any[]; /** * Router link which will be used for navigation by app card click. * Using for the default app card only. * @example * '/apps' */ @Input() routerLinkForOneApp: string; /** * Key name of the App object which will be chosen like navigation parameter for the Router link. * Using only with the default app card template. * @default 'appId' */ @Input() appNavigationParam: string = 'appId'; /** * Heading tag of label * @type {HeadingTag}. * @example. * 'h2'. */ @Input() headingTag: HeadingTag = 'h2'; /** * @deprecated * Sending current app data on click by App card. It is deprecated, use {@link routerLinkForOneApp} with * {@link appNavigationParam} for the redirect. * * Return {FullAppData} */ @Output() readonly clickAppCard: EventEmitter<FullAppData> = new EventEmitter<FullAppData>(); /** * Emitter for click by moreAppsTitle. */ @Output() readonly clickMoreApps: EventEmitter<void> = new EventEmitter<void>(); /** * Emitter for click by title text. */ @Output() readonly clickHeaderTitle: EventEmitter<void> = new EventEmitter<void>(); getAppValueByParameter(app: FullAppData): string { if (this.appNavigationParam) { return get(app, this.appNavigationParam); } return ''; } onClickByHeaderTitle(): void { this.clickHeaderTitle.emit(); } }
mukesh-openchannel/angular-template-libraries
src/app-overall-rating.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcOverallRatingComponent } from '@openchannel/angular-common-components/src/lib/market-components'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; const modules = { imports: [OcCommonLibModule, NgbModule], }; export default { title: 'Overall Rating [BEM]', component: OcOverallRatingComponent, decorators: [moduleMetadata(modules)], }; const overAllRatingSummaryEmpty = { rating: 0, reviewCount: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, }; const overAllRatingSummary1 = { rating: 4.3, reviewCount: 12, 1: 0, 2: 0, 3: 1, 4: 3, 5: 8, }; const OverallRatingComponent = (args: OcOverallRatingComponent) => ({ component: OcOverallRatingComponent, moduleMetadata: modules, prop: args, }); export const EmptyRating = OverallRatingComponent.bind({}); EmptyRating.args = { overallReviewLabel: 'Overall rating', allReviewSummary: overAllRatingSummaryEmpty, }; export const RatingSummary = OverallRatingComponent.bind({}); RatingSummary.args = { overallReviewLabel: 'Overall rating', allReviewSummary: overAllRatingSummary1, };
mukesh-openchannel/angular-template-libraries
src/file-uploader.stories.ts
<reponame>mukesh-openchannel/angular-template-libraries import { moduleMetadata, storiesOf } from '@storybook/angular'; import { withA11y } from '@storybook/addon-a11y'; import { OcFileUploadComponent, FileDetails, FileUploaderService } from '@openchannel/angular-common-components/src/lib/form-components'; import { action } from '@storybook/addon-actions'; import { HttpClientModule, HttpResponse, HttpUploadProgressEvent } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { ImageCropperModule } from 'ngx-image-cropper'; const mockResponse: FileDetails = { uploadDate: 214213, fileId: 'fileId', name: 'test1.jpg', contentType: 'type', size: 123123, isPrivate: false, mimeCheck: 'PASSED', fileUrl: 'http://file-url.com', isError: false, fileUploadProgress: 100, virusScan: { started: 1457710762784, finished: 1457710769567, status: 'CLEAN', foundViruses: [ { fileName: 'jacks.docx', virusName: 'H237 Worm', }, ], }, fileIconUrl: '', }; class FileUploadDownloadServiceStub extends FileUploaderService { constructor() { super(); } fileUploadRequest( file: FormData, isPrivate: boolean, hash?: string[], ): Observable<HttpResponse<FileDetails> | HttpUploadProgressEvent> { return of(new HttpResponse({ body: mockResponse })); } fileDetailsRequest(fileId: string): Observable<FileDetails> { return of(mockResponse); } } const modules = { imports: [OcCommonLibModule, NgbModule, HttpClientModule, ImageCropperModule], providers: [{ provide: FileUploaderService, useClass: FileUploadDownloadServiceStub }], }; const file1 = new FileDetails(); file1.name = 'Product_image.png'; file1.fileUploadProgress = 0; const file2 = new FileDetails(); file2.name = 'Product_image.png'; file2.fileUploadProgress = 50; const file3 = new FileDetails(); file3.name = 'Product_side_image.png'; file3.fileUploadProgress = 75; const file4 = new FileDetails(); file4.name = 'Product_backside_image.png'; file4.fileUploadProgress = 100; file4.fileUrl = './assets/angular-common-components/standard-app-icon.svg'; file4.size = 2048000; file4.uploadDate = 1595942005169; const metadata = moduleMetadata({}); storiesOf('File Uploader [BEM]', module) .addParameters({ component: OcFileUploadComponent, }) .addDecorator(withA11y) .addDecorator(metadata) .add('Single Private File', () => ({ component: OcFileUploadComponent, moduleMetadata: modules, props: { fileUpload: action('fileUpload'), fileType: 'privateSingleFile', uploadIconUrl: 'assets/angular-common-components/upload_icon.svg', defaultFileIcon: 'assets/angular-common-components/file_icon.svg', }, })) .add('Single File With Data', () => ({ component: OcFileUploadComponent, moduleMetadata: modules, props: { fileDetailArr: [file2], fileType: 'privateSingleFile', uploadIconUrl: 'assets/angular-common-components/upload_icon.svg', defaultFileIcon: 'assets/angular-common-components/file_icon.svg', }, })) .add('Multi Public Image With Data', () => ({ component: OcFileUploadComponent, moduleMetadata: modules, props: { isMultiFile: true, fileDetailArr: [file1, file2, file3, file4], fileType: 'multiImage', uploadIconUrl: 'assets/angular-common-components/upload_icon.svg', defaultFileIcon: 'assets/angular-common-components/file_icon.svg', }, }));
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/model/utils.model.ts
<filename>projects/angular-common-components/src/lib/common-components/model/utils.model.ts import { AbstractControl, AbstractControlDirective, FormArray, FormGroup, NgModel } from '@angular/forms'; export function replaceHTMLTags(text: string): string { if (text && text.match(/<[^>]*>/g)) { const tmp = document.createElement('div'); tmp.innerHTML = text; return tmp.textContent || tmp.innerText || ''; } return text; } export class ControlUtils { static getParentControl(control: AbstractControl): AbstractControl { if (control?.parent) { return this.getParentControl(control?.parent); } return control; } static getFullControlPath(control: AbstractControlDirective | AbstractControl | NgModel): string { if (!control) { return ''; } else if (control instanceof NgModel || control instanceof AbstractControlDirective) { return (control.path || []).join('.'); } else { return this.getFullControlPathByAbstractControl(control, ''); } } private static getFullControlPathByAbstractControl(childControl: AbstractControl, childPath: string): string { const parentControl = childControl?.parent; if (parentControl) { if (parentControl instanceof FormArray) { const controlName = this.getControlName(parentControl, childControl); return this.getFullControlPathByAbstractControl(parentControl, `[${controlName}].${childPath}`); } else if (parentControl instanceof FormGroup) { const controlName = this.getControlName(parentControl, childControl); if (!childPath) { return this.getFullControlPathByAbstractControl(parentControl, controlName); } else { const childPathWithSeparator = childPath[0] === '[' ? childPath : `.${childPath}`; return this.getFullControlPathByAbstractControl(parentControl, `${controlName}${childPathWithSeparator}`); } } } return childPath; } private static getControlName(parentControl: FormArray | FormGroup, childControl: AbstractControl): string { const { controls } = parentControl; return Object.keys(controls).find(name => childControl === controls[name]) || null; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-label/oc-label.component.ts
<gh_stars>0 import { Component, Input } from '@angular/core'; /** * Label component. Represent label template with some variables. * * @example <oc-label [text]="`label`" [required]="true" [class]="`label`"> */ @Component({ selector: 'oc-label', templateUrl: './oc-label.component.html', styleUrls: ['./oc-label.component.css'], }) export class OcLabelComponent { /** Label text */ @Input() text: string = ''; /** Show indicator of required field */ @Input() required: boolean = false; /** Set global classes for label */ @Input() class: string = ''; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-form/oc-form-validator.ts
<gh_stars>0 import { AbstractControl, ValidatorFn } from '@angular/forms'; import { OcFieldType } from '../model/app-form-model'; import { TrimTextUtils } from '../service/trim-text-utils/trim-text.service'; import { AppTypeFieldModel } from '@openchannel/angular-common-components/src/lib/common-components'; export class OcFormValidator { /** * Return 'minLength' validation error, when array length < min. */ static validatorMinLengthArray(min: number, label: string, showLengthErrorText?: boolean): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { if (!c.value || c.value.length === 0 || c.value.length >= min) { return null; } else { if (showLengthErrorText) { return { minElementsCount: { requiredCount: min, fieldLabel: label, }, }; } else { return { minCount: true, }; } } }; } /** * Return 'maxLength' validation error, when array length > max. */ static validatorMaxLengthArray(max: number, label: string, showLengthErrorText?: boolean): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { if (!c.value || c.value.length === 0 || c.value.length <= max) { return null; } else { if (showLengthErrorText) { return { maxElementsCount: { requiredCount: max, fieldLabel: label, }, }; } else { return { maxCount: true, }; } } }; } /** * Custom validator * for the url type control */ static urlValidator(isTrimText: boolean): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { // regex for url validation const reg = new RegExp(/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/gm); // NOSONAR const value = isTrimText ? TrimTextUtils.updateByType(c.value) : c.value; if (reg.test(value) || !value) { return null; } else { return { websiteValidator: true, }; } }; } /** * Custom validator for color control */ static colorValidator(): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { const value = c.value; if ((value.charAt(0) === '#' && value.length === 7) || value === '') { return null; } else { return { colorValidator: true, }; } }; } /** * Custom validator of min characters for rich text. * Check only characters, not tags */ static richTextMinCharactersValidator(min: number, isTrimText: boolean): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { const characters = this.removeHtmlTagsFromRichText( (isTrimText ? TrimTextUtils.updateByType(c.value, 'richText') : c.value) || '', ); if (!characters || characters.length >= min) { return null; } else { return { minlength: { requiredLength: min, }, }; } }; } /** * Custom validator of max characters for rich text. * Check only characters, not tags */ static richTextMaxCharactersValidator(max: number, isTrimText: boolean): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { const characters = this.removeHtmlTagsFromRichText( (isTrimText ? TrimTextUtils.updateByType(c.value, 'richText') : c.value) || '', ); if (characters.length <= max) { return null; } else { return { maxlength: { requiredLength: max, }, }; } }; } /** * Custom validator of password */ static passwordValidator(): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%!^&]).{8,}$/; const password = c.value; if (!password || password.match(regex)) { return null; } else { return { passwordValidator: {} }; } }; } /** * Custom validator for numbers */ static numberTagsValidator(label: string): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { const numberArray = c.value as any[]; if (numberArray) { for (const numberItem of numberArray) { if (isNaN(Number(numberItem))) { return { numberTagsValidator: { fieldTitle: label, }, }; } } return null; } return null; }; } /** * Custom validator for boolean */ static booleanTagsValidator(label: string): ValidatorFn { const booleanAcceptedValues: boolean[] = [true, false]; return (c: AbstractControl): { [key: string]: any } => { const booleanArray = c.value as any[]; if (booleanArray) { for (const booleanItem of booleanArray) { if (!booleanAcceptedValues.includes(booleanItem)) { return { booleanTagsValidator: { fieldTitle: label, }, }; } } return null; } return null; }; } static emailValidator(isTrimText: boolean): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { const email = isTrimText ? TrimTextUtils.updateByType(c.value) : c.value; if ( !email || email.match( /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])*$/, ) ) { return null; } else { return { email: true }; } }; } static childDFAFieldValidator(fieldDefinition: AppTypeFieldModel): ValidatorFn { return (c: AbstractControl): { [key: string]: any } => { if (c.touched && Object.values((c as any).controls).find((v: any) => v.invalid)) { return this.createChildDfaFieldError(fieldDefinition); } else { return null; } }; } static createChildDfaFieldError(fieldDefinition: AppTypeFieldModel): any { return { invalidDFAField: { fieldDefinition, }, }; } static maxLength(maxLength: number, isTrimText: boolean): ValidatorFn { return (control: AbstractControl) => { const value = isTrimText ? TrimTextUtils.updateByType(control.value) : control.value; if (this.hasValidLength(value) && value.length > maxLength) { return { maxlength: { requiredLength: maxLength, actualLength: value.length, }, }; } else { return null; } }; } static minLength(minLength: number, isTrimText: boolean): ValidatorFn { return (control: AbstractControl) => { const value = isTrimText ? TrimTextUtils.updateByType(control.value) : control.value; if (this.isEmptyInputValue(value) || !this.hasValidLength(value)) { return null; } if (value.length < minLength) { return { minlength: { requiredLength: minLength, actualLength: value.length, }, }; } else { return null; } }; } static required(type: OcFieldType, isTrimText: boolean): ValidatorFn { return (control: AbstractControl) => { let value = isTrimText ? TrimTextUtils.updateByType(control.value, type) : control.value; if (type === 'richText') { value = this.removeHtmlTagsFromRichText(value || ''); } if (this.isEmptyInputValue(value)) { return { required: true, }; } else { return null; } }; } static hasValidLength(value: any): boolean { return value !== null && typeof value.length === 'number'; } static isEmptyInputValue(value: any): boolean { return value === null || value.length === 0; } static removeHtmlTagsFromRichText(text: string): string { return text.replace(/(<[^>]*>)|(&nbsp)/g, ''); } }
mukesh-openchannel/angular-template-libraries
src/login.stories.ts
<reponame>mukesh-openchannel/angular-template-libraries import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { ComponentsUserLoginModel, OcLoginComponent } from '@openchannel/angular-common-components/src/lib/auth-components'; import { action } from '@storybook/addon-actions'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { FormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { ERROR_MESSAGES_STORY_PROVIDER } from './utils.model'; /** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */ const modules: NgModule = { imports: [OcCommonLibModule, BrowserAnimationsModule, RouterTestingModule, FormsModule], providers: [ERROR_MESSAGES_STORY_PROVIDER], }; const loginEmpty = new ComponentsUserLoginModel(); const loginFilled = new ComponentsUserLoginModel(); loginFilled.email = '<EMAIL>'; loginFilled.password = '<PASSWORD>#'; loginFilled.isChecked = true; export default { title: 'Login [BEM]', component: OcLoginComponent, decorators: [moduleMetadata(modules)], }; const LoginComponent = (args: OcLoginComponent) => ({ component: OcLoginComponent, moduleMetadata: modules, props: args, }); const defaultProps = { submit: action('clicked event'), forgotPwdUrl: 'forgotPwd', signupUrl: 'signup', companyLogoUrl: 'assets/angular-common-components/logo-company.png', loginModelChange: action('model changed'), }; export const EmptyLogin = LoginComponent.bind({}); EmptyLogin.args = { ...defaultProps, loginModel: loginEmpty, }; export const FilledLogin = LoginComponent.bind({}); FilledLogin.args = { ...defaultProps, loginModel: loginFilled, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-multi-select-checkbox-list/oc-multi-select-checkbox-list.component.ts
<reponame>mukesh-openchannel/angular-template-libraries import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; import { DropdownItem, DropdownItemType } from '../model/multi-select-checkbox.model'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; interface LocalDropdownItem extends DropdownItem { selected: boolean; } /** * Multi select checkbox list component. Represent input for search tags by a list of checkboxes. * @example <oc-multi-select-checkbox-list (selectedItemsOutput)="yourFunction($event)" [itemsArray]="['1']" [defaultItemsArray]="['1']"> */ @Component({ selector: 'oc-multi-select-checkbox-list', templateUrl: './oc-multi-select-checkbox-list.component.html', styleUrls: ['./oc-multi-select-checkbox-list.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => OcMultiSelectCheckboxListComponent), multi: true, }, ], }) export class OcMultiSelectCheckboxListComponent implements OnInit, ControlValueAccessor { /** * Sets an array which contains all dropdown items. * @type {DropdownItemType[]}. */ @Input() set itemsArray(items: DropdownItemType[]) { this.checkboxItemsArray = this.mapToArrayWithDropdownItem(items); } /** * Sets an array which contains all default dropdown items. * @type {DropdownItemType[]}. */ @Input() set defaultItemsArray(items: DropdownItemType[]) { this.defaultCheckboxItemsArray = this.mapToArrayWithDropdownItem(items); } /** * Sets result items array value. * Updates component data. */ @Input() set value(items: DropdownItemType[]) { this.checkboxItemsArray.forEach(item => (item.selected = false)); this.mapToArrayWithDropdownItem(items).forEach(selectedItem => this.selectItemStatus(selectedItem, false)); this.updateComponentData(); } /** * Event emitter, passes checked items when components updates. */ @Output() readonly selectedItemsOutput: EventEmitter<DropdownItemType[]> = new EventEmitter<DropdownItemType[]>(); checkboxItemsArray: LocalDropdownItem[] = []; defaultCheckboxItemsArray: LocalDropdownItem[] = []; disabled: boolean = false; ngOnInit(): void { if (this.defaultCheckboxItemsArray.length > 0) { this.defaultCheckboxItemsArray.forEach(defaultItem => this.selectItemStatus(defaultItem)); } this.updateComponentData(); } /** * Takes itemsArray or defaultItemsArray as a parameter. * Calls createDropDownItem method for each item. * Returns an array of items with LocalDropdownItem type. */ mapToArrayWithDropdownItem(rawItems: DropdownItemType[] = []): LocalDropdownItem[] { return (rawItems || []).map(item => this.createDropDownItem(item)); } /** * Checks for existing values of each item. * Sets 'selected' property as false. */ createDropDownItem(item: DropdownItemType | any): LocalDropdownItem { if (item !== null && item !== undefined) { if (item.hasOwnProperty('label') && item.hasOwnProperty('value')) { return { ...item, selected: false, }; } else if (typeof item === 'number' || typeof item === 'string') { return { label: item, value: item, selected: false, }; } } } /** * A group of methods to check changes of selected values. * updateSelectValueForItem method - finds a current selected item if it exists. * Checks if current item is selected. */ switchItemStatus(item: LocalDropdownItem, withOnChange: boolean = true): void { this.updateSelectValueForItem(item, !item.selected, withOnChange); } selectItemStatus(item: LocalDropdownItem, withOnChange: boolean = true): void { this.updateSelectValueForItem(item, !item.selected, withOnChange); } updateSelectValueForItem(item: DropdownItem, selectedValue: boolean, withOnChange: boolean = true): void { const selectItem = this.checkboxItemsArray.find(resultItem => resultItem.label === item.label); if (selectItem) { selectItem.selected = selectedValue; if (withOnChange) { this.updateComponentData(); } } } /** * Calls this function with new value. * When user writes something in the component, it needs to know that new data has entered the control. */ registerOnChange(onChange: (value: any) => void): void { this.onChange = onChange; } /** * Calls this function when user leaves chosen component. * It is needed for validation. */ registerOnTouched(onTouched: () => void): void { this.onTouched = onTouched; } /** * (Optional) * The method will be called by the control when the [disabled] state changes. */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } /** * This method will be called by the control to pass the value to our component. * It is used if the value is changed through the code outside * (setValue or changing the variable that ngModel is tied to), * as well as to set the initial value. */ writeValue(value: any[]): void { this.mapToArrayWithDropdownItem(value).forEach(item => this.selectItemStatus(item)); } /** * Updates component filters and result value. */ private updateComponentData(): void { const selectedItems = this.checkboxItemsArray.filter(item => item.selected).map(item => item.value); this.onChange(selectedItems); this.selectedItemsOutput.emit(selectedItems); } private onTouched = () => { // nothing to do }; private onChange: (value: any) => void = () => { // nothing to do }; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/oc-activation/oc-activation.component.spec.ts
<filename>projects/angular-common-components/src/lib/auth-components/oc-activation/oc-activation.component.spec.ts<gh_stars>0 import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcActivationComponent } from './oc-activation.component'; import { FormsModule } from '@angular/forms'; import { Location } from '@angular/common'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { By } from '@angular/platform-browser'; import { MockButtonComponent, MockErrorComponent, MockHeadingTagDirective, MockInputComponent, MockLabelComponent, MockRoutingComponent, } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcActivationComponent', () => { let component: OcActivationComponent; let fixture: ComponentFixture<OcActivationComponent>; let location: Location; let router: Router; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ OcActivationComponent, MockLabelComponent, MockErrorComponent, MockButtonComponent, MockInputComponent, MockRoutingComponent, MockHeadingTagDirective, ], imports: [ FormsModule, RouterTestingModule.withRoutes([ { path: 'resend-activation', component: MockRoutingComponent }, { path: 'signup', component: MockRoutingComponent }, ]), ], }).compileComponents(); router = TestBed.inject(Router); location = TestBed.inject(Location); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcActivationComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should redirect to resend activation url', async () => { component.resendActivationUrl = 'resend-activation'; fixture.detectChanges(); const reactivation: HTMLLinkElement = fixture.debugElement.query(By.css('#reactivation')).nativeElement; reactivation.click(); await fixture.whenStable().then(() => { expect(location.path()).toEqual('/resend-activation'); }); }); it('should redirect to sign up page', async () => { component.signupUrl = 'signup'; fixture.detectChanges(); const signup: HTMLLinkElement = fixture.debugElement.query(By.css('#signup')).nativeElement; signup.click(); await fixture.whenStable().then(() => { expect(location.path()).toEqual('/signup'); }); }); it('should emit false value on form button click', () => { component.process = false; jest.spyOn(component.buttonClick, 'emit'); fixture.detectChanges(); const button = fixture.debugElement.query(By.css('oc-button')).nativeElement; button.click(); expect(component.buttonClick.emit).toHaveBeenCalledWith(false); }); it('button should not emmit submit when process is on', () => { component.process = true; jest.spyOn(component.buttonClick, 'emit'); fixture.detectChanges(); const button = fixture.debugElement.query(By.css('oc-button')).nativeElement; button.click(); expect(component.buttonClick.emit).toHaveBeenCalledTimes(0); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/management-components/models/menu-user-grid.model.ts
import { SortField } from '../oc-menu-user-grid/oc-menu-user-grid.component'; /** * Config for setting current sort icon direction (up or down). Used in {@link OcMenuUserGridComponent#sortOptions}. * * Values:<br> * -1 => sort icon to down.<br> * null => sort icon to down.<br> * 1 => sort icon to up.<br> */ export type UserGridSortOrder = { [name in SortField]: 1 | -1 | null; }; /** * New sort config, after click by sort icon. * Used in {@link OcMenuUserGridComponent#sortOptionsChosen} */ export type UserSortChosen = { /** New sort config. */ sortOptions: UserGridSortOrder; /** Updated column ID. */ changedSortOption: SortField; };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-radio-button/oc-radio-button.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { OcRadioButtonComponent } from './oc-radio-button.component'; import { By } from '@angular/platform-browser'; import { TransformTextPipe } from '@openchannel/angular-common-components/src/lib/common-components'; describe('OcRadioButtonComponent', () => { let component: OcRadioButtonComponent; let fixture: ComponentFixture<OcRadioButtonComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [OcRadioButtonComponent, TransformTextPipe], }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OcRadioButtonComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should set the Label text', () => { component.labelText = 'Test label'; fixture.detectChanges(); const label = fixture.debugElement.query(By.css('.form-radio-button__label')).nativeElement; expect(label.textContent.trim()).toEqual('Test label'); }); it('should contain value', () => { component.value = 'test'; fixture.detectChanges(); component.writeValue('test'); fixture.detectChanges(); expect(component.radioButtonValue).toEqual('test'); expect(component.isChecked).toEqual(true); }); it('should call onChange with value', async () => { component.value = 'test'; fixture.detectChanges(); const onChangeFunc = jest.fn(); component.registerOnChange(onChangeFunc); const radio = fixture.debugElement.query(By.css('input')).nativeElement; radio.click(); expect(onChangeFunc).toHaveBeenCalled(); expect(onChangeFunc.mock.calls[0][0]).toBe('test'); }); it('should disable the component', () => { component.setDisabledState(true); fixture.detectChanges(); expect(component.disabled).toEqual(true); }); });
mukesh-openchannel/angular-template-libraries
src/review-list.stories.ts
import { OcRatingComponent, OCReviewDetails, OcReviewListComponent, } from '@openchannel/angular-common-components/src/lib/market-components'; import { OcButtonComponent } from '@openchannel/angular-common-components/src/lib/common-components'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { AngularSvgIconModule } from 'angular-svg-icon'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NgxSpinnerModule } from 'ngx-spinner'; import { moduleMetadata } from '@storybook/angular'; const modules = { imports: [NgbModule, AngularSvgIconModule.forRoot(), HttpClientTestingModule, NgxSpinnerModule], declarations: [OcRatingComponent, OcButtonComponent], }; const appReview1 = new OCReviewDetails(); appReview1.rating = 5; appReview1.review = 'We love this app. very useful and easy to use!'; appReview1.reviewOwnerName = 'Jon from Sales CRM'; const appReview2 = new OCReviewDetails(); appReview2.rating = 3; appReview2.review = 'Great Support, had a few problem first but they took ' + 'care of everything and the whole team is running smuthly.'; appReview2.reviewOwnerName = 'Best Accounting'; const appReview3 = new OCReviewDetails(); appReview3.rating = 4; appReview3.review = 'I have tried a lot of App. and this one has helped me communicate faster with my' + ' entire team. I would definitely recommend it.'; appReview3.reviewOwnerName = '<NAME>.'; const appReview4 = new OCReviewDetails(); appReview4.rating = 2; appReview4.review = 'I tried app. The app is good. But not recommended'; appReview4.reviewOwnerName = '<NAME>.'; export default { title: 'Review List [BEM]', component: OcReviewListComponent, decorators: [moduleMetadata(modules)], argTypes: { writeAReview: { action: 'New Review button has been clicked' } }, }; const ReviewListComponent = (args: OcReviewListComponent) => ({ component: OcReviewListComponent, moduleMetadata: modules, props: args, }); export const Empty = ReviewListComponent.bind({}); Empty.args = { reviewListTitle: 'Most recent reviews', reviewsList: [], noReviewMessage: 'No Review for this app', }; export const SomeReviews = ReviewListComponent.bind({}); SomeReviews.args = { reviewsList: [appReview1], totalReview: 1, maxReviewDisplay: 3, }; export const All = ReviewListComponent.bind({}); All.args = { reviewsList: [appReview1, appReview2, appReview3, appReview4, appReview1, appReview2], totalReview: 7, maxReviewDisplay: 4, }; export const CanNotWriteANewReview = ReviewListComponent.bind({}); CanNotWriteANewReview.args = { reviewsList: [appReview1], totalReview: 7, maxReviewDisplay: 4, allowWriteReview: false, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/model/social-link.model.ts
export class SocialLink { link: string; iconSrc: string; iconAlt: string; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-sidebar/oc-sidebar.component.spec.ts
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { OcSidebarComponent } from './oc-sidebar.component'; import { Component, Input, SimpleChanges } from '@angular/core'; import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap'; import { RouterTestingModule } from '@angular/router/testing'; import { MockButtonComponent, MockHeadingTagDirective } from '@openchannel/angular-common-components/src/mock/mock'; import { SidebarValue } from '../model/components-basic.model'; import { By } from '@angular/platform-browser'; @Component({ selector: 'svg-icon', template: '', }) export class MockSvgIconComponent { @Input() src: string = ''; } const filters: SidebarValue[] = [ { id: 'cat1', label: 'Category 1', sort: '', query: '', description: '', checked: false, values: [], }, { id: 'cat2', label: 'Category 2', checked: false, values: [], sort: '', query: '', description: '', }, { id: 'cat3', label: 'Category 3', checked: false, expanded: false, sort: '', query: '', description: '', values: [ { id: 'sub1', label: 'Subcategory 1', checked: false, sort: '', query: '', description: '', values: [], }, { id: 'sub2', label: 'Subcategory 2', checked: false, sort: '', query: '', description: '', values: [], }, ], }, { id: 'cat4', label: 'Category 4', checked: true, sort: '', query: '', description: '', values: [], }, { id: 'cat5', label: 'Category 5', checked: false, sort: '', query: '', description: '', values: [], }, ]; describe('OcSidebarComponent', () => { let component: OcSidebarComponent; let fixture: ComponentFixture<OcSidebarComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcSidebarComponent, MockSvgIconComponent, MockHeadingTagDirective, MockButtonComponent], imports: [NgbCollapseModule, RouterTestingModule.withRoutes([])], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcSidebarComponent); component = fixture.componentInstance; component.sidebarModel = filters; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should collapse sublist', () => { const expandableList = fixture.debugElement.queryAll(By.css('.oc-sidebar__list-item-wrapper'))[2].nativeElement; expandableList.click(); fixture.detectChanges(); const sublist = fixture.debugElement.query(By.css('.oc-sidebar__sublist')); expect(sublist).toBeTruthy(); }); it('should change button type', () => { component.threshold = 2; const changes: SimpleChanges = { threshold: { previousValue: 10, currentValue: 2, firstChange: true, isFirstChange(): boolean { return false; }, }, }; component.toggleListButtonType = 'primary'; // tslint:disable-next-line:no-lifecycle-call component.ngOnChanges(changes); fixture.detectChanges(); const button = fixture.debugElement.query(By.css('.oc-sidebar__toggle-button')); expect(component.toggleListButtonType).toEqual('primary'); expect(button).toBeTruthy(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-multi-select-list/oc-multi-select-list.component.spec.ts
<reponame>mukesh-openchannel/angular-template-libraries<gh_stars>0 import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { OcMultiSelectListComponent } from './oc-multi-select-list.component'; import { DropboxMockComponent, TagElementMockComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcMultiSelectListComponent', () => { let component: OcMultiSelectListComponent; let fixture: ComponentFixture<OcMultiSelectListComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcMultiSelectListComponent, TagElementMockComponent, DropboxMockComponent], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcMultiSelectListComponent); component = fixture.componentInstance; component.availableItemsList = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7']; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should contain items', () => { expect(component.availableItems.length).toBeGreaterThan(0); }); it('should set result items', () => { component.value = ['item2', 'item1']; component.label = 'Test Multiselect'; fixture.detectChanges(); expect(component.resultItems[0]).toEqual('item2'); expect(component.resultItems[1]).toEqual('item1'); expect(component.resultItems.length).toEqual(2); }); it('should remove result items', () => { component.value = ['item2', 'item1']; fixture.detectChanges(); component.removeItem(1); expect(component.resultItems[0]).toEqual('item2'); expect(component.resultItems[1]).toBeUndefined(); expect(component.resultItems.length).toEqual(1); }); it('should call onChange with value', async () => { const onChangeFunc = jest.fn(); component.registerOnChange(onChangeFunc); component.addTagToResultList('item4'); expect(onChangeFunc).toHaveBeenCalled(); expect(onChangeFunc.mock.calls[0][0]).toEqual(['item4']); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/directive/heading-tag.directive.ts
import { Directive, ElementRef, Input, OnChanges, Renderer2, SimpleChanges } from '@angular/core'; import { HeadingTag } from '../model/heading-tag.interface'; @Directive({ selector: '[headingTag]', }) export class HeadingTagDirective implements OnChanges { @Input() headingTag: HeadingTag; @Input() set headingTagContent(content: string) { this._headingTagContent = content; this._staticContent = false; } private _staticContent = true; private _headingTagContent; private _oldHtmlElement: HTMLHeadingElement = null; constructor(private renderer: Renderer2, private el: ElementRef) {} ngOnChanges(changes: SimpleChanges): void { const currentHtmlTag: HTMLHeadingElement = this._oldHtmlElement || this.el.nativeElement; if ( (changes.headingTag && changes.headingTag.currentValue !== currentHtmlTag.localName) || (!this._staticContent && this._headingTagContent !== currentHtmlTag.innerText) ) { this.modifyHtmlTag(currentHtmlTag); } } modifyHtmlTag(currentHtmlTag: HTMLHeadingElement): void { // Get parent of the original heading tag const parent = currentHtmlTag.parentNode; // Create new heading tag const newHeadingTag = this.renderer.createElement(this.headingTag); // update text this.renderer.appendChild(newHeadingTag, this.renderer.createText(this._headingTagContent || currentHtmlTag.innerText)); // copy classes (currentHtmlTag.className.split(' ') || []).forEach(oldClass => this.renderer.addClass(newHeadingTag, oldClass)); // Add new heading tag, just before the input this.renderer.insertBefore(parent, newHeadingTag, currentHtmlTag); // Remove the old heading tag this.renderer.removeChild(parent, currentHtmlTag); this._oldHtmlElement = newHeadingTag; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/users.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Page } from '../model/api/page.model'; import { HttpRequestService } from './http-request-services'; import { UserCompanyModel } from '../model/api/user.model'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { HttpHeaders } from '@angular/common/http'; import { TypeFieldModel, TypeModel } from '../model/api/type-model'; import { toString } from 'lodash'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting and modifying user model.<br> * * Documentation: <a href="https://support.openchannel.io/documentation/api/#439-users">Openchannel API</a><br> * * Endpoints:<br> * * GET 'v2/users/all'<br> * * GET 'v2/users/this'<br> * * PATCH 'v2/users/this'<br> * * GET 'v2/userTypes/{type}'<br> * * GET 'v2/userTypes'<br> * */ @Injectable({ providedIn: 'root', }) export class UsersService { constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Getting data about non-developer user's company * * @returns {Observable<UserCompanyModel>} Observable<UserCompanyModel> * * ### Example *`` * getUserCompany() *`` */ getUserCompany(): Observable<UserCompanyModel> { return this.httpService.get(`${this.apiPaths.users}/this`); } /** * * Description: Saving data of non-developer user's company * * @param {any} companyData (required) new company fields data * @returns {Observable<any>} Observable<any> * * ### Example *`` * updateUserCompany(any) *`` */ updateUserCompany(companyData: any): Observable<any> { return this.httpService.patch(`${this.apiPaths.users}/this`, companyData); } /** * * Description: Getting Fields definition for current user type * * @param {string} type (required) User Type * @param {any} httpOptions (optional) * @returns {Observable<any>} Observable<any> * * ### Example *`` * getUserTypeDefinition('developer', {"Authorization": "Bearer <KEY>"}) *`` */ getUserTypeDefinition(type: string, httpOptions?: any): Observable<any> { return this.httpService.get(`${this.apiPaths.userTypes}/${type}`, httpOptions); } /** * * Description: Get all user types with pagination * * @param {number} pageNumber - (optional) Current page index. Starts from >= 1. * @param {number} pageLimit - (optional) Count user types into response. Starts from >= 1. * @param {string} sort - (optional) Sort user types by specific field. * @param {string} query - (optional) Your specific search query. * @param {HttpHeaders} headers - (optional) * @returns {Observable<Page<TypeModel<TypeFieldModel>>>} Observable<Page<TypeModel<TypeFieldModel>>> * * ### Example *`` * getUserTypes(1, 10, "{"name": 1}", "{"name": {"$in":["first", "second"]}}", {"Authorization": "Bearer <KEY>"}) *`` */ getUserTypes( query?: string, sort?: string, pageNumber?: number, pageLimit?: number, headers?: HttpHeaders, ): Observable<Page<TypeModel<TypeFieldModel>>> { const options: any = { params: new OcHttpParams() .append('query', query) .append('sort', sort) .append('pageNumber', toString(pageNumber)) .append('limit', toString(pageLimit)), }; if (headers) { options.headers = headers; } return this.httpService.get(`${this.apiPaths.userTypes}`, options); } }
mukesh-openchannel/angular-template-libraries
src/rating.stories.ts
<filename>src/rating.stories.ts<gh_stars>0 import { moduleMetadata } from '@storybook/angular'; import { OcRatingComponent } from '@openchannel/angular-common-components/src/lib/market-components'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { AngularSvgIconModule } from 'angular-svg-icon'; import { HttpClientTestingModule } from '@angular/common/http/testing'; const modules = { imports: [AngularSvgIconModule.forRoot(), NgbModule, HttpClientTestingModule], }; export default { title: 'Rating [BEM]', component: OcRatingComponent, decorators: [moduleMetadata(modules)], }; const RatingComponent = (args: OcRatingComponent) => ({ component: OcRatingComponent, moduleMetadata: modules, props: args, }); export const MultiStar = RatingComponent.bind({}); MultiStar.args = { type: 'multi-star', rating: 4, disabled: true, }; export const SingleStar = RatingComponent.bind({}); SingleStar.args = { type: 'single-star', rating: 4.5, reviewCount: 50, }; export const InteractiveRating = RatingComponent.bind({}); InteractiveRating.args = { type: 'multi-star', };
mukesh-openchannel/angular-template-libraries
src/grid-user.stories.ts
<filename>src/grid-user.stories.ts import { moduleMetadata } from '@storybook/angular'; import { OcMenuUserGridComponent, OcManagementComponentsModule, ComponentsUsersGridParametersModel, } from '@openchannel/angular-common-components/src/lib/management-components'; const modules = { imports: [OcManagementComponentsModule], }; export default { title: 'Grid User [BEM]', component: OcMenuUserGridComponent, decorators: [moduleMetadata(modules)], }; const ListGridComponent = (args: OcMenuUserGridComponent) => ({ component: OcMenuUserGridComponent, moduleMetadata: modules, props: args, }); const propsConfig: ComponentsUsersGridParametersModel = { layout: 'table', data: { pages: 50, pageNumber: 1, list: [ { name: '<NAME>', created: new Date().getTime() - 10 * 24 * 60 * 60 * 1000, email: '<EMAIL>', userId: 'undefined_id', userAccountId: 'undefined_account_id', type: 'VIEWER', roles: ['VIEWER'], inviteStatus: 'INVITED', customData: { companyName: 'Company', interests: [] }, }, { name: '<NAME>', created: new Date().getTime() - 30 * 24 * 60 * 60 * 1000, email: '<EMAIL>', userId: 'mark_id', userAccountId: 'mark_account_id', type: 'VIEWER', roles: ['VIEWER'], inviteStatus: 'ACTIVE', customData: { companyName: 'Mark Company', interests: [] }, }, { name: '<NAME>', created: new Date().getTime() - 10 * 24 * 60 * 60 * 1000, email: '<EMAIL>', userId: 'johnny_id', userAccountId: 'johnny_account_id', type: 'ADMIN', roles: ['ADMIN'], inviteStatus: 'ACTIVE', customData: { companyName: 'Johnny Company', interests: [] }, }, { name: 'Test', created: new Date().getTime() - 10 * 24 * 60 * 60 * 1000, email: '<EMAIL>', userId: 'jon_id', userAccountId: 'jon_account_id', type: 'VIEWER', roles: ['VIEWER'], inviteStatus: 'INVITED', customData: { companyName: 'Jon Company', interests: [] }, }, ], count: 50, }, options: ['EDIT', 'DELETE'], }; export const UsersGrid = ListGridComponent.bind({}); UsersGrid.args = { properties: propsConfig, };
mukesh-openchannel/angular-template-libraries
src/select-expandable.stories.ts
import { OcCommonLibModule, OcSelectExpandableComponent } from '@openchannel/angular-common-components/src/lib/common-components'; import { moduleMetadata } from '@storybook/angular'; /** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */ const modules = { imports: [OcCommonLibModule], }; export default { title: 'Expandable Select [BEM]', component: OcSelectExpandableComponent, decorators: [moduleMetadata(modules)], }; const SelectComponent = (args: OcSelectExpandableComponent) => ({ component: OcSelectExpandableComponent, moduleMetadata: modules, props: args, }); export const CollapsedSelect = SelectComponent.bind({}); CollapsedSelect.args = { title: 'App Category', selectModels: [ { label: 'Category 1', checked: false, }, { label: 'Category 2', checked: false, }, { label: 'Category 3', checked: false, }, { label: 'Category 4', checked: true, }, ], }; export const ExpandedSelect = SelectComponent.bind({}); ExpandedSelect.args = { title: 'App Category', isCollapsed: false, collapsedOnInit: false, selectModels: [ { label: 'Category 1', checked: false, }, { label: 'Category 2', checked: false, }, { label: 'Category 3', checked: false, }, { label: 'Category 4', checked: true, }, ], };
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/user-activation-model.ts
export interface UserActivationModel { password: string; email: string; code: string; } export interface UserResetPassword { newPassword: string; code: string; }
mukesh-openchannel/angular-template-libraries
src/dropbox.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { OcDropboxComponent } from '@openchannel/angular-common-components'; const modules = { imports: [OcCommonLibModule], }; export default { title: 'Dropbox search [BEM]', component: OcDropboxComponent, decorators: [moduleMetadata(modules)], argTypes: { selectedItem: { action: 'Get selected' } }, }; const DropboxComponent = (args: OcDropboxComponent) => ({ component: OcDropboxComponent, moduleMetadata: modules, props: args, }); export const DefaultDropbox = DropboxComponent.bind({}); DefaultDropbox.args = { placeHolder: 'Default place holder', items: ['first', 'second', 'third'], clearFormAfterSelect: true, }; export const ScrollDropbox = DropboxComponent.bind({}); ScrollDropbox.args = { placeHolder: 'Default place holder', items: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15'], clearFormAfterSelect: false, }; export const EmptyDropbox = DropboxComponent.bind({}); EmptyDropbox.args = { placeHolder: null, items: null, clearFormAfterSelect: null, };
mukesh-openchannel/angular-template-libraries
src/radio-button.stories.ts
<reponame>mukesh-openchannel/angular-template-libraries import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule, OcRadioButtonComponent } from '@openchannel/angular-common-components/src/lib/common-components'; const modules = { imports: [OcCommonLibModule], }; export default { title: 'Radio Button [BEM]', component: OcRadioButtonComponent, decorators: [moduleMetadata(modules)], }; const RadioButtonComponent = (args: OcRadioButtonComponent) => ({ component: OcRadioButtonComponent, moduleMetadata: modules, props: args, }); export const SimpleRadioButton = RadioButtonComponent.bind({}); SimpleRadioButton.args = { labelText: 'Test Label', radioButtonGroupName: 'test', value: 1, };
mukesh-openchannel/angular-template-libraries
src/title.stories.ts
<filename>src/title.stories.ts<gh_stars>0 import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule, OcTitleComponent } from '@openchannel/angular-common-components/src/lib/common-components'; const modules = { imports: [OcCommonLibModule], }; export default { title: 'Title [BEM]', component: OcTitleComponent, decorators: [moduleMetadata(modules)], }; const TitleComponent = (args: OcTitleComponent) => ({ component: OcTitleComponent, moduleMetadata: modules, props: args, }); export const DefaultTitle = TitleComponent.bind({}); DefaultTitle.args = { title: 'Options', required: true, description: 'Description description description description', }; export const WithoutRequiredTitle = TitleComponent.bind({}); WithoutRequiredTitle.args = { title: 'Options', required: false, description: 'Description description description description', }; export const WithoutDescriptionTitle = TitleComponent.bind({}); WithoutDescriptionTitle.args = { title: 'Options', required: true, }; export const CustomIconTitle = TitleComponent.bind({}); CustomIconTitle.args = { title: 'Options', required: true, infoTitleIconCsv: './assets/angular-common-components/delete.svg', description: 'Description description description description', };
mukesh-openchannel/angular-template-libraries
src/full-image-gallery-view-modal.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { GalleryItem, OcCommonLibModule, OcFullImageGalleryViewModalComponent, } from '@openchannel/angular-common-components/src/lib/common-components'; import { CarouselModule } from 'ngx-owl-carousel-o'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AngularSvgIconModule } from 'angular-svg-icon'; const modules = { imports: [OcCommonLibModule, CarouselModule, BrowserAnimationsModule, AngularSvgIconModule], }; export default { title: 'Full Image Gallery View Modal [BEM]', component: OcFullImageGalleryViewModalComponent, decorators: [moduleMetadata(modules)], parameters: { layout: 'centered', }, }; const imageItem: GalleryItem = { image: 'https://static.zerochan.net/Yakkun.full.1531987.jpg', title: 'Test App Image', description: 'Improve and extend your experience right from your own UI', }; const imageItem2: GalleryItem = { image: 'https://static.zerochan.net/Cola.Gotouryouta.full.1501202.jpg', title: 'Test App Image', description: 'Improve and extend your experience right from your own UI.' + ' Improve and extend your experience right from your own UI. Improve and extend your experience right from your own UI.' + ' Improve and extend your experience right from your own UI', }; const anotherImageItem: GalleryItem = { image: 'https://static.zerochan.net/Wenqing.Yan.full.2318589.jpg', title: 'Test App Image', description: 'Improve and extend your experience right from your own UI. Improve and extend your experience right from your own UI.' + ' Improve and extend your experience right from your own UI. Improve and extend your experience right from your own UI', }; const videoItem: GalleryItem = { video: 'https://youtu.be/L_LUpnjgPso', title: 'Test App Video', description: 'Improve and extend your experience right from your own UI', }; const GalleryModal = (args: OcFullImageGalleryViewModalComponent) => ({ component: OcFullImageGalleryViewModalComponent, moduleMetadata: modules, props: args, }); export const OneImageView = GalleryModal.bind({}); OneImageView.args = { galleryItems: [imageItem, imageItem2, anotherImageItem, videoItem, imageItem], activeItemIdx: 2, showDetails: true, componentIconsPath: { arrowLeft: 'assets/angular-common-components/arrow-left-analog.svg', arrowRight: 'assets/angular-common-components/arrow-right-analog.svg', closeIcon: 'assets/angular-common-components/close-icon.svg', }, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-textarea/oc-textarea.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcTextareaComponent } from './oc-textarea.component'; import { FormsModule } from '@angular/forms'; describe('OcTextareaComponent', () => { let component: OcTextareaComponent; let fixture: ComponentFixture<OcTextareaComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcTextareaComponent], imports: [FormsModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcTextareaComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should contain value', () => { component.writeValue('Test value'); expect(component.textAreaValue).toEqual('Test value'); }); it('should set value', () => { component.value = 'Input value'; expect(component.textAreaValue).toEqual('Input value'); }); it('should contain value in textarea', async () => { component.writeValue('Test value'); const textarea = fixture.nativeElement.querySelector('textarea'); fixture.detectChanges(); await fixture.whenStable().then(() => { expect(textarea.value).toEqual('Test value'); }); }); it('textarea should contain placeholder', async () => { component.placeholder = 'Textarea placeholder'; const textarea = fixture.nativeElement.querySelector('textarea'); fixture.detectChanges(); await fixture.whenStable().then(() => { expect(textarea.placeholder).toEqual('Textarea placeholder'); }); }); it('textarea should contain the rows', () => { component.rows = 4; const textarea = fixture.nativeElement.querySelector('textarea'); fixture.detectChanges(); expect(textarea.rows).toEqual(4); }); it('textarea should be required', () => { component.required = true; const textarea = fixture.nativeElement.querySelector('textarea'); fixture.detectChanges(); expect(textarea.required).toEqual(true); }); it('textarea should be disabled', async () => { component.setDisabledState(true); const textarea = fixture.nativeElement.querySelector('textarea'); fixture.detectChanges(); await fixture.whenStable().then(() => { expect(textarea.disabled).toBeTruthy(); }); }); it('should call onChange with value', async () => { const onChangeFunc = jest.fn(); component.registerOnChange(onChangeFunc); const textarea = fixture.nativeElement.querySelector('textarea'); textarea.value = 'test on change'; textarea.dispatchEvent(new Event('input')); expect(onChangeFunc).toHaveBeenCalled(); expect(onChangeFunc.mock.calls[0][0]).toBe('test on change'); }); it('should call onTouch', async () => { const onTouchedFunc = jest.fn(); component.registerOnTouched(onTouchedFunc); const textarea = fixture.nativeElement.querySelector('textarea'); textarea.value = 'test on change'; textarea.dispatchEvent(new Event('blur')); expect(onTouchedFunc).toHaveBeenCalled(); }); });
mukesh-openchannel/angular-template-libraries
src/invite-user-modal.stories.ts
import { OcCommonLibModule, OcFormComponentsModule, OcInviteModalComponent } from '@openchannel/angular-common-components'; import { moduleMetadata } from '@storybook/angular'; import { of } from 'rxjs'; import { NgModule } from '@angular/core'; import { ERROR_MESSAGES_STORY_PROVIDER } from './utils.model'; const modules: NgModule = { imports: [OcCommonLibModule, OcFormComponentsModule], providers: [ERROR_MESSAGES_STORY_PROVIDER], }; export default { title: 'Invite User modal [BEM]', component: OcInviteModalComponent, decorators: [moduleMetadata(modules)], }; const InviteModal = (args: OcInviteModalComponent) => ({ component: OcInviteModalComponent, moduleMetadata: modules, props: args, }); export const modal = InviteModal.bind({}); modal.args = { modalData: { modalTitle: 'Invite a member', successButtonText: 'Send invite', requestFindUserRoles: of({ list: [ { userRoleId: '2337627gdhwj', }, ], }), requestSendInvite: of(), }, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/public-api.ts
export * from './oc-auth-components.module'; export * from './oc-signup/oc-signup.component'; export * from './oc-resend-activation/oc-resend-activation.component'; export * from './oc-activation/oc-activation.component'; export * from './oc-reset-password/oc-reset-password.component'; export * from './oc-login/oc-login.component'; export * from './oc-forgot-password/oc-forgot-password.component'; export * from './oc-signup-custom/oc-signup-custom.component'; export * from './oc-edit-user-form/oc-edit-user-form.component'; /** Models */ export * from './models/auth-types.model'; export * from './models/oc-edit-user-form.model'; export * from './models/oc-type-definition.model'; export * from './models/signup-router-state.model';
mukesh-openchannel/angular-template-libraries
src/input.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcCheckboxComponent, OcCommonLibModule, OcInputComponent } from '@openchannel/angular-common-components/src/lib/common-components'; /** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */ const modules = { imports: [OcCommonLibModule], }; export default { title: 'Input [BEM]', component: OcInputComponent, decorators: [moduleMetadata(modules)], }; const InputComponent = (args: OcInputComponent) => ({ component: OcInputComponent, moduleMetadata: modules, props: args, }); const CheckboxComponent = (args: OcCheckboxComponent) => ({ component: OcCheckboxComponent, moduleMetadata: modules, props: args, }); export const Text = InputComponent.bind({}); Text.args = { focus: true, }; export const Checkbox = CheckboxComponent.bind({}); Checkbox.args = { labelText: 'Custom Checkbox', requiredIndicator: true, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/directive/ellipsis.directive.ts
<reponame>mukesh-openchannel/angular-template-libraries<filename>projects/angular-common-components/src/lib/common-components/directive/ellipsis.directive.ts import { AfterViewInit, Directive, ElementRef, HostBinding, HostListener, Inject, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Directive({ selector: '[ellipsis]', }) export class EllipsisDirective implements AfterViewInit { @HostBinding('class.ellipsis-directive') ellipsisDirectiveClass = true; /** The native HTMLElement. */ private get el(): HTMLElement { return this.elementRef.nativeElement; } /** The original innerText; */ private innerText: string; constructor(private readonly elementRef: ElementRef, @Inject(PLATFORM_ID) private readonly platformId: any) {} ngAfterViewInit(): void { this.truncate(); } @HostListener('window:resize') onWindowResize(): void { this.truncate(); } getIsTextOverflows(): boolean { return this.el.scrollHeight > this.el.clientHeight; } private truncate(): void { // verify execution context is the browser platform if (!isPlatformBrowser(this.platformId)) { return; } // store the original innerText if (this.innerText === undefined) { this.innerText = this.el.innerText.trim(); } // reset the innerText this.el.innerText = this.innerText; // truncate the text and append the ellipsis let text = this.innerText; while (text.length > 0 && this.getIsTextOverflows()) { text = text.slice(0, -1); this.el.innerText = `${text}…`; } } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/user-account-types.service.ts
import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { Observable } from 'rxjs'; import { Page } from '../model/api/page.model'; import { UserAccountTypeModel } from '../model/api/user-type.model'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting User Account Types.<br> * * Endpoints:<br> * * GET 'v2/userAccountTypes/{type}'<br> * * GET 'v2/userAccountTypes'<br> */ @Injectable({ providedIn: 'root', }) export class UserAccountTypesService { constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Getting user profile fields definition by type * * @param {string} type - (required) type from the user account data * @param {any} httpOptions - (optional) * @returns {Observable<UserAccountTypeModel>} Observable<UserAccountTypeModel> * * ### Example *`` * getUserAccountType("developer", {"Authorization": "Bearer <PASSWORD>"}) *`` */ getUserAccountType(type: string, httpOptions?: any): Observable<UserAccountTypeModel> { return this.httpService.get(`${this.apiPaths.userAccountTypes}/${type}`, httpOptions); } /** * * Description: Get account types list with pagination * * @param {number} pageNumber - (optional) Current page index. Starts from >= 1. * @param {number} limit - (optional) Count types into response. Starts from >= 1. * @param {string} query - (optional) Your specific search query. * @returns {Observable<Page<UserAccountTypeModel>>} Observable<Page<UserAccountTypeModel>> * * ### Example *`` * getUserAccountTypes(1,10,"{"name": {"$in":["first", "second"]}}") *`` */ getUserAccountTypes(pageNumber?: number, limit?: number, query?: string): Observable<Page<UserAccountTypeModel>> { const params = new OcHttpParams().append('pageNumber', String(pageNumber)).append('limit', String(limit)).append('query', query); return this.httpService.get(this.apiPaths.userAccountTypes, { params }); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/portal-components/models/oc-chart.model.ts
<filename>projects/angular-common-components/src/lib/portal-components/models/oc-chart.model.ts import { DropdownItemModel } from '@openchannel/angular-common-components/src/lib/common-components'; /** * Interface for the [Chart]{@link OcChartComponent} component. * Contains of chart layout type, chart data, chart fields and periods. */ export interface ChartStatisticModel { /** * type of the component layout * @default 'standard' */ layout: ChartLayoutTypeModel.standard; /** main chart data */ data: ChartStatisticDataModel; /** fields array that will be used for the dropdown menu */ fields: ChartStatisticFiledModel[]; /** periods array for data switching */ periods: ChartStatisticPeriodModel[]; /** * apps dropdown */ apps?: { activeItem: ChartStatisticAppModel; items: ChartStatisticAppModel[]; }; } /** * Interface for the [Chart]{@link OcChartComponent} component's data. * @example * configExample: ChartStatisticDataModel = { * labelsY: [3, 10, 30, 50], * labelsX: ['Mar', 'Apr', 'May', 'Jun'], * tabularLabels: ['March','April','May','June'] * } */ export interface ChartStatisticDataModel { /** data that will be shown on Y axis */ labelsY: number[]; /** data that will be shown on X axis */ labelsX: string[]; /** * labels that will be shown in tabular data. * It's necessary if `tabular` data view option is applied */ tabularLabels?: string[]; } /** * Interface for the [Chart]{@link OcChartComponent} component's dropdown menu. * Extends the {@link ChartStatisticParameterModel} . * Has `icon` field for the custom dropdown menu item icon. * @example * chartData = { * ... * fields: [ * { * id: 'downloads', * label: 'Downloads', * active: true, * icon: './assets/img/image.png' * }, * { * id: 'reviews', * label: 'Reviews', * icon: './assets/img/image2.png' * } * ] * } */ export interface ChartStatisticFiledModel extends ChartStatisticParameterModel { /** * path to the icon that will be placed near dropdown menu item. * Can be local or url from server. * @example * './assets/img/image.png' * 'https://example.site.com/image.png' */ icon?: string; } /** * Interface for the [Chart]{@link OcChartComponent} component's period radio buttons. * Extends the {@link ChartStatisticParameterModel} . * Has `tabularLabel` field that will be shown as a header of labels column * @example * chartData = { * ... * periods: [ * { * id: 'month', * label: 'Monthly', * active: true, * tabularLabel: 'Month', * }, * { * id: 'day', * label: 'Daily', * tabularLabel: 'Day', * } * ] * } */ export interface ChartStatisticPeriodModel extends ChartStatisticParameterModel { /** field that will be shown as a header of labels column */ tabularLabel?: string; } /** * Interface for the [Chart]{@link OcChartComponent} component's emitter which triggering on period or field changes. */ export interface ChartOptionsChange { /** object of chosen field */ field: ChartStatisticFiledModel; /** object of chosen period */ period: ChartStatisticPeriodModel; selectedApp?: ChartStatisticAppModel; } /** * Basic interface for the [Chart]{@link OcChartComponent} component's [Field model]{@link ChartStatisticFiledModel} * and [Period model]{@link ChartStatisticPeriodModel} */ export interface ChartStatisticParameterModel extends DropdownItemModel { /** unique identificator of the parameter */ id: string; /** label text of the parameter that will be shown */ label: string; /** marks parameter as chosen */ active?: boolean; } export interface ChartStatisticAppModel extends DropdownItemModel { id: string; } export enum ChartLayoutTypeModel { standard = 'standard', }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-multi-select-list/oc-multi-select-list.component.ts
import { Component, forwardRef, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { difference } from 'lodash'; /** * Multi select list component. Represent input for search tags by name and tags list. * * @example <oc-multi-select-list [(ngModel)]="resultList" [availableItemsList]="['1','2','3']" [label]="'LABEL'" [description]="'Description'" [defaultItems]="['1']"> */ @Component({ selector: 'oc-multi-select-list', templateUrl: './oc-multi-select-list.component.html', styleUrls: ['./oc-multi-select-list.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => OcMultiSelectListComponent), multi: true, }, ], }) export class OcMultiSelectListComponent implements OnInit, ControlValueAccessor, OnChanges { /** * (Required) * List of available items to choose in dropbox */ @Input() set availableItemsList(value: any[]) { this.availableItems = value; } /** * Set result items array value */ @Input() set value(val: any[]) { this.resultItems = val; this.onChange(this.resultItems); } /** Label of the Component */ @Input() label: string = ''; /** Placeholder in oc-dropbox input */ @Input() placeholder: string = ''; /** Label text of the Oc-Tag-Component */ @Input() tagTooltipLabelText: string = ''; /** * Description for all list items. */ @Input() description: string = ''; /** * (optional) * List of items for automatically adding to the user tags list. * Default: `[]` */ @Input() defaultItems: string[] = []; availableItems: string[] = []; resultItems: any[] = []; // tags for DropBox dropBoxItems = []; ngOnInit(): void { this.applyDefaultItems(); this.dropBoxItems = this.findAvailableDropBoxItems(); } ngOnChanges(changes: SimpleChanges): void { if (difference(changes.availableItemsList.currentValue, changes.availableItemsList.previousValue)?.length > 0) { this.dropBoxItems = this.findAvailableDropBoxItems(); } } /** * Set default items list to the result list */ applyDefaultItems(): void { this.defaultItems.forEach(tag => this.addTagToResultList(tag)); } /** * Remove item from selected items list by index * @param index index of the chosen item */ removeItem(index: number): void { this.resultItems.splice(index, 1); this.updateComponentData(); } /** * Adding Selected item to the result item list array * @param item selected item */ addTagToResultList(item: string): void { const itemNormalized = item.trim(); if (!this.existTagInResultList(itemNormalized)) { this.resultItems = [...this.resultItems, item]; this.updateComponentData(); } } /** * Filter drop box items that are not yet selected */ findAvailableDropBoxItems(): string[] { return this.availableItems.filter(tag => !this.existTagInResultList(tag)); } /** * Check is tag already selected */ existTagInResultList(currentTag: string): boolean { const tagNormalized = currentTag.toLowerCase(); return this.resultItems.filter(t => tagNormalized === t.toLowerCase()).length > 0; } /** * Update component filters and result value */ updateComponentData(): void { this.dropBoxItems = this.findAvailableDropBoxItems(); this.onChange(this.resultItems); } /** * Calls this function with new value. When user wrote something in the component * It needs to know that new data has been entered in the control. */ registerOnChange(onChange: (value: any) => void): void { this.onChange = onChange; } /** * Calls this function when user left chosen component. * It needs for validation */ registerOnTouched(onTouched: () => void): void { this.onTouched = onTouched; } /** * (Optional) * the method will be called by the control when the [disabled] state changes. */ // prettier-ignore setDisabledState(isDisabled: boolean): void { // NOSONAR } /** * this method will be called by the control to pass the value to our component. * It is used if the value is changed through the code outside * (setValue or changing the variable that ngModel is tied to), * as well as to set the initial value. */ writeValue(value: any): void { this.resultItems = value && value.length ? value.filter(tag => tag && tag.trim().length > 0) : []; this.dropBoxItems = this.findAvailableDropBoxItems(); } onTouched = () => { // nothing to do }; private onChange: (value: any) => void = () => { // nothing to do }; }
mukesh-openchannel/angular-template-libraries
src/utils.model.ts
import { Provider } from '@angular/core'; import { AbstractErrorMessageConfiguration, DefaultErrorMessageConfiguration, } from '@openchannel/angular-common-components/src/lib/common-components'; // --- providers --- export const ERROR_MESSAGES_STORY_PROVIDER: Provider = { provide: AbstractErrorMessageConfiguration, useValue: new DefaultErrorMessageConfiguration(), };
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/config.service.ts
<filename>projects/angular-common-services/src/lib/service/config.service.ts<gh_stars>0 import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { BehaviorSubject, Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: Service for setting up site config.<br> * * Methods: * * loadMarketUrl * * getMarketUrl * */ @Injectable({ providedIn: 'root', }) export class ConfigService { private marketUrl: string; constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Get market url * * @returns {Observable<string>} `Observable<string> * * ### Example * * `getMarketUrl();` */ getMarketUrl(): Observable<string> { if (!this.marketUrl) { return this.loadMarketUrl(); } return new BehaviorSubject(this.marketUrl).asObservable(); } /** * * Description: Set up market url * * @returns {Observable<string>} `Observable<string> * * ### Example * * `loadMarketUrl();` */ private loadMarketUrl(): Observable<string> { return this.httpRequest .get(`${this.apiPaths.config}/market-url`, { responseType: 'text', withCredentials: true, }) .pipe(tap(x => (this.marketUrl = x))); } }
mukesh-openchannel/angular-template-libraries
src/recommended-apps.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { OcMarketComponentsModule, OcRecommendedAppsComponent } from '@openchannel/angular-common-components/src/lib/market-components'; import { OcNumberComponent } from '@openchannel/angular-common-components/src/lib/form-components'; import { StatElement } from '@openchannel/angular-common-components/src/lib/common-components'; const modules = { imports: [OcMarketComponentsModule, BrowserAnimationsModule, RouterTestingModule], }; const stat: StatElement = { '90day': 10, '30day': 20, total: 20, }; const app = { appId: '344gf-s3j-gi3423', icon: '', name: 'Test App', model: [ { type: 'recurring', price: 5, trial: 1, license: 'single', modelId: '23235hfg4', currency: 'EUR', billingPeriod: 'monthly', }, ], rating: 4.2, reviewCount: 20, summary: 'Some test summary', description: 'Some Description', lastUpdated: new Date(), version: 1.1, safeName: ['test-app'], developerId: '44<PASSWORD>', submittedDate: new Date(), created: new Date().getMonth() - 2, status: { value: '', lastUpdated: 1.1, modifiedBy: '', reason: '', }, statistics: { views: stat, downloads: stat, developerSales: stat, totalSales: stat, ownerships: stat, reviews: stat, }, isLive: true, }; const app1 = { ...app }; app1.description = 'With this plugin you can communicate with your teammates any time'; app1.summary = 'With this plugin you can communicate with your teammates any time'; app1.icon = './assets/angular-common-components/standard-app-icon.svg'; app1.name = 'Plugin'; app1.model[0].type = 'free'; app1.rating = 3.5; app1.reviewCount = 12; const app2 = { ...app }; app2.description = app2.summary = 'Integrate directly with your account and make customer updates a breeze'; app2.icon = './assets/angular-common-components/standard-app-icon.svg'; app2.name = 'Application'; app2.model[0].price = 11.99; app2.rating = 0; app2.reviewCount = 0; const app3 = { ...app }; app3.description = app2.summary = 'Improve and extend your experience right from your own UI'; app3.icon = './assets/angular-common-components/standard-app-icon.svg'; app3.name = 'Integration'; app3.model[0].price = 4.99; app3.rating = 4.9; app3.reviewCount = 87; export default { title: 'Recommended Apps [BEM]', component: OcRecommendedAppsComponent, decorators: [moduleMetadata(modules)], }; const RecommendedAppsComponent = (args: OcNumberComponent) => ({ component: OcRecommendedAppsComponent, moduleMetadata: modules, props: args, }); export const EmptyList = RecommendedAppsComponent.bind({}); EmptyList.args = { appList: [], noAppMessage: 'No App Found', recommendedAppTitle: 'Recommended For You', }; export const RecommendedAppsWithData = RecommendedAppsComponent.bind({}); RecommendedAppsWithData.args = { appList: [app1, app2, app3], noAppMessage: 'No App Found', recommendedAppTitle: 'Recommended For You', };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-profile-navbar/oc-profile-navbar.component.spec.ts
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import { OcProfileNavbarComponent } from './oc-profile-navbar.component'; import {By} from '@angular/platform-browser'; describe('OcProfileNavbarComponent', () => { let component: OcProfileNavbarComponent; let fixture: ComponentFixture<OcProfileNavbarComponent>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ OcProfileNavbarComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(OcProfileNavbarComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show data', () => { component.username = 'Test Username'; component.initials = 'TU'; component.role = 'admin'; fixture.detectChanges(); const usernameField = fixture.debugElement.query(By.css('.profile-navbar__username')).nativeElement; const initialsField = fixture.debugElement.query(By.css('.profile-navbar__initials')).nativeElement; const roleField = fixture.debugElement.query(By.css('.profile-navbar__role')).nativeElement; expect(usernameField.textContent).toEqual('Test Username'); expect(initialsField.textContent).toEqual('TU'); expect(roleField.textContent).toEqual('admin'); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-app-description/oc-app-description.component.spec.ts
<reponame>mukesh-openchannel/angular-template-libraries import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcAppDescriptionComponent } from './oc-app-description.component'; import { FormsModule } from '@angular/forms'; import { OcCommonLibModule } from '../../common-components/'; import { By } from '@angular/platform-browser'; import { MockHeadingTagDirective } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcAppDescriptionComponent', () => { let component: OcAppDescriptionComponent; let fixture: ComponentFixture<OcAppDescriptionComponent>; let descriptionElement: Element; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcAppDescriptionComponent, MockHeadingTagDirective], imports: [FormsModule, OcCommonLibModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcAppDescriptionComponent); component = fixture.componentInstance; descriptionElement = fixture.debugElement.query(By.css('#ocAppDescriptionTruncatedTextId')).nativeElement; }); it('should create', () => { expect(component).toBeTruthy(); }); it('description normal value', () => { const description = 'Description'; setDescriptionText(description); expect(getDescriptionText()).toEqual(description); }); it('description non null', () => { const description = null; setDescriptionText(description); expect(getDescriptionText()).toEqual(''); }); it('description non undefined', () => { const description = undefined; setDescriptionText(description); expect(getDescriptionText()).toEqual(''); }); it('switch full description by click', () => { component.appDescription = '1234567890'; component.truncateTextLength = 5; fixture.detectChanges(); const description = fixture.nativeElement.querySelector('#ocAppDescriptionTruncatedTextId'); const switchButton = fixture.nativeElement.querySelector('#ocAppDescriptionShowMoreId'); expect(switchButton.textContent).toEqual('Show more'); expect(description.textContent).toEqual('12345...'); switchButton.click(); fixture.detectChanges(); expect(switchButton.textContent).toEqual('Show less'); expect(description.textContent).toEqual('1234567890'); }); it('description without any html tags', () => { component.appDescription = '<a>1234567890</a>'; component.truncateTextLength = 5; fixture.detectChanges(); const description = fixture.nativeElement.querySelector('#ocAppDescriptionTruncatedTextId'); const switchButton = fixture.nativeElement.querySelector('#ocAppDescriptionShowMoreId'); expect(switchButton.textContent).toEqual('Show more'); expect(description.textContent).toEqual('12345...'); }); function setHeaderText(header: string): void { component.header = header; fixture.detectChanges(); } function setDescriptionText(description: string): void { component.appDescription = description; fixture.detectChanges(); } function getDescriptionText(): string { return fixture.nativeElement.querySelector('#ocAppDescriptionTruncatedTextId').innerHTML; } });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-recommended-apps/oc-recommended-apps.component.ts
<reponame>mukesh-openchannel/angular-template-libraries import { Component, EventEmitter, Input, Output, TemplateRef } from '@angular/core'; import { FullAppData, HeadingTag } from '@openchannel/angular-common-components/src/lib/common-components'; import { get } from 'lodash'; /** * Recommended apps component. Renders a list of applications, tha are recommended for a user. * Located on the single application page after its description. * Shows brief information via app cards. */ @Component({ selector: 'oc-recommended-apps', templateUrl: './oc-recommended-apps.component.html', styleUrls: ['./oc-recommended-apps.component.css'], }) export class OcRecommendedAppsComponent { /** * Array of the Recommended apps. * Must contains of fields: `name`, `model`, * `rating`, `reviewCount`, `summary` or `description`. * @type {FullAppData[]}. */ @Input() appList: FullAppData[] = []; /** * Message that will be shown when no apps. * @type {string}. */ @Input() noAppMessage: string = ''; /** * Title for the Recommended apps list. * @type {string}. * @default 'Recommended Apps'. */ @Input() recommendedAppTitle: string = 'Recommended Apps'; /** * Heading tag of title * @type {HeadingTag}. * @example. * 'h2'. */ @Input() headingTag: HeadingTag = 'h2'; /** * Custom template for the app card. * @type {FullAppData}. */ @Input() customAppCardTemplate: TemplateRef<FullAppData>; /** * Router link for one app when clicked. * Using for the default app card. If you are using the custom card - you must * create your own router link on the card template. * @type {string | any}. * @example * '/details'. */ @Input() routerLinkForOneApp: string | any; /** * Key name of the App object which will be chosen like navigation parameter for the Router link. * Using only with the default app card template. * @type {string}. * @example * 'appId'. */ @Input() appNavigationParam: string; /** * @deprecated * Emitter for click on App card. It is deprecated. If you want to get data for redirect only - use * {@link routerLinkForOneApp} with {@link appNavigationParam}. * @type {FullAppData}. */ @Output() readonly clickByAppCard: EventEmitter<FullAppData> = new EventEmitter<FullAppData>(); /** * Uses to get a part of an app router link. * Returns app navigation param or empty string value. */ getAppValueByParameter(app: FullAppData): string { if (this.appNavigationParam) { return get(app, this.appNavigationParam); } return ''; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-additional-select/oc-additional-select.component.ts
<reponame>mukesh-openchannel/angular-template-libraries<filename>projects/angular-common-components/src/lib/form-components/oc-additional-select/oc-additional-select.component.ts import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { AppFormField, DropdownAdditionalField } from '../model/app-form-model'; import { FormGroup } from '@angular/forms'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { OcFormGenerator } from '../oc-form/oc-form-generator'; import { cloneDeep } from 'lodash'; @Component({ selector: 'oc-additional-select', templateUrl: './oc-additional-select.component.html', styleUrls: ['./oc-additional-select.component.scss'], }) export class OcAdditionalSelectComponent implements OnInit, OnDestroy { @Input() formGroup: FormGroup; @Input() dropdownField: DropdownAdditionalField; @Input() fields: AppFormField[]; otherFieldId: string; destroy$ = new Subject<void>(); ngOnInit(): void { this.initOtherFieldId(); this.listenDropdownChanges(); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); } private initOtherFieldId(): void { this.otherFieldId = this.dropdownField?.attributes?.subTypeSettings?.additionalFieldId; } private listenDropdownChanges(): void { if (this.formGroup && this.dropdownField) { this.formGroup.controls[this.dropdownField.id].valueChanges .pipe(takeUntil(this.destroy$)) .subscribe(dropdownValue => this.updateValidatorsForOtherField(dropdownValue)); } } private updateValidatorsForOtherField(dropdownValue: string): void { const attributesByValue = this.dropdownField?.attributes?.subTypeSettings?.additionalFieldAttributesByDropdownValue[dropdownValue]; const otherField = cloneDeep(this.fields?.find(field => field.id === this.otherFieldId)); if (attributesByValue && otherField && this.formGroup?.controls[this.otherFieldId]) { const control = this.formGroup.controls[this.otherFieldId]; otherField.attributes = { ...(otherField?.attributes || {}), ...attributesByValue }; OcFormGenerator.setValidators(control, otherField); control.updateValueAndValidity(); } } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-tooltip-label/oc-tooltip-label.component.ts
import { Component, Input } from '@angular/core'; type TooltipPlacement = | 'auto' | 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'left-top' | 'left-bottom' | 'right-top' | 'right-bottom'; export type TooltipPlacementArray = TooltipPlacement[] | TooltipPlacement; @Component({ selector: 'oc-tooltip-label', templateUrl: './oc-tooltip-label.component.html', styleUrls: ['./oc-tooltip-label.component.css'], }) export class OcTooltipLabelComponent { /** * The text for tooltip label. * @type {string}. * Default empty. */ @Input() text: string = ''; /** * The value that defines whether a field will be required or not. * Shown as an asterisk. * @type {boolean}. * Default false. */ @Input() required: boolean = false; /** * Description (optional) - description for a title. * Open small modal panel on the right side with this description text. * @type {string}. * Default empty. */ @Input() description: string = ''; /** * infoTitleIconCsv (optional) - the path to the description icon. * @type {string}. * Default 'assets/angular-common-components/info.svg' */ @Input() infoTitleIconCsv: string = 'assets/angular-common-components/info.svg'; /** * Set custom classes for label. * Optional. * @type {string}. * Default empty. */ @Input() labelClass: string = ''; /** * Tooltip position. * Optional. * @type {TooltipPlacementArray}. * Default 'right'. */ @Input() tooltipPlacement: TooltipPlacementArray = 'right'; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-full-image-gallery-view-modal/oc-full-image-gallery-view-modal.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { OcFullImageGalleryViewModalComponent } from './oc-full-image-gallery-view-modal.component'; import { MockSvgIconComponent, MockVideoComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { GalleryItem } from '@openchannel/angular-common-components/src/lib/common-components'; import { By } from '@angular/platform-browser'; const imageItem: GalleryItem = { image: 'https://static.zerochan.net/Yakkun.full.1531987.jpg', title: 'Test App Image', description: 'Improve and extend your experience right from your own UI', }; describe('OcFullImageGalleryViewModalComponent', () => { let component: OcFullImageGalleryViewModalComponent; let fixture: ComponentFixture<OcFullImageGalleryViewModalComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [OcFullImageGalleryViewModalComponent, MockSvgIconComponent, MockVideoComponent], providers: [NgbActiveModal], }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OcFullImageGalleryViewModalComponent); component = fixture.componentInstance; component.galleryItems = [imageItem, imageItem, imageItem]; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should hide details', () => { component.showDetails = false; fixture.detectChanges(); const detailsBlock = fixture.debugElement.query(By.css('.full-image-gallery-modal__details')); expect(detailsBlock).toBeFalsy(); }); it('should show image and description', () => { const detailsBlock = fixture.debugElement.query(By.css('.full-image-gallery-modal__details')).nativeElement; const image = fixture.debugElement.query(By.css('.full-image-gallery-modal__item-image')).nativeElement; const title = fixture.debugElement.query(By.css('.full-image-gallery-modal__details-title')).nativeElement; const description = fixture.debugElement.query(By.css('.full-image-gallery-modal__details-description')).nativeElement; expect(detailsBlock).toBeTruthy(); expect(image).toBeTruthy(); expect(title.textContent).toEqual('Test App Image'); expect(description.textContent).toEqual(' Improve and extend your experience right from your own UI '); }); it('should change slide on click', () => { const arrowRight = fixture.debugElement.query(By.css('.full-image-gallery-modal__carousel-nav-right')).nativeElement; const arrowLeft = fixture.debugElement.query(By.css('.full-image-gallery-modal__carousel-nav-left')).nativeElement; arrowRight.click(); fixture.detectChanges(); expect(component.activeItemIdx).toEqual(1); arrowLeft.click(); fixture.detectChanges(); expect(component.activeItemIdx).toEqual(0); }); it('should change slides be arrow key press', () => { const eventRight = new KeyboardEvent('keyup', { code: 'ArrowRight', }); const eventLeft = new KeyboardEvent('keyup', { code: 'ArrowLeft', }); window.dispatchEvent(eventRight); fixture.detectChanges(); expect(component.activeItemIdx).toEqual(1); window.dispatchEvent(eventLeft); fixture.detectChanges(); expect(component.activeItemIdx).toEqual(0); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/model/oc-sidebar-model.ts
import { SidebarValue } from './components-basic.model'; export class OcSidebarSelectModel { parent: SidebarValue; child: SidebarValue; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/authentication.service.ts
import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { Observable, of, throwError } from 'rxjs'; import { LoginRequest, LoginResponse, RefreshTokenRequest } from '../model/api/login.model'; import { AuthHolderService } from './auth-holder.service'; import { catchError, map, mergeMap, tap } from 'rxjs/operators'; import { OcApiPaths } from '../oc-ng-common-service.module'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { SiteAuthConfig } from '../model/api/market.model'; import { HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class AuthenticationService { constructor(private httpService: HttpRequestService, private authHolderService: AuthHolderService, private apiPaths: OcApiPaths) {} initCsrf(): Observable<any> { return this.httpService.get(`${this.apiPaths.authorization}/csrf`); } getAuthConfig(): Observable<SiteAuthConfig> { return this.httpService.get(`${this.apiPaths.authorization}/config`); } login(request: LoginRequest): Observable<LoginResponse> { return this.httpService.post(`${this.apiPaths.authorization}/external/token`, request); } /** * Endpoint to exchange code from auth server for LoginResponse * @param code from auth server * @param redirectUri uri that initiated login procedure */ verifyCode(code: string, redirectUri: string): Observable<LoginResponse> { const params = new OcHttpParams().append('code', code).append('redirectUri', redirectUri); return this.httpService.post(`${this.apiPaths.authorization}/external/verify`, {}, { params }); } refreshToken(request: RefreshTokenRequest, headers: HttpHeaders = new HttpHeaders()): Observable<LoginResponse> { return this.httpService.post(`${this.apiPaths.authorization}/refresh`, request, { headers }); } logOut(): Observable<void> { const requestBody = { accessToken: this.authHolderService.accessToken, refreshToken: this.authHolderService.refreshToken, }; return this.httpService.post(`${this.apiPaths.authorization}/logout`, requestBody); } refreshTokenSilent(): Observable<any> { return this.refreshToken({ refreshToken: this.authHolderService.refreshToken }, new HttpHeaders({ 'x-handle-error': '401' })).pipe( tap((response: LoginResponse) => this.authHolderService.persist(response.accessToken, response.refreshToken)), catchError(err => { this.authHolderService.clearTokensInStorage(); return throwError(err); }), ); } tryLoginByRefreshToken(): Observable<boolean> { return of(this.authHolderService.isLoggedInUser()).pipe( mergeMap((isLogged: boolean) => { if (isLogged) { return of(isLogged); } else if (!this.authHolderService.refreshToken) { return of(false); } else { return this.refreshTokenSilent().pipe( map(() => this.authHolderService.isLoggedInUser()), catchError(() => of(false)), ); } }), ); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/utils/type-mapper.util.ts
<filename>projects/angular-common-components/src/lib/auth-components/utils/type-mapper.util.ts import { cloneDeep, each, forIn, get, map, set } from 'lodash'; import { OptionValue, TypeFieldModel, TypeModel } from '../models/oc-type-definition.model'; export class TypeMapperUtils { /** * Inject default value into type fields. * @fields: * [{ * id: 'customData.text', * defaultValue: 'any-value' * }] * @defaultValues: * { * customData: { * text: 'new-value' * } * } * @return * [{ * id: 'customData.text', * defaultValue: 'new-value' * }] */ static injectDefaultValues<T extends TypeFieldModel>(fields: T[], defaultValues: any): T[] { const clonedFields = cloneDeep(fields); if (clonedFields && defaultValues) { clonedFields.forEach(field => { field.defaultValue = get(defaultValues, field.id, field?.defaultValue); }); } return clonedFields; } /** * Normalize field options for type. * @fields: Example: * [{ * id: 'dropdown' * options: [{ * value: 'first' * },{ * value: 'second' * }] * }] * @return: Example: * [{ * id: 'dropdown' * options: ['first', 'second'] * }] */ static normalizeOptions<T extends TypeFieldModel>(fields: T[]): T[] { const clonedFields: T[] = cloneDeep(fields); each(clonedFields, field => { if (field?.options) { field.options = map(field.options, (option: OptionValue) => (option?.value !== undefined ? option.value : option)); } if (field?.fields) { field.fields = this.normalizeOptions(field.fields); } }); return clonedFields; } /** * Normalize field path(customData) before REST saving. * @data: Example: * { * 'customData.text': 'any-value; * } * @return: Example: * { * customData: { * text: 'any-value'; * } * } */ static buildDataForSaving(data: any): any { let result: any = {}; forIn(data, (value, key) => (result = set(result, key, value))); return result; } static createFormConfig<T extends TypeFieldModel>(type: TypeModel<T>, oldData: any): TypeModel<T> { if (type) { return set({ ...type }, 'fields', this.normalizeOptions(this.injectDefaultValues(type.fields, oldData))); } return type; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/management-components/public-api.ts
export * from './oc-management-components.module'; export * from './oc-menu-user-grid/oc-menu-user-grid.component'; export * from './oc-invite-modal/oc-invite-modal.component'; /** Models */ export * from './models/oc-modal.model'; export * from './models/user-data.model'; export * from './models/menu-user-grid.model';
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-datetime-picker/oc-datetime-picker.component.spec.ts
<reponame>mukesh-openchannel/angular-template-libraries import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcDatetimePickerComponent } from './oc-datetime-picker.component'; import { FormsModule } from '@angular/forms'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { OcButtonComponent } from '@openchannel/angular-common-components/src/lib/common-components'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NgxSpinnerModule } from 'ngx-spinner'; describe('OcDatetimePickerComponent', () => { let component: OcDatetimePickerComponent; let fixture: ComponentFixture<OcDatetimePickerComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcDatetimePickerComponent, MockSvgIconComponent, OcButtonComponent], imports: [FormsModule, NgbModule, HttpClientTestingModule, NgxSpinnerModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcDatetimePickerComponent); component = fixture.componentInstance; fixture.detectChanges(); }); const dateStr = 'Fri Oct 30 2020 11:51:07'; it('should create', () => { expect(component).toBeTruthy(); }); it('should contain date value', () => { component.writeValue(dateStr); expect(component.date).toEqual(new Date(dateStr)); }); it('should set date value', () => { component.value = dateStr; expect(component.date).toEqual(new Date(dateStr)); }); it('should contain date value in date container', async () => { component.writeValue(dateStr); component.type = 'date'; component.settings = { format: 'dd/MM/yyyy' }; fixture.detectChanges(); const dateContainer = fixture.nativeElement.querySelector('.date-picker__format-text'); await fixture.whenStable().then(() => { expect(dateContainer.textContent.trim()).toEqual('30/10/2020'); }); }); it('should change date value format', async () => { component.writeValue(dateStr); component.type = 'datetime'; component.settings = { format: 'dd/MM/yyyy HH:mm' }; fixture.detectChanges(); const dateContainer = fixture.nativeElement.querySelector('.date-picker__format-text'); await fixture.whenStable().then(() => { expect(dateContainer.textContent.trim()).toEqual('30/10/2020 11:51'); }); }); it('datepicker should be disabled', async () => { component.setDisabledState(true); const pickerButton = fixture.nativeElement.querySelector('#datePickerDD'); pickerButton.click(); fixture.detectChanges(); const calendar = fixture.nativeElement.querySelector('.dropdown-menu.show'); await fixture.whenStable().then(() => { expect(calendar).toBeFalsy(); }); }); it('should call onChange with value', async () => { const onChangeFunc = jest.fn(); component.registerOnChange(onChangeFunc); component.emitChanges(new Date(dateStr)); expect(onChangeFunc).toHaveBeenCalled(); expect(onChangeFunc.mock.calls[0][0]).toBe(new Date(dateStr).valueOf()); }); it('datepicker should change month to next', async () => { const nextMonthStr = new Date('Fri Nov 30 2020 11:51:07'); component.value = dateStr; const pickerButton = fixture.nativeElement.querySelector('#datePickerDD'); pickerButton.click(); fixture.detectChanges(); const nextMonthBtn = fixture.nativeElement.querySelector('#nextMonth'); nextMonthBtn.click(); await fixture.whenStable().then(() => { expect(component.date).toEqual(nextMonthStr); }); }); it('datepicker should change month to prev', async () => { const prevMonthStr = new Date('Fri Sep 30 2020 11:51:07'); component.value = dateStr; const pickerButton = fixture.nativeElement.querySelector('#datePickerDD'); pickerButton.click(); fixture.detectChanges(); const prevMonthBtn = fixture.nativeElement.querySelector('#prevMonth'); prevMonthBtn.click(); await fixture.whenStable().then(() => { expect(component.date).toEqual(prevMonthStr); }); }); it('datepicker should change time', async () => { const timeChanged = new Date(dateStr); timeChanged.setHours(timeChanged.getHours() - 1, timeChanged.getMinutes() + 1); component.value = dateStr; component.type = 'datetime'; fixture.nativeElement.querySelector('#datePickerDD').click(); fixture.detectChanges(); fixture.nativeElement.querySelector('#hourDec').click(); fixture.nativeElement.querySelector('#minInc').click(); fixture.detectChanges(); await fixture.whenStable().then(() => { expect(component.date).toEqual(timeChanged); }); }); it('should check leap year', () => { component.value = new Date(dateStr).setMonth(1, 20); component.ngOnInit(); const lastDayOfFeb = component.monthDays.find(week => { return week.find(day => day.day === 29 && day.date.getMonth() === 1); }); expect(component.monthDays.length).toBeGreaterThan(0); expect(lastDayOfFeb).toBeTruthy(); }); it('should change year on January', async () => { const prevYearString = new Date('Fri Dec 30 2019 11:51:07'); component.value = 'Fri Jan 30 2020 11:51:07'; const pickerButton = fixture.nativeElement.querySelector('#datePickerDD'); pickerButton.click(); fixture.detectChanges(); const prevMonthBtn = fixture.nativeElement.querySelector('#prevMonth'); prevMonthBtn.click(); await fixture.whenStable().then(() => { expect(component.date).toEqual(prevYearString); }); }); it('should show placeholder, if date is not exist', () => { const placeholder = 'Placeholder'; component.placeholder = placeholder; component.date = null; fixture.detectChanges(); const placeholderElement = fixture.nativeElement.querySelector('.date-picker__format-text_placeholder'); expect(placeholderElement.textContent.trim()).toBe(placeholder); }); it('should show default value, if placeholder is not exist', () => { component.placeholder = null; component.date = null; fixture.detectChanges(); const placeholderElement = fixture.nativeElement.querySelector('.date-picker__format-text_placeholder'); expect(placeholderElement.textContent.trim()).toBe(component.settings.format.toUpperCase()); }); });
mukesh-openchannel/angular-template-libraries
src/radio-button-list.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcFormComponentsModule, OcRadioButtonListComponent } from '@openchannel/angular-common-components/src/lib/form-components'; const modules = { imports: [OcFormComponentsModule], }; export default { title: 'Radio Button List [BEM]', component: OcRadioButtonListComponent, decorators: [moduleMetadata(modules)], }; const RadioButtonListComponent = (args: OcRadioButtonListComponent) => ({ component: OcRadioButtonListComponent, moduleMetadata: modules, props: args, }); export const RadioGroup = RadioButtonListComponent.bind({}); RadioGroup.args = { itemsArray: [ { label: 'Angular', value: 'angular', }, { label: 'React', value: 'react', }, { label: 'Vue', value: 'vue', }, ], value: 'angular', radioButtonGroup: 'frameworks', };
mukesh-openchannel/angular-template-libraries
src/tags.stories.ts
<filename>src/tags.stories.ts import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { OcTagsComponent } from '@openchannel/angular-common-components/src/lib/form-components'; const modules = { imports: [OcCommonLibModule], }; export default { title: 'Tags [BEM]', component: OcTagsComponent, decorators: [moduleMetadata(modules)], argTypes: { updatingTags: { action: 'Get Tags' } }, }; const TagsComponent = (args: OcTagsComponent) => ({ component: OcTagsComponent, moduleMetadata: modules, props: args, }); export const EmptyTags = TagsComponent.bind({}); EmptyTags.args = {}; export const DefaultTags = TagsComponent.bind({}); DefaultTags.args = { availableTags: [ 'default', 'first', 'second', '111111', '222222', '333333', '444444444444', '5555555555555555', '6666666', '777777', '888888', '999999999999', '000000000000', ], value: ['default'], }; export const CustomTags = TagsComponent.bind({}); CustomTags.args = {}; CustomTags.args = { placeholder: 'Select MyTag', availableTags: ['1', '2', '3', '4', '5', '6', '7', 'default', 'default_second'], value: ['default', 'default_second'], }; export const BooleanTags = TagsComponent.bind({}); BooleanTags.args = { availableTags: ['true', 'false'], tagsType: 'boolean', }; export const NumberTags = TagsComponent.bind({}); NumberTags.args = { availableTags: ['1', '3', '45'], value: [45], tagsType: 'number', };
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/http-request-services.ts
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { catchError, mergeMap } from 'rxjs/operators'; import { API_URL, OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: Service for setting up site config.<br> * @param {{ headers: HttpHeaders; withCredentials: boolean;}} options (default: `{headers: { 'Content-Type': 'application/json' }, withCredentials: true}`) - default Http options * Methods: * * get * * post * * put * * patch * * delete */ @Injectable({ providedIn: 'root', }) export class HttpRequestService { options = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), withCredentials: true, }; constructor(private http: HttpClient, @Inject(API_URL) private apiUrl: string, private apiPaths: OcApiPaths) {} /** * * Description: GET request with additional http options * * @param {string} url - (required) URL string * @param {any} options - (optional) any Http options * @returns {Observable<any>} `Observable<any>` * * ### Example * * get('/users', {observe: 'body', reportProgress: true}) */ get(url: string, options?: any): Observable<any> { return this.http.get(this.apiUrl + url, this.mergeHttpOptions(options)); } /** * * Description: POST request with provided body and additional http options * * @param {string} url - (required) URL string * @param {any} body - (required) Http body * @param {any} options - (optional) any Http options * @returns {Observable<any>} `Observable<any>` * * ### Example * * post('/users', {name:'User', password: 'password'}, {observe: 'body', reportProgress: true}) */ post(url: string, body, options?: any): Observable<any> { return this.reInitCSRF(this.http.post<any>(this.apiUrl + url, body, this.mergeHttpOptions(options))); } /** * * Description: PUT request with provided body and additional http options * * @param {string} url - (required) URL string * @param {any} body - (required) Http body * @param {any} options - (optional) any Http options * @returns {Observable<any>} `Observable<any>` * * ### Example * * put('/users/sd7yf0987sdhf970', {name:'User', password: 'password'}, {observe: 'body', reportProgress: true}) */ put(url: string, body, options?: any): Observable<any> { return this.reInitCSRF(this.http.put(this.apiUrl + url, body, this.mergeHttpOptions(options))); } /** * * Description: PATCH request with provided body and additional http options * * @param {string} url - (required) URL string * @param {any} body - (required) Http body * @param {any} options - (optional) any Http options * @returns {Observable<any>} `Observable<any>` * * ### Example * * patch('/users/sd7yf0987sdhf970', {name:'User', password: 'password'}, {observe: 'body', reportProgress: true}) */ patch(url: string, body, options?: any): Observable<any> { return this.reInitCSRF(this.http.patch(this.apiUrl + url, body, this.mergeHttpOptions(options))); } /** * * Description: DELETE request with additional http options * * @param {string} url - (required) URL string * @param {any} options - (optional) any Http options * @returns {Observable<any>} `Observable<any>` * * ### Example * * delete('/users/sd7yf0987sdhf970', {reportProgress: true}) */ delete(url: string, options?: any): Observable<any> { return this.reInitCSRF(this.http.delete(this.apiUrl + url, this.mergeHttpOptions(options))); } private reInitCSRF<T>(request: Observable<T>): Observable<T> { return request.pipe( catchError((error: HttpErrorResponse) => { if (error?.status === 403 && error?.error?.toLowerCase()?.includes('csrf')) { return this.initCSRF().pipe(mergeMap(csrf => request)); } else { return throwError(error); } }), ); } private initCSRF(): Observable<any> { return this.http.get(`${this.apiUrl}${this.apiPaths.authorization}/csrf`, this.options); } private mergeHttpOptions(newOptions: any): any { return newOptions ? { ...this.options, ...newOptions } : this.options; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-file-upload/oc-file-upload.component.ts
<gh_stars>0 import { Component, ElementRef, EventEmitter, forwardRef, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { base64ToFile, ImageCroppedEvent, ImageTransform } from 'ngx-image-cropper'; import { HttpEventType, HttpResponse } from '@angular/common/http'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { Subject, Subscription } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { FileDetails, FileType, FileUploaderService } from '../model/file.model'; export interface ImageCropperOptions { headerText: string; cancelText: string; confirmText: string; } /** * File upload component. Represents template and logic for upload and download files. * * @example <oc-file-upload [(ngModel)]="fileModel" * fileType="singleImage" * [isMultiFile]="false" * fileUploadText="Throw file here" * fileUploadButtonText="Browse file" * imageUploadButtonText="Browse file" * defaultFileIcon="/fIcon.png" * uploadIconUrl="/uIcon.png" * closeIconUrl="/close.png" * zoomInIconUrl="/zoomIn.png" * zoomOutIconUrl="/zoomOut.png" * imageWidth="1024" * imageHeight="768" * [hash]="['a87sh098a7shd098ahs0d97has09dha09sdh9a07shd09ahs90dhas09d7h9a0s7hd09ahsd097has9d7ha9sd7ha09s7dh']" * acceptType="image/*" * (customMsgChange)="onMsgChange()" * > */ @Component({ selector: 'oc-file-upload', templateUrl: './oc-file-upload.component.html', styleUrls: ['./oc-file-upload.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => OcFileUploadComponent), multi: true, }, ], }) export class OcFileUploadComponent implements OnInit, OnDestroy, ControlValueAccessor { /** * File input template reference */ @ViewChild('fileDropRef', { static: false }) fileInputVar: ElementRef; /** * Set model value */ @Input() set value(val: string) { this.initValues(val); } /** * Text for file upload block */ @Input() fileUploadText: string = 'Drag & drop file here or'; /** * Text for file upload button */ @Input() fileUploadButtonText: string = 'Browse File'; /** * Text for image upload button */ @Input() imageUploadButtonText: string = 'Browse File'; /** * Options for image cropper modal. * You can change text of the buttons, for example. */ @Input() imageCropperOptions: ImageCropperOptions = { headerText: 'Edit Image', cancelText: 'Cancel', confirmText: 'Confirm', }; /** * Flag for download multiple files allowed or not */ @Input() isMultiFile: boolean = false; /** * URL for default file icon. */ @Input() defaultFileIcon: string = 'assets/angular-common-components/file_icon.svg'; /** * Supported file type ( "singleFile", "singleImage", "privateSingleFile", "multiFile", "multiImage", "multiPrivateFile" ) */ @Input() fileType: FileType; /** * Icon for upload button */ @Input() uploadIconUrl: string = 'assets/angular-common-components/upload_icon.svg'; /** * Icon URL value for buttons that close container window and stop uploading file */ @Input() closeIconUrl: string = 'assets/angular-common-components/close-icon.svg'; /** * Icon URL value for button that active zoomIn feature */ @Input() zoomInIconUrl: string = 'assets/angular-common-components/zoom-in.svg'; /** * Icon URL value for button that active zoomOut feature */ @Input() zoomOutIconUrl: string = 'assets/angular-common-components/zoom-out.svg'; /** * Variable for width of image */ @Input() imageWidth: number; /** * Variable for height of image */ @Input() imageHeight: number; /** * File hash */ @Input() hash: string[] = []; /** * File type (MIME) allowed to use */ @Input() acceptType: string; /** * Output emits after change custom message */ @Output() readonly customMsgChange = new EventEmitter<boolean>(); /** * Subscription to upload file from server */ uploadFileReq: Subscription = null; /** * Flag to know is upload in process or not */ isUploadInProcess: boolean = false; /** * Array of objects with file data */ fileDetailArr: FileDetails[] = []; /** * Text that shows up when image load throw error */ imageLoadErrorMessage: string = 'Please provide valid image'; /** * Flag that shows existence of image load error */ hasImageLoadError: boolean = false; /** * Object of cropped file */ croppedFileObj: any; /** * Image transform data */ transform: ImageTransform = {}; /** * Flag that shows that upload image in process */ uploadImageInProcess: boolean = false; /** * Event that triggers when file browsed */ browsedFileEvent: any; /** * Name of valid file */ fileName: string = ''; /** * Name of invalid file */ invalidFileName: string; /** * Flag that shows existence of invalid file */ containsInvalidFile = false; /** * Flag that allow maintain aspect ratio logic or not */ maintainAspectRatio = false; /** * Aspect ratio value */ aspectRatio: number; /** * Scale value */ scale = 1; /** * Percent progress showed up in loader */ loaderValue = 0; /** * Width of cropped image value */ croppedImageWidth: number; /** * Height of cropped image value */ croppedImageHeight: number; /** * Width value to resize */ resizeToWidth = 0; /** * Height value to resize */ resizeToHeight = 0; /** * Upload button text */ uploadButtonText: string = 'Browse file'; /** * @private Subject to clear all subscriptions */ private destroy$ = new Subject<void>(); constructor(private modalService: NgbModal, private fileUploaderService: FileUploaderService) {} ngOnInit(): void { this.setUploadButtonText(); if (this.isFileTypeImage) { this.calculateAspectRatio(); } } ngOnDestroy(): void { this.resetSelection(); this.destroy$.next(); this.destroy$.complete(); if (this.uploadFileReq) { this.uploadFileReq.unsubscribe(); } } /** * Return allowed default or provided MIME type for file input */ getAcceptedMIMEType(): string { const setTypeIfImage = this.isFileTypeImage() ? 'image/*' : '*/*'; return this.acceptType ? this.acceptType : setTypeIfImage; } /** * On file drop handler */ onFileDropped($event: any): void { if (this.validMimeTypeCheck($event.dataTransfer.files[0].type) && (this.isMultiFileSupport() || this.fileDetailArr.length === 0)) { this.fileInputVar.nativeElement.files = $event.dataTransfer.files; this.fileInputVar.nativeElement.dispatchEvent(new Event('change', { bubbles: true })); } } /** * Compare file type with allowed type list * @param fileType - string MIME type ex.: 'image/jpg' * @return boolean - result of validation */ validMimeTypeCheck(fileType: string): boolean { const typeArr: string[] = this.getAcceptedMIMEType().split(','); for (const validType of typeArr) { const validTypeArr: string[] = validType.split('/'); const fileTypeSplitArr: string[] = fileType.split('/'); const acceptedWildCardType = validTypeArr[1] === '*' && validTypeArr[0] === fileTypeSplitArr[0]; return validTypeArr[0] === '*' || fileType === validType || acceptedWildCardType; } return false; } /** * Function for upload file * @param {File} file */ uploadFile(file: File): void { if (!this.fileUploaderService.fileUploadRequest || this.hasImageLoadError) { // tslint:disable-next-line:no-console console.error('Please, set the fileUploadRequest function'); this.resetSelection(); } else { this.isUploadInProcess = true; let lastFileDetail = new FileDetails(); lastFileDetail.name = this.fileName; if (!this.fileDetailArr) { this.fileDetailArr = []; } this.fileDetailArr.push(lastFileDetail); const formData: FormData = new FormData(); formData.append('file', file, this.fileName); this.uploadFileReq = this.fileUploaderService.fileUploadRequest(formData, this.isFileTypePrivate(), this.hash).subscribe( (event: any) => { if (event.type === HttpEventType.UploadProgress) { lastFileDetail.fileUploadProgress = Math.round((event.loaded * 100) / event.total) - 5; } else if (event.type === HttpEventType.ResponseHeader) { lastFileDetail.fileUploadProgress = 97; } else if (event.type === HttpEventType.DownloadProgress) { lastFileDetail.fileUploadProgress = 99; } else if (event instanceof HttpResponse) { lastFileDetail = this.convertFileUploadResToFileDetails(event); lastFileDetail.fileUploadProgress = 100; lastFileDetail.fileIconUrl = this.defaultFileIcon; this.fileDetailArr[this.fileDetailArr.length - 1] = lastFileDetail; this.isUploadInProcess = false; this.uploadFileReq = null; this.emitChanges(); this.resetSelection(); } }, () => { this.isUploadInProcess = false; this.resetSelection(); }, () => { this.isUploadInProcess = false; this.resetSelection(); }, ); } } /** * This method is used to convert uploaded file response to fileDetails. */ convertFileUploadResToFileDetails(fileUploadRes: HttpResponse<FileDetails>): FileDetails { const fileDetails = new FileDetails(); fileDetails.uploadDate = fileUploadRes.body.uploadDate; fileDetails.fileId = fileUploadRes.body.fileId; fileDetails.name = fileUploadRes.body.name; fileDetails.contentType = fileUploadRes.body.contentType; fileDetails.size = fileUploadRes.body.size; fileDetails.isPrivate = fileUploadRes.body.isPrivate; fileDetails.mimeCheck = fileUploadRes.body.mimeCheck; fileDetails.fileUrl = fileUploadRes.body.fileUrl; fileDetails.isError = fileUploadRes.body.isError; return fileDetails; } /** * Handle file on browsing */ fileBrowseHandler(event: any, content?: any): void { this.onTouched(); if (!event?.target?.files[0]?.name) { return; } if (this.isFileTypeImage()) { this.browsedFileEvent = event; this.fileName = event?.target?.files[0]?.name; this.fileName = this.fileName ? this.fileName : event?.dataTransfer?.files[0]?.name; this.customMsgChange.emit(false); this.modalService .open(content, { centered: true, backdrop: 'static', keyboard: false, size: 'lg', }) .result.then( () => { // Do Nothing }, () => { this.resetSelection(); }, ); } else { this.fileName = event?.target?.files[0]?.name; this.fileName = this.fileName ? this.fileName : event?.dataTransfer?.files[0]?.name; this.uploadFile(event.target.files[0]); } } /** * Function to reset selection in case if previous one didnt die by itself */ resetSelection(): void { if (this.fileInputVar) { this.fileInputVar.nativeElement.value = ''; } this.imageLoadErrorMessage = ''; this.hasImageLoadError = false; if (this.fileDetailArr && this.fileDetailArr.length < 1) { this.customMsgChange.emit(true); } } /** * Function check if file type related to image types * @returns `boolean` */ isFileTypeImage(): boolean { return this.fileType === 'singleImage' || this.fileType === 'multiImage'; } /** * Function check if file type related to private types * @returns `boolean` */ isFileTypePrivate(): boolean { return this.fileType === 'multiPrivateFile' || this.fileType === 'privateSingleFile'; } /** * Function check if file type related to types with multiple files support * @returns `boolean` */ isMultiFileSupport(): boolean { return this.fileType === 'multiPrivateFile' || this.fileType === 'multiFile' || this.fileType === 'multiImage'; } /** * Function check if file type NOT related to image types * @returns `boolean` */ isFileTypeNotImage(): boolean { return ( this.fileType === 'singleFile' || this.fileType === 'privateSingleFile' || this.fileType === 'multiFile' || this.fileType === 'multiPrivateFile' ); } /** * Function that executes after image cropping * @param {ImageCroppedEvent} event - Crop event object */ imageCropped(event: ImageCroppedEvent): void { this.croppedImageWidth = event.width; this.croppedImageHeight = event.height; this.croppedFileObj = base64ToFile(event.base64); } /** * Function that executes after image load failed */ loadImageFailed(): void { this.hasImageLoadError = true; } /** * Function that subtract from scale 0.1 and save it */ zoomOut(): void { this.scale -= 0.1; this.transform = { ...this.transform, scale: this.scale, }; } /** * Function that add to scale 0.1 and save it */ zoomIn(): void { this.scale += 0.1; this.transform = { ...this.transform, scale: this.scale, }; } /** * Set resize width and height, also aspect ratio */ calculateAspectRatio(): void { if (this.imageWidth) { this.resizeToWidth = this.imageWidth; } if (this.imageHeight) { this.resizeToHeight = this.imageHeight; } if (this.imageWidth && this.imageHeight) { this.aspectRatio = this.imageWidth / this.imageHeight; this.maintainAspectRatio = true; } else { this.aspectRatio = 1; } } /** * Function to stop upload. Close subscription if active and reset all related data. * @param {number} idx - Index of file in details */ cancelUploading(idx: number): void { this.onTouched(); if (this.isUploadInProcess && this.uploadFileReq) { this.uploadFileReq.unsubscribe(); } this.uploadFileReq = null; this.fileDetailArr.splice(idx, 1); this.emitChanges(); if (this.fileDetailArr.length < 1) { this.customMsgChange.emit(true); } } /** * Function get file details and returns file url * @param {FileDetails} file * @returns `string` */ getUrl(file: FileDetails): string { // NOTE: for non image file upload always show default file upload icon if (this.isFileTypeNotImage()) { return this.defaultFileIcon; } if (file.fileUploadProgress === 100) { return file.fileUrl; } else { return this.defaultFileIcon; } } /** * Function get file details and returns CSS class for file icon * @param {FileDetails} file * @returns `string` */ getFileIconClass(file: FileDetails): string { if (this.isFileTypeNotImage()) { return 'default-icon'; } return file?.fileUploadProgress === 100 ? 'app-icon' : 'default-icon'; } /** * Function for download file. If file is private then it opens link in new window and download file. If not call service method to start downloading process. * @param {FileDetails} file */ // prettier-ignore downloadFile(file: FileDetails): void { // NOSONAR if (file && file.fileUploadProgress && file.fileUploadProgress === 100) { if (this.isFileTypePrivate()) { if (!this.fileUploaderService.fileDetailsRequest) { // tslint:disable-next-line:no-console console.error('Please, set the FileDetailsRequest function'); } else { this.fileUploaderService .fileDetailsRequest(file.fileId) .pipe(takeUntil(this.destroy$)) .subscribe(res => { if (res && res.fileUrl) { window.open(res.fileUrl, '_blank'); } }); } } else { if (file.fileUrl) { window.open(file.fileUrl, '_blank'); } } } } /** * Function that called on main model change and emits value */ emitChanges(): void { if (this.isMultiFileSupport()) { this.onChange(this.getFileUrlOrFileId(this.fileDetailArr)); } else { this.onChange(this.fileDetailArr?.length > 0 ? this.getFileUrlOrFileId(this.fileDetailArr)[0] : null); } } onTouched = () => { // nothing to do }; onChange: (value: any) => void = () => { // nothing to do }; writeValue(obj: any): void { this.initValues(obj); } registerOnChange(onChange: (value: any) => void): void { this.onChange = onChange; } registerOnTouched(onTouched: () => void): void { this.onTouched = onTouched; } // prettier-ignore setDisabledState?(isDisabled: boolean): void { // NOSONAR } /** * @private Sets the text for the upload button based on the file type */ private setUploadButtonText(): void { this.uploadButtonText = this.isFileTypeImage() ? this.imageUploadButtonText : this.fileUploadButtonText; } /** * @private Initialization of value for component * @param {string | string[]} urlData */ private initValues(urlData: string | string[]): void { if (!this.fileUploaderService.fileDetailsRequest) { console.error('Please, set the FileDetailsRequest function'); } else if (urlData) { this.fileDetailArr = []; if (this.isMultiFileSupport() && typeof urlData !== 'string') { urlData.forEach(fileUrl => { this.getFileDetails(fileUrl); }); } else if (typeof urlData === 'string') { this.getFileDetails(urlData); } else { console.error('initValues function error: something wrong with provided data'); } } } /** * @private Uses fileUploadService to get file details. * @param {string} urlData */ private getFileDetails(urlData: string): void { this.fileUploaderService .fileDetailsRequest(urlData) .pipe(takeUntil(this.destroy$)) .subscribe( res => { this.fileDetailArr.push({ ...res, fileUploadProgress: 100 }); this.emitChanges(); }, error => { if (error.error.code === 404) { this.fileDetailArr.push(this.externallyHostedImageHandler(urlData)); this.emitChanges(); } }, ); } /** * @private Creates an object when the image is externally hosted * @returns {FileDetails} */ private externallyHostedImageHandler(urlData: string): FileDetails { const fileDetails = new FileDetails(); fileDetails.name = urlData; fileDetails.fileUrl = urlData; return { ...fileDetails, fileUploadProgress: 100 }; } /** * @private Returns array with file ids and URLs * @param {FileDetails[]} files * @returns {string[]} `string[]` */ private getFileUrlOrFileId(files: FileDetails[]): string[] { if (files?.length > 0) { return files.map(file => (file?.isPrivate ? file.fileId : file.fileUrl)); } return null; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/pipe/price.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { AppModel } from '../model/app-data.model'; @Pipe({ name: 'price', }) export class PricePipe implements PipeTransform { private isoCurrencyCode = { USD: '$', EUR: '€', CNY: '¥', GBP: '£', }; transform(model: AppModel): string { let price = ''; if (!model || model.type === 'free') { price = 'Free'; } else { price = model.currency ? this.getCurrency(model.currency) : ''; price += model.price / 100; if (model.type === 'recurring') { price += '/' + model.billingPeriod.substring(0, 3); } } return price; } private getCurrency(currency: string): string { if (Object.keys(this.isoCurrencyCode).includes(currency)) { return this.isoCurrencyCode[currency]; } else { return '$'; } } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/app-categories/models/app-category-model.ts
/** * Class consist of necessary fields: * ``` typescript * { * categoryName: string; * categoryQuery: any; * } * ``` * And not required fields: * ``` typescript * { * categoryCardClass: string; * categoryLogo: string; * categoryBackgroundImage: string; * categoryTitleColor: string; * } * ``` */ export class AppCategoryDetail { /** Additional class for the one card */ categoryCardClass?: string; /** url to the category card icon image */ categoryLogo?: string; /** Will be used for category card title. */ categoryName: string; /** queryParams for the routerLink */ categoryQuery: any; /** url to the category card background image */ categoryBackgroundImage?: string; /** set custom color for the category title */ categoryTitleColor?: string; }
mukesh-openchannel/angular-template-libraries
src/dropdown-multi-app.stories.ts
import { OcFormComponentsModule } from '@openchannel/angular-common-components/src/lib/form-components'; import { moduleMetadata } from '@storybook/angular'; import { OcDropdownMultiAppComponent } from '@openchannel/angular-common-components/src/lib/form-components/oc-dropdown-multi-app/oc-dropdown-multi-app.component'; import { AppsSearchService } from '@openchannel/angular-common-components/src/lib/form-components/model/dropdown-multi-app.model'; import { Observable, of } from 'rxjs'; import { NgModule, Provider } from '@angular/core'; import { FullAppData, OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; const mockApps: Partial<FullAppData>[] = [ { appId: '<KEY>', version: 5, name: 'API Connect Play', }, { appId: '<KEY>', version: 3, name: 'Fuel CRM Gold', icon: 'assets/angular-common-components/standard-app-icon.svg', }, { appId: '<KEY>', version: 7, name: 'Intersect Connect', }, { appId: '<KEY>', version: 13, name: 'Lead Accounting', icon: 'assets/angular-common-components/star.svg', }, { appId: '<KEY>', version: 4, name: 'Fuel CRM Lite', }, ]; class StoryMockAppSearchService extends AppsSearchService { constructor(private apps: Partial<FullAppData>[]) { super(); } loadDefaultApps(existsAppIDs: string[]): Observable<FullAppData[]> { return of(this.apps.filter(app => existsAppIDs?.includes(app.appId)) as FullAppData[]); } appsSearch(existsApps: FullAppData[], searchText: string): Observable<FullAppData[]> { const existsAppIDs = (existsApps || []).map(app => app.appId); return of( this.apps.filter(app => !existsAppIDs.includes(app.appId) && app.name.toLowerCase().includes(searchText)) as FullAppData[], ); } } const storyMockProviderAppSearchService: Provider = { provide: AppsSearchService, useFactory: () => new StoryMockAppSearchService(mockApps), }; const modules: NgModule = { imports: [OcFormComponentsModule, OcCommonLibModule], providers: [storyMockProviderAppSearchService], }; export default { title: 'Dropdown multi app component [BEM]', component: OcDropdownMultiAppComponent, decorators: [moduleMetadata(modules)], excludeStories: /.*[M|m]ock.*/, }; const DropdownMultiAppComponent = (args: OcDropdownMultiAppComponent) => ({ component: OcDropdownMultiAppComponent, moduleMetadata: modules, props: args, }); export const EmptyMultiApp = DropdownMultiAppComponent.bind({}); EmptyMultiApp.args = {}; export const SearchPlaceholderMultiApp = DropdownMultiAppComponent.bind({}); SearchPlaceholderMultiApp.args = { dropdownPlaceholder: 'Search ...', }; export const DefaultAppsInMultiApp = DropdownMultiAppComponent.bind({}); DefaultAppsInMultiApp.args = { dropdownPlaceholder: 'Search ...', defaultAppIDs: ['<KEY>', '<KEY>'], }; // Exports for another stories (provider for StoryMockAppSearchService, StoryMockAppSearchService) export { storyMockProviderAppSearchService, StoryMockAppSearchService };
mukesh-openchannel/angular-template-libraries
src/button.stories.ts
<filename>src/button.stories.ts<gh_stars>0 import { moduleMetadata } from '@storybook/angular'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { OcButtonComponent, OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; const modules = { imports: [OcCommonLibModule, BrowserAnimationsModule], }; export default { title: 'Buttons [BEM]', component: OcButtonComponent, decorators: [moduleMetadata(modules)], }; const ButtonComponent = (args: OcButtonComponent) => ({ component: OcButtonComponent, template: ` <div> <oc-button [text]="text" [type]="typeButton" [process]="process || false"></oc-button> </div>`, props: args, }); export const Primary = ButtonComponent.bind({}); Primary.args = { text: 'Submit', typeButton: 'primary', }; export const Secondary = ButtonComponent.bind({}); Secondary.args = { text: 'Cancel', typeButton: 'secondary', }; export const Warning = ButtonComponent.bind({}); Warning.args = { text: 'Warning', typeButton: 'warning', }; export const Link = ButtonComponent.bind({}); Link.args = { text: 'Submit', typeButton: 'link', }; export const Progress = ButtonComponent.bind({}); Progress.args = { text: 'Submit', typeButton: 'primary', process: true, }; export const ProgressSecondary = ButtonComponent.bind({}); ProgressSecondary.args = { text: 'Submit', typeButton: 'secondary', process: true, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-dropbox/oc-dropbox.component.ts
import { Component, ElementRef, EventEmitter, forwardRef, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core'; import { NgbTypeaheadSelectItemEvent } from '@ng-bootstrap/ng-bootstrap'; import { Observable, of, Subject } from 'rxjs'; import { map, mergeAll } from 'rxjs/operators'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { NgStyle } from '@angular/common'; /** * A component represents a dropdown list and input field which acts as a search for items from this list. * For functional of this component was used [Angular Bootstrap Typeahead]{@link https://ng-bootstrap.github.io/#/components/typeahead/examples} * @example * <oc-dropbox #dropBox * [items]="dropBoxItems" * placeHolder="Placeholder text" * [clearFormAfterSelect]="true" * [dropElementTemplate]="dropElementTemplateExample" * (inputChange)="onInputChange($event)" * (selectedItem)="addTagToResultList($event)"> * </oc-dropbox> */ @Component({ selector: 'oc-dropbox', templateUrl: './oc-dropbox.component.html', styleUrls: ['./oc-dropbox.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => OcDropboxComponent), multi: true, }, ], }) export class OcDropboxComponent implements OnInit, ControlValueAccessor { /** * (Optional) * Placeholder text of the search input field. */ @Input() placeHolder: string = ''; /** * (Optional) * Items of the dropdown list. */ @Input() items: string[] = []; /** * Clear/not clear input text form, after the user, chooses an item. * Form will not be cleared by default. * @default false */ @Input() clearFormAfterSelect: boolean = false; /** * Custom style for the search input field. * Implements [ngStyle]{@link NgStyle} * ## Usage example * ` <oc-dropbox [customNgStyle]="{"width": widthValueVariable}"></oc-dropbox> ` * @example * <oc-dropbox [customNgStyle]="{'width': widthValueVariable}"></oc-dropbox> */ @Input() customNgStyle: NgStyle; /** * String of classes will be added to the general class of the search input field. * ## Usage example * ` <oc-dropbox customClassStyle="custom-class another-class"></oc-dropbox> ` * @example * <oc-dropbox customClassStyle="custom-class another-class"></oc-dropbox> */ @Input() customClassStyle: string; /** * The template to override the way resulting items are displayed in the dropdown. * @example * <ng-template #dropElementTemplate let-result="resultItem"> * <span> {{result}}</span> * </ng-template> */ @Input() dropElementTemplate: TemplateRef<any>; /** * Custom function for searching items of the [items array]{@link items}. */ @Input() customSearch: (text: Observable<string>) => Observable<readonly any[]>; /** * Flag, that determines whether to add custom items by 'Enter' key up (from input). * @default false */ @Input() disableAddCustomItemsByEnter: boolean = false; /** * Emit currently selected item from dropdown to the parent component. */ @Output() readonly selectedItem: EventEmitter<string> = new EventEmitter<string>(); /** * Emit text from the input field to the parent component. */ @Output() readonly inputChange: EventEmitter<string> = new EventEmitter<string>(); /** * Getting the dropbox input element. */ @ViewChild('dropBox', { static: false }) dropBox: ElementRef<HTMLInputElement>; /** Listener of the `focus` event */ focus$: Subject<string> = new Subject<string>(); /** Listener of the `click` event */ click$: Subject<string> = new Subject<string>(); /** Selected item from the dropdown */ outputSelectedItem: string; /** Variable for disable state */ disabled: boolean = false; ngOnInit(): void { if (!this.customSearch) { this.customSearch = this.defaultSearch; } } /** * Toggles dropdown results list. Used by arrow icon. */ toggleResultsDropdown(): void { if (this.disabled) { return; } const isListOpened = this.dropBox.nativeElement.getAttribute('aria-expanded') === 'true'; if (isListOpened) { this.clearFocus(); } else { // Simulate input click with latest input value to trigger ngbTypeahead search this.click$.next(this.outputSelectedItem); } } /** * Launch of the search function * @param text$ observable text from the input field */ search = (text$: Observable<string>) => { return of(text$, this.focus$, this.click$).pipe(mergeAll(3), e => this.customSearch(e)); }; /** * Default search function. * @param text$ observable text from the input field */ defaultSearch = (text$: Observable<string>) => { return text$.pipe(map(searchTag => this.filterItems(searchTag, this.items))); }; /** * Filter items from the dropdown list. * @param searchItem string from the input field * @param items array of the items from the dropdown list */ filterItems(searchItem: string, items: string[]): string[] { if (items && searchItem) { const lowerTag = searchItem.toLowerCase(); return this.items.filter(v => v && `${v}`.toLowerCase().indexOf(lowerTag) > -1); } return items; } /** * Catching selected item from the dropdown list. * @param itemEvent item from the [NgbTypeaheadSelectItemEvent]{@link https://ng-bootstrap.github.io/#/components/typeahead/api#NgbTypeaheadSelectItemEvent} */ selectItem(itemEvent?: NgbTypeaheadSelectItemEvent): void { if (itemEvent) { this.outputSelectedItem = itemEvent.item; } this.selectedItem.emit(this.outputSelectedItem); this.onChange(this.outputSelectedItem); this.clearForm(itemEvent); this.clearFocus(); } /** * Clearing of the search input field. * @param itemEvent item from the [NgbTypeaheadSelectItemEvent]{@link https://ng-bootstrap.github.io/#/components/typeahead/api#NgbTypeaheadSelectItemEvent} */ clearForm(itemEvent?: NgbTypeaheadSelectItemEvent): void { if (this.clearFormAfterSelect) { itemEvent?.preventDefault(); this.outputSelectedItem = ''; } } /** * Catching `focus` event. * This is necessary for the custom form controls validation. */ onFocus(): void { this.onTouched(); } /** * Removing focus from the search input field. */ clearFocus(): void { this.dropBox.nativeElement.blur(); } /** * Calls this function with new value. When user wrote something in the component. * It needs to know that new data has been entered in the control. */ registerOnChange(onChange: (value: any) => void): void { this.onChange = onChange; } /** * Calls this function when user left chosen component. * It needs for validation of custom form controls. */ registerOnTouched(onTouched: () => void): void { this.onTouched = onTouched; } /** * this method will be called by the control to pass the value to our component. * It is used if the value is changed through the code outside * (setValue or changing the variable that ngModel is tied to), * as well as to set the initial value. */ writeValue(obj: any): void { this.outputSelectedItem = obj ? obj : ''; } /** * (Optional) * the method will be called by the control when the [disabled] state changes. */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } /** * Clears the previous value if the user writes a new value. * @param event input event from the search field */ clearSelectedValue(event: any): void { if (this.outputSelectedItem !== event.target.value) { this.onChange(''); } } private onTouched = () => { // nothing to do }; private onChange: (value: any) => void = () => { // nothing to do }; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/directive/autofocus.directive.ts
<reponame>mukesh-openchannel/angular-template-libraries import { Directive, ElementRef, Input, OnInit } from '@angular/core'; @Directive({ selector: '[ocAutofocus]', }) export class AutofocusDirective implements OnInit { @Input() ocAutofocus = false; constructor(private elementRef: ElementRef) {} ngOnInit(): void { if (this.ocAutofocus) { this.focus(); } } focus(): void { this.elementRef.nativeElement.focus(); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-market-components.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { OcAppCardComponent } from './oc-app-card/oc-app-card.component'; import { OcAppDescriptionComponent } from './oc-app-description/oc-app-description.component'; import { OcAppGalleryComponent } from './oc-app-gallery/oc-app-gallery.component'; import { OcAppGetStartedComponent } from './oc-app-get-started/oc-app-get-started.component'; import { OcAppListGridComponent } from './oc-app-list-grid/oc-app-list-grid.component'; import { OcAppShortInfoComponent } from './oc-app-short-info/oc-app-short-info.component'; import { OcFeaturedAppsComponent } from './oc-featured-apps/oc-featured-apps.component'; import { OcImageGalleryComponent } from './oc-image-gallery/oc-image-gallery.component'; import { OcOverallRatingComponent } from './oc-overall-rating/oc-overall-rating.component'; import { OcRatingComponent } from './oc-rating/oc-rating.component'; import { OcRecommendedAppsComponent } from './oc-recommended-apps/oc-recommended-apps.component'; import { OcReviewListComponent } from './oc-review-list/oc-review-list.component'; import { OcTextSearchComponent } from './oc-text-search/oc-text-search.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { RouterModule } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { OcReviewComponent } from './oc-review/oc-review.component'; import { OcFormComponentsModule } from '@openchannel/angular-common-components/src/lib/form-components'; import { CarouselModule } from 'ngx-owl-carousel-o'; import { AngularSvgIconModule } from 'angular-svg-icon'; @NgModule({ declarations: [ OcAppCardComponent, OcAppDescriptionComponent, OcAppGalleryComponent, OcAppGetStartedComponent, OcAppListGridComponent, OcAppShortInfoComponent, OcFeaturedAppsComponent, OcImageGalleryComponent, OcOverallRatingComponent, OcRatingComponent, OcRecommendedAppsComponent, OcReviewListComponent, OcTextSearchComponent, OcReviewComponent, ], imports: [ CommonModule, NgbModule, OcCommonLibModule, RouterModule, FormsModule, ReactiveFormsModule, OcFormComponentsModule, CarouselModule, AngularSvgIconModule.forRoot(), ], exports: [ OcAppCardComponent, OcAppDescriptionComponent, OcAppGalleryComponent, OcAppGetStartedComponent, OcAppListGridComponent, OcAppShortInfoComponent, OcFeaturedAppsComponent, OcImageGalleryComponent, OcOverallRatingComponent, OcRatingComponent, OcRecommendedAppsComponent, OcReviewListComponent, OcTextSearchComponent, OcReviewComponent, ], }) export class OcMarketComponentsModule {}
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/portal-components/models/app-listing.model.ts
<reponame>mukesh-openchannel/angular-template-libraries import { ComponentsPage, FullAppData } from '@openchannel/angular-common-components/src/lib/common-components'; import { TemplateRef } from '@angular/core'; /** Default column IDs. */ export type ModifyColumnId = | 'left-placeholder' | 'name' | 'summary' | 'create-date' | 'status' | 'app-options' | 'right-placeholder' | string; /** * Context for table cells, will added to your TemplateRef.<br> * Used only for {@link ModifyColumnConfig.rowCellTemplate}.<br> */ export interface ColumnTemplateContext { app: FullAppData | any; isChild: boolean; index: number; } /** * Context for bottom table area.<br> * Used only for {@link OcAppTableComponent#tableBottomRowTemplate}. */ export interface AppsNotFoundTemplateContext { /** Count of table columns. */ columnCount: number; } export interface FieldPathConfig { /** * By this path will be get icon url from {@link FullAppData}.<br> * Used for showing image in column 'Name'. Look: {@link ModifyColumnId}.<br> */ appIconPath?: 'customData.icon' | string; /** * By this path will be get icon text from {@link FullAppData}.<br> * Used for showing app description in column 'Name'. Look: {@link ModifyColumnId}.<br> */ appDescriptionPath?: 'customData.summary' | string; } /** * This config used for:<br> * 1. Overriding default table cells {@link ModifyColumnId}. * 2. Adding new table columns. */ export type ModifyColumnConfig = { [key in ModifyColumnId]: { /** * Template for header cell. * When non null, will be override default cell. */ headerCellTemplate?: TemplateRef<any>; /** * Template for row cell (showing same app data, like: name, description, date etc.). * When non null, will be override default cell. */ rowCellTemplate?: TemplateRef<ColumnTemplateContext>; }; }; /** Configuration model for the App Listing component */ export interface AppListing { /** layout of the component. Default: 'table' */ layout: 'table'; /** data response with list of apps, pagination, etc. */ data: ComponentsPage<FullAppData | any>; /** array of options which will be applied in dropdown menu of the component */ options: AppListingOptions[]; /** * A URL template for the preview. * @example https://mysite.com/apps/{appId}/{version} */ previewTemplate?: string; } /** The available options of the dropdown menu */ export type AppListingOptions = string | 'EDIT' | 'PREVIEW' | 'PUBLISH' | 'SUBMIT' | 'SUSPEND' | 'UNSUSPEND' | 'DELETE'; /** Interface for the action from a dropdown menu */ export interface AppListMenuAction { /** Which action was chosen */ action: AppListingOptions; /** ID of the app which has been chosen */ appId: string; /** Version of the app which has been chosen */ appVersion: number; /** Marker for apps which has been subversion of the main app */ isChild?: boolean; } // ---- Sorting for app table columns ---- /** Column names for sorting {@link OcAppTableComponent}. */ export type AppGridSortColumn = 'name' | 'created' | 'status'; /** * Config for setting current sort icon direction (up or down). Used in {@link OcAppTableComponent#sortOptions}. * * Values:<br> * -1 => sort icon to down.<br> * null => sort icon to down.<br> * 1 => sort icon to up.<br> */ export type AppGridSortOptions = { [name in AppGridSortColumn]: 1 | -1 | null; }; export type AppGridSortChosen = { /** New sort config. */ sortOptions: AppGridSortOptions; /** Updated column ID. */ changedSortOption: AppGridSortColumn; };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/management-components/models/user-data.model.ts
import { ComponentsPage } from '@openchannel/angular-common-components/src/lib/common-components'; export interface ComponentsUser { userId: string; name: string; email: string; customData: any; created: number; type?: string; roles?: string[]; permissions?: string[]; } export interface ComponentsUserAccount extends ComponentsUser { userAccountId: string; } export interface ComponentsUserAccountGridModel extends ComponentsUserAccount { inviteStatus?: UserAccountInviteStatusType; inviteId?: string; inviteToken?: string; } export declare type UserAccountInviteStatusType = 'ACTIVE' | 'INVITED'; export declare type UserGridOptionType = 'EDIT' | 'DELETE'; export interface ComponentsUserGridActionModel { action: UserGridOptionType; userId: string; userAccountId?: string; inviteId?: string; inviteToken?: string; } export interface ComponentsUsersGridParametersModel { layout: 'table'; data: ComponentsPage<ComponentsUserAccountGridModel>; options: UserGridOptionType[]; previewTemplate?: string; } export interface Role { created: number; lastUpdated: number; name: string; permissions?: string[]; systemDefined: boolean; } export interface DeveloperRole extends Role { developerRoleId: string; } export interface UserRole extends Role { userRoleId: string; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-select-expandable/oc-select-expandable.component.ts
<gh_stars>0 import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { SelectModel } from '../model/components-basic.model'; @Component({ selector: 'oc-select-expandable', templateUrl: './oc-select-expandable.component.html', styleUrls: ['./oc-select-expandable.component.css'], }) export class OcSelectExpandableComponent implements OnInit { /** * Text of the select-expandable heading. * @type {string}. */ @Input() title: string; /** * Select-expandable config, contains labels and `checked` states of select options. * @type {SelectModel[]}. */ @Input() selectModels: SelectModel[]; /** * Initial select collapse state. * @type {boolean}. * @default true. */ @Input() collapsedOnInit: boolean = true; /** * Current select collapse state. * @type {boolean}. * @default true. */ @Input() isCollapsed: boolean = true; /** * Source path to expanded svg icon. * @type {boolean}. * @default select-up.svg */ @Input() expandedIcon: string = 'assets/angular-common-components/select-up.svg'; /** * Source path to collapsed svg icon. * @type {boolean}. * @default down-arrow.svg */ @Input() collapsedIcon: string = 'assets/angular-common-components/down-arrow.svg'; /** * Emits select model changes and passes to a parent component. */ @Output() readonly selectModelsChange: EventEmitter<SelectModel[]> = new EventEmitter<SelectModel[]>(); ngOnInit(): void { this.isCollapsed = this.collapsedOnInit; } /** * This method runs on select options change. * Uses selectModelsChange to emit select model value. */ onChange(): void { this.selectModelsChange.emit(this.selectModels); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/models/overall-rating-summary-model.ts
<filename>projects/angular-common-components/src/lib/market-components/models/overall-rating-summary-model.ts export class OverallRatingSummary { rating = 0; reviewCount = 0; 1 = 0; 2 = 0; 3 = 0; 4 = 0; 5 = 0; constructor(rating?: number, reviewCount?: number) { this.rating = rating ? rating : 0; this.reviewCount = reviewCount ? reviewCount : 0; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/portal-components/oc-portal-components.module.ts
<filename>projects/angular-common-components/src/lib/portal-components/oc-portal-components.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { OcChartComponent } from './oc-chart/oc-chart.component'; import { OcAppTableComponent, OcAppTableCellPattern } from './oc-app-table/oc-app-table.component'; import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; @NgModule({ declarations: [OcChartComponent, OcAppTableComponent, OcAppTableCellPattern], imports: [CommonModule, OcCommonLibModule, InfiniteScrollModule, NgbModule], exports: [OcChartComponent, OcAppTableComponent], }) export class OcPortalComponentsModule {}
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/prerender-requests-watcher.service.ts
<reponame>mukesh-openchannel/angular-template-libraries<gh_stars>0 import { Injectable } from '@angular/core'; import { Observable, of, throwError } from 'rxjs'; import { catchError, delay, filter, finalize, tap } from 'rxjs/operators'; import { HttpEvent, HttpResponse, HttpResponseBase } from '@angular/common/http'; /** * Description: This service for the Netlify pre-rendering. It's getting data about requests, changing pre-render status * and creating special meta tags. */ @Injectable({ providedIn: 'root', }) export class PrerenderRequestsWatcherService { private buffer: HttpEvent<any>[] = []; private sleepAfterLastRequestMS = 1000; private requestCount = 0; /** * Adding a new observable with api request to the watcher. This function checking of the all requests fulfillment. * @param httpEvent observable with a request data */ addHttpEvent(httpEvent: Observable<HttpEvent<any>>): Observable<HttpEvent<any>> { this.setPrerenderStatus(false); this.requestCount++; return httpEvent.pipe( tap(response => this.buffer.push(response)), catchError(error => { this.buffer.push(error); return throwError(error); }), finalize(() => this.handleLastResponse()), ); } /** HttpEvent<any> | HttpErrorResponse ? */ handleLastResponse(): void { of(1) .pipe( delay(this.sleepAfterLastRequestMS), tap(() => this.requestCount--), filter(() => this.requestCount === 0), ) .subscribe(() => { this.checkErrorsOrChangeStatus(this.buffer as HttpResponse<any>[]); }); } /** * Checking of api error responses and changing pre-render status. * @param responses array of the responses */ checkErrorsOrChangeStatus(responses: HttpEvent<any>[]): void { const anyError: HttpEvent<any>[] = responses.filter(resp => resp instanceof HttpResponseBase && resp?.status >= 300); this.setPrerenderStatus(anyError.length === 0); } /** * Changing the prerender status. Creating a special flag for the Netlify pre-render. * @param ready status of the page. Ready or not for prerender. * `true` means that all requests are done and page is ready. */ setPrerenderStatus(ready: boolean): void { const createdScript = document.querySelector('#renderScript'); if (createdScript) { createdScript.textContent = `document.prerenderReady = ${ready};`; } else { const renderScript = document.createElement('script'); renderScript.type = 'text/javascript'; renderScript.src = ''; renderScript.textContent = `document.prerenderReady = ${ready};`; renderScript.id = 'renderScript'; document.getElementsByTagName('head')[0].prepend(renderScript); } } /** * Creation the special 404 meta tag for the pre-render. */ create404MetaTag(): void { const meta404 = document.createElement('meta'); meta404.name = 'prerender-status-code'; meta404.content = '404'; meta404.id = 'prerender404'; document.getElementsByTagName('head')[0].appendChild(meta404); } /** * Removing the 404 meta tag for the pre-render */ remove404MetaTag(): void { document.querySelector('#prerender404').remove(); } /** * Creation of the special 301 meta tags for the pre-render. * @param location new page location for the search crawlers */ create301MetaTag(location: string): void { const meta303 = document.createElement('meta'); const meta303Redirect = document.createElement('meta'); meta303.name = 'prerender-status-code'; meta303.content = '301'; meta303Redirect.name = 'prerender-header'; meta303Redirect.content = `Location: ${location}`; document.getElementsByTagName('head')[0].appendChild(meta303); document.getElementsByTagName('head')[0].appendChild(meta303Redirect); } /** * Clearing all of the prerender tags */ clearPrerenderMeta(): void { document.querySelectorAll('meta').forEach(item => { if (item.name.includes('prerender')) { item.remove(); } }); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/transactions.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpRequestService } from './http-request-services'; import { OcApiPaths } from '../oc-ng-common-service.module'; import { Page } from '../model/api/page.model'; import { Transaction } from '../model/api/transaction.model'; import { HttpHeaders } from '@angular/common/http'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; /** * Description: API service to work with Transactions.<br> * * [OpenChannel Documentation]{@link https://support.openchannel.io/documentation/api/#426-transactions} * * Endpoints:<br> * * GET 'v2/transactions'<br> * * GET 'v2/transactions/{transactionId}'<br> * * POST 'v2/transactions/{transactionId}'<br> * * DELETE 'v2/transactions/{transactionId}'<br> */ @Injectable({ providedIn: 'root', }) export class TransactionsService { constructor(public httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Returns the list of transactions for the current user * * @param pageNumber - (optional) Current page index. Starts from >= 1. * @param limit - (optional) Count apps into response. Starts from >= 1. * @param sort - (optional) Sort apps by specific field. * [OpenChannel Documentation]{@link https://support.openchannel.io/documentation/api/#381-sort-document} * @param query - (optional) Your specific search query. * [OpenChannel Documentation]{@link https://support.openchannel.io/documentation/api/#380-query-document} * @returns {Observable<Page<Transaction>>} `Observable<Page<Transaction>>` * * ### Example * * `getTransactionsList(1, 10, { date: 1 }, { type: 'payment' });` */ getTransactionsList(pageNumber: number = 1, limit: number = 100, sort: any = {}, query: any = {}): Observable<Page<Transaction>> { const params = new OcHttpParams() .append('pageNumber', String(pageNumber)) .append('limit', String(limit)) .append('sort', JSON.stringify(sort)) .append('query', JSON.stringify(query)); return this.httpRequest.get(`${this.apiPaths.transactions}`, { params }); } /** * * Description: Returns a transaction by the id * * @param {string} transactionId - The id of the transaction to be returned * @param {HttpHeaders} headers - (optional) HTTP headers for the request * @returns {Observable<Transaction>} `Observable<Transaction>` * * ### Example * * `getTransactionById('transaction-id');` */ getTransactionById(transactionId: string, headers: HttpHeaders = new HttpHeaders()): Observable<Transaction> { return this.httpRequest.get(`${this.apiPaths.transactions}/${transactionId}`, { headers }); } /** * * Description: Updates a transaction by the id * * @param {string} transactionId - The id of the transaction to be updated * @param {string} customData - A custom JSON object to attach to this transaction * @param {HttpHeaders} headers - (optional) HTTP headers for the request * @returns {Observable<Transaction>} `Observable<Transaction>` * * ### Example * * `updateTransactionById('transaction-id', { department: 'billing' });` */ updateTransactionById(transactionId: string, customData: any, headers: HttpHeaders = new HttpHeaders()): Observable<Transaction> { return this.httpRequest.post(`${this.apiPaths.transactions}/${transactionId}`, { customData }, { headers }); } /** * * Description: Deletes a transaction by the id * * @param {string} transactionId - The id of the transaction to be deleted * @param {HttpHeaders} headers - (optional) HTTP headers for the request * @returns {Observable<{}>} `Observable<{}>` * * ### Example * * `deleteTransactionById('transaction-id');` */ deleteTransactionById(transactionId: string, headers: HttpHeaders = new HttpHeaders()): Observable<{}> { return this.httpRequest.delete(`${this.apiPaths.transactions}/${transactionId}`, { headers }); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/app-categories/oc-app-categories/oc-app-categories.component.ts
import { Component, Input, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { CarouselComponent, OwlOptions } from 'ngx-owl-carousel-o'; import { AppCategoryDetail } from '../models/app-category-model'; @Component({ selector: 'oc-app-categories', templateUrl: './oc-app-categories.component.html', styleUrls: ['./oc-app-categories.component.css'], }) export class OcAppCategoriesComponent { @ViewChild('carousel', { static: false }) carouselRef: CarouselComponent; /** * Data of the category that will be shown in array. * Default: empty */ @Input() data: AppCategoryDetail[] = []; /** * Title of the category section. * Default: empty */ @Input() categoryHeaderTitle: string = ''; /** * Main router link for the category card. * Default: empty * @example * '/collections' * '/collections/categoryName' */ @Input() categoryRouterLink: string = ''; /** Owl Carousel options */ customOptions: OwlOptions = { loop: true, mouseDrag: false, touchDrag: false, pullDrag: true, dots: false, autoWidth: true, navSpeed: 700, navText: ['', ''], responsive: { 0: { items: 1, }, 400: { items: 1, }, 740: { items: 2, }, 940: { items: this.data.length > 5 ? 5 : this.data.length, }, }, nav: false, }; constructor(private router: Router) {} /** Navigates to the category page */ navigateToCategory(routerQuery?: any): void { if (routerQuery) { this.router.navigate([this.categoryRouterLink], { queryParams: routerQuery }).then(); } else { this.router.navigate([this.categoryRouterLink]).then(); } } /** Move carousel to next slide */ nextSlide(): void { this.carouselRef.next(); } /** Move carousel to previous slide */ prevSlide(): void { this.carouselRef.prev(); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/user.model.ts
<gh_stars>0 import { Page } from './page.model'; import { OwnershipModelResponse } from './ownership.model'; export interface User { userId: string; name: string; email: string; customData: any; created: number; type?: string; roles?: string[]; permissions?: string[]; } export interface UserDetails { email: string; exp: number; firstName: string; generatedByOrigin: string; lastName: string; organizationId: string; roles: string[]; permissions?: string[]; userExternalId: string; isSSO: boolean; individualId?: string; userClass?: string; } export interface UserAccount extends User { userAccountId: string; } export interface UserAccountGridModel extends UserAccount { inviteStatus?: UserAccountInviteStatusTypeModel; inviteId?: string; inviteToken?: string; } export interface UsersGridParametersModel { layout: 'table'; data: Page<UserAccountGridModel>; options: UserGridOptionTypeModel[]; previewTemplate?: string; } export interface UserGridActionModel { action: UserGridOptionTypeModel; userId: string; userAccountId?: string; inviteId?: string; inviteToken?: string; } export interface UserCompanyModel extends User { ownedApps?: OwnershipModelResponse[]; accountCount?: number; } export declare type UserGridOptionTypeModel = 'EDIT' | 'DELETE'; export declare type UserAccountInviteStatusTypeModel = 'ACTIVE' | 'INVITED'; export enum AccessLevel { ALL = '*', READ = 'READ', MODIFY = 'MODIFY', DELETE = 'DELETE', } export enum PermissionType { ALL = '*', APPS = 'APPS', ACCOUNTS = 'ACCOUNTS', DEVELOPERS = 'DEVELOPERS', USERS = 'USERS', FILES = 'FILES', FORMS = 'FORMS', OWNERSHIPS = 'OWNERSHIPS', REVIEWS = 'REVIEWS', ORGANIZATIONS = 'ORGANIZATIONS', } export interface Permission { type: PermissionType; access: AccessLevel[]; }
mukesh-openchannel/angular-template-libraries
src/image-gallery.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcImageGalleryComponent } from '@openchannel/angular-common-components/src/lib/market-components'; import { GalleryItem, OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { CarouselModule } from 'ngx-owl-carousel-o'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; /** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */ const modules = { imports: [OcCommonLibModule, CarouselModule, BrowserAnimationsModule], }; export default { title: 'Image Gallery [BEM]', component: OcImageGalleryComponent, decorators: [moduleMetadata(modules)], }; const ImageGalleryComponent = (args: OcImageGalleryComponent) => ({ component: OcImageGalleryComponent, moduleMetadata: modules, props: args, }); const imageItem: GalleryItem = { image: 'https://static.zerochan.net/Cola.Gotouryouta.full.1501202.jpg', title: 'Test App Image', description: 'Improve and extend your experience right from your own UI', }; const anotherImageItem: GalleryItem = { image: 'https://static.zerochan.net/Yakkun.full.1531987.jpg', title: 'Test App Image', description: 'Improve and extend your experience right from your own UI', }; const imageItem2: GalleryItem = { image: 'https://static.zerochan.net/Wenqing.Yan.full.2318589.jpg', title: 'Test App Image', description: 'Improve and extend your experience right from your own UI', }; const videoItem: GalleryItem = { video: 'https://youtu.be/L_LUpnjgPso', title: 'Test App Video', description: 'Improve and extend your experience right from your own UI', }; export const SmallGallery = ImageGalleryComponent.bind({}); SmallGallery.args = { gallery: [imageItem, imageItem, imageItem], maxItems: 3, displayDetails: true, mediaDimensions: { width: '100%', height: '192px' }, }; export const ExtendedGallery = ImageGalleryComponent.bind({}); ExtendedGallery.args = { gallery: [imageItem, imageItem2, anotherImageItem, imageItem, videoItem, imageItem, anotherImageItem, anotherImageItem], displayDetails: true, maxItems: 8, mediaDimensions: { width: '100%', height: '192px' }, expandOnClick: true, componentIconsPath: { arrowLeft: 'assets/angular-common-components/arrow-left-analog.svg', arrowRight: 'assets/angular-common-components/arrow-right-analog.svg', }, }; export const CarouselGallery = ImageGalleryComponent.bind({}); CarouselGallery.args = { gallery: [imageItem, imageItem2, anotherImageItem, imageItem, videoItem, imageItem, anotherImageItem, anotherImageItem], displayDetails: true, allowArrowControllers: true, mediaDimensions: { width: '100%', height: '192px' }, componentIconsPath: { arrowLeft: 'assets/angular-common-components/arrow-left-analog.svg', arrowRight: 'assets/angular-common-components/arrow-right-analog.svg', }, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/app-categories/oc-app-categories/oc-app-categories.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcAppCategoriesComponent } from './oc-app-categories.component'; import { By } from '@angular/platform-browser'; import { CarouselModule } from 'ngx-owl-carousel-o'; import { RouterTestingModule } from '@angular/router/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { Component, NO_ERRORS_SCHEMA } from '@angular/core'; import { Location } from '@angular/common'; import { Router } from '@angular/router'; import { AppCategoryDetail } from '../models/app-category-model'; @Component({ template: '', }) export class MockRoutingComponent {} const appCategory1: AppCategoryDetail = { categoryCardClass: 'category-card', categoryLogo: '', categoryName: 'All Apps', categoryTitleColor: 'orange', categoryQuery: null, }; describe('OcAppCategoriesComponent', () => { let component: OcAppCategoriesComponent; let fixture: ComponentFixture<OcAppCategoriesComponent>; let location: Location; let router: Router; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [ BrowserAnimationsModule, CarouselModule, RouterTestingModule.withRoutes([{ path: 'mock-router', component: MockRoutingComponent }]), ], declarations: [OcAppCategoriesComponent, MockRoutingComponent], schemas: [NO_ERRORS_SCHEMA], }).compileComponents(); router = TestBed.inject(Router); location = TestBed.inject(Location); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcAppCategoriesComponent); component = fixture.componentInstance; }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should move slides to the next', () => { component.data = [appCategory1, appCategory1, appCategory1, appCategory1, appCategory1, appCategory1]; jest.spyOn(component, 'nextSlide'); fixture.detectChanges(); const rightScrollButton = fixture.debugElement.query(By.css('#iconRight')).nativeElement; rightScrollButton.click(); expect(component.nextSlide).toHaveBeenCalled(); }); it('should move slides to the preview', () => { component.data = [appCategory1, appCategory1, appCategory1, appCategory1, appCategory1, appCategory1]; jest.spyOn(component, 'prevSlide'); fixture.detectChanges(); const leftScrollButton = fixture.debugElement.query(By.css('#iconLeft')).nativeElement; leftScrollButton.click(); expect(component.prevSlide).toHaveBeenCalled(); }); it('should redirect on route without query', async () => { component.data = [appCategory1, appCategory1, appCategory1, appCategory1, appCategory1, appCategory1]; component.categoryRouterLink = 'mock-router'; fixture.detectChanges(); const categoryCard = fixture.debugElement.query(By.css('.category-card')).nativeElement; categoryCard.click(); await fixture.whenStable().then(() => { expect(location.path()).toEqual('/mock-router'); }); }); it('should redirect on route with query', async () => { appCategory1.categoryQuery = { test: 'test' }; component.data = [appCategory1, appCategory1, appCategory1, appCategory1, appCategory1, appCategory1]; component.categoryRouterLink = 'mock-router'; fixture.detectChanges(); const categoryCard = fixture.debugElement.query(By.css('.category-card')).nativeElement; categoryCard.click(); await fixture.whenStable().then(() => { expect(location.path()).toEqual('/mock-router?test=test'); }); }); });
mukesh-openchannel/angular-template-libraries
src/content-modal.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule, OcContentModalComponent } from '@openchannel/angular-common-components/src/lib/common-components'; const modules = { imports: [OcCommonLibModule], }; export default { title: 'Content modal [BEM]', component: OcContentModalComponent, decorators: [moduleMetadata(modules)], }; const ContentModal = (args: OcContentModalComponent) => ({ component: OcContentModalComponent, moduleMetadata: modules, props: args, template: ` <div style="margin-top: 100px;"> <oc-content-modal modalTitle="Test modal title" [customContentTemplate]="modalContent" [closeButton]="true"></oc-content-modal> <ng-template #modalContent> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce eu sollicitudin nulla. Donec ultrices ornare velit. Donec ac molestie eros, at aliquet ligula. Ut et nibh lorem. Vestibulum egestas ac sapien eu fermentum. Cras ac ex a nulla maximus porta id eget velit. Nulla et eros at arcu efficitur ullamcorper vel quis lacus. Morbi a posuere mauris. Fusce rhoncus, eros nec ullamcorper varius, neque turpis ornare est, ac lacinia massa libero vitae erat. Ut ullamcorper in metus et condimentum. Aliquam condimentum, dolor in gravida ullamcorper, tortor dui ultrices ante, a tincidunt ante nisl id sapien. Duis semper aliquam eleifend. Nullam eget commodo magna, in luctus nulla. Sed sit amet feugiat magna. Phasellus vitae aliquam nulla. Suspendisse placerat dui tortor, at molestie ipsum egestas ut. Nullam eget mollis lectus. Sed augue sem, egestas sed lobortis quis, ultricies vel lorem. In vel ex nec mi gravida ornare dapibus nec neque. Mauris laoreet cursus augue, id sagittis quam varius non. Donec nec ipsum nec quam condimentum euismod eu quis lacus. Ut ut faucibus mi. </p> <ul> <strong> List Example:</strong> <li>Ut et mollis ex. Sed eu dolor erat. In purus leo, dapibus eget turpis sit amet, ultrices efficitur ligula. Donec nec velit neque. Morbi porta tellus id sem consectetur, quis pretium augue rutrum.</li> <li>Aenean ut purus non dui porttitor mattis. Morbi hendrerit lacus ante, sit amet feugiat lectus hendrerit sed.</li> <li>Etiam bibendum ullamcorper ligula, eu ullamcorper quam tincidunt non. Aliquam varius tellus non lacinia sodales. </li> <li>Suspendisse neque tortor, sodales eget ultrices varius, efficitur eu elit. Vestibulum ut erat augue. Suspendisse non scelerisque massa, vel gravida erat. In tortor lectus, congue tempus augue quis, vestibulum varius nisi. Nam quis molestie libero. </li> </ul> <p> Aliquam risus est, condimentum sodales lobortis quis, ullamcorper id justo. Vestibulum feugiat lacus ante, vel dictum felis euismod a. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nam venenatis ante a augue rutrum congue. Nam nec porta risus. Integer sed dui eget velit dapibus dapibus. Praesent sed tincidunt massa. Maecenas nec mi tincidunt neque consequat pellentesque. Phasellus egestas tempor nibh non pulvinar. Donec pretium velit consectetur ullamcorper congue. Vivamus vitae ante purus. Nam tellus nisi, lobortis vel viverra sit amet, mollis ut felis. Phasellus tincidunt metus odio, sed elementum nunc congue sit amet. Nulla ut tellus et ligula mattis lobortis. Morbi scelerisque iaculis nunc eget pharetra. </p> </ng-template> </div> `, }); export const modal = ContentModal.bind({}); modal.args = {};
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/pipe/get-text-by-path.pipe.ts
<filename>projects/angular-common-components/src/lib/common-components/pipe/get-text-by-path.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { get } from 'lodash'; import { replaceHTMLTags } from '../model/utils.model'; /** * Select text value from object by path. * @example without default value. * <h1>{{ {myObject: {textField: 'myTextValue'}} | getTextByPath: 'myObject.textField' }}</h1> * * @example with default value. * <h1>{{ {myObject: {textField: 'myTextValue'}} | getTextByPath: 'myObject.textField' : 'My default text'}}</h1> */ @Pipe({ name: 'getTextByPath', }) export class GetTextByPathPipe implements PipeTransform { transform(value: any, path: string, defaultValue: string = '', replaceHtmlTags: boolean = true): any { const text = get(value || {}, path); if (text === null || text === undefined) { return defaultValue; } switch (typeof text) { case 'boolean': case 'bigint': case 'number': case 'symbol': return String(text); case 'string': return (replaceHtmlTags ? replaceHTMLTags(text) : text) || defaultValue; default: console.warn(`Detected invalid path. Can\'t convert this value to string. path: ${path}, valueByPath: ${text}`); return defaultValue; } } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-dropdown-form/oc-dropdown-form.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { OcDropdownFormComponent } from './oc-dropdown-form.component'; import { MockFormComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcDropdownFormComponent', () => { let component: OcDropdownFormComponent; let fixture: ComponentFixture<OcDropdownFormComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [OcDropdownFormComponent, MockFormComponent], }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OcDropdownFormComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-review/oc-review.component.ts
<filename>projects/angular-common-components/src/lib/market-components/oc-review/oc-review.component.ts import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Review } from '../models/oc-review-details-model'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { ErrorMessageFormId } from '@openchannel/angular-common-components/src/lib/common-components'; @Component({ selector: 'oc-review', templateUrl: './oc-review.component.html', styleUrls: ['./oc-review.component.scss'], }) export class OcReviewComponent implements OnInit, OnDestroy { /** * (Optional) * Heading of the Review component. If not set - heading would not appear. */ @Input() heading: string = ''; /** * (Optional) * Shows the `cancel` and `submit` buttons of the component. * Buttons will not be shown by default. * @default false */ @Input() enableButtons: boolean = false; /** * (Optional) * Text of the `cancel` button. * @default 'Cancel' */ @Input() cancelButtonText: string = 'Cancel'; /** * (Optional) * Text of the `submit` button. * @default 'Submit' */ @Input() submitButtonText: string = 'Submit'; /** * (Optional) * Hid only the `cancel` button. * @default false */ @Input() hidCancelButton: boolean = false; /** * Data of the review from the user. */ @Input() reviewData: Review; /** * Flag that gives information that review submit request is in progress. * This will disable the buttons and user can not interact with it. * Also it applies a spinner to the `submit` button. * @default false */ @Input() submitInProgress: boolean = false; /** * Emits the fresh Review data to the parent component on `submit` button click or on form value changes. */ @Output() readonly reviewFormData: EventEmitter<Review> = new EventEmitter<Review>(); /** * Emits to the parent that `cancel` button was pressed and review has been canceled. */ @Output() readonly cancelReview: EventEmitter<boolean> = new EventEmitter<boolean>(); /** Emits the form valid status to a parent */ @Output() readonly isFormInvalid: EventEmitter<boolean> = new EventEmitter<boolean>(); /** Form for the review. */ reviewForm: FormGroup; /** * Subject for control of the form subscription life cycle * @private */ private destroy$: Subject<void> = new Subject(); formId: ErrorMessageFormId = 'review'; constructor(private fb: FormBuilder) {} ngOnInit(): void { this.generateForm(this.reviewData); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); } /** * Generating form with review data if it applied. * @param reviewData review data input. Necessary for the review editing */ generateForm(reviewData?: Review): void { this.reviewForm = this.fb.group({ rating: [reviewData?.rating ? reviewData.rating / 100 : null, [Validators.required]], headline: [reviewData?.headline, [Validators.required]], description: [reviewData?.description || '', [Validators.required, Validators.maxLength(2000)]], }); if (!this.enableButtons) { this.subscribeToForm(); } } /** * Function for the `submit` button. Triggers on click, * checking form and emits review data if form is valid. Otherwise, invalid form fields will be highlighted. */ submitReview(): void { this.reviewForm.markAllAsTouched(); if (this.reviewForm.valid && !this.submitInProgress) { this.reviewFormData.emit(this.fillReviewData()); } } clearForm(): void { if (!this.submitInProgress) { this.reviewForm.reset(); this.cancelReview.emit(true); } } /** * Fills review data from a previous data, new data from a form and parse rating. * @private * @return Review */ private fillReviewData(): Review { return { ...this.reviewForm.getRawValue(), rating: this.reviewForm.get('rating').value * 100, }; } /** * Listening to value changes of the form if buttons not applied. * @private */ private subscribeToForm(): void { this.isFormInvalid.emit(this.reviewForm.valid); this.reviewFormData.emit(this.fillReviewData()); this.reviewForm.valueChanges.pipe(takeUntil(this.destroy$)).subscribe(() => { this.isFormInvalid.emit(this.reviewForm.valid); this.reviewFormData.emit(this.fillReviewData()); }); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/type-model.ts
export interface TypeModel<T extends TypeFieldModel> { fields?: T[]; } export interface TypeFieldModel { id: string; type: string; label?: string; defaultValue?: any; attributes?: any; options?: OptionValue[] | string[]; fields?: TypeFieldModel[]; } export interface OptionValue { value: any; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/stripe.model.ts
export interface StripeAccount { stripeId: string; accountName: string; country: string; defaultCurrency: string; } export interface ChangeableCreditCardFields { isDefault: boolean; address_city?: string; address_country?: string; address_line1?: string; address_line2?: string; address_state?: string; address_zip?: string; } export interface CreditCard extends ChangeableCreditCardFields { cardId: string; exp_year: number; exp_month: number; last4: string; brand: string; name: string; } export interface ConnectStripeAccountResponse { developerId: string; expires: number; /** * URL to redirect developer, where Stripe account can be connected */ targetUrl: string; } export interface StripeAccountsResponse { developerId: string; accounts: StripeAccount[]; } export interface GetMarketplaceStripeSettingsResponse { clientId: string; /** * The publishableKey of the Stripe connected Stripe account for this marketplace */ publishableKey: string; } export interface UserCreditCardsResponse { userId: string; cards: CreditCard[]; } export interface Taxes { displayName: string; amount: number; } export interface PaymentTaxesResponse { subtotal: number; total: number; taxes: Taxes[]; } export interface PurchaseModel { appId: string; modelId: string; } export interface Purchase { models: PurchaseModel[]; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-social-links/oc-social-links.component.ts
import { Component, Input } from '@angular/core'; import { SocialLink } from '../model/social-link.model'; @Component({ selector: 'oc-social-links', templateUrl: './oc-social-links.component.html', styleUrls: ['./oc-social-links.component.css'], }) export class OcSocialLinksComponent { /** data passed to a social link component */ @Input() socialLinks: SocialLink[]; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/oc-edit-user-form/oc-edit-user-form.component.ts
import { Component, EventEmitter, Input, OnInit, Output, TemplateRef } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { OcCheckboxData, OcEditUserFormConfig, OcEditUserResult, OCOrganization } from '../models/oc-edit-user-form.model'; import { TypeMergeUtils } from '../utils/type-merge.util'; import { ErrorMessageFormId } from '@openchannel/angular-common-components/src/lib/common-components'; import { AppFormField, AppFormModel } from '@openchannel/angular-common-components/src/lib/form-components'; @Component({ selector: 'oc-edit-user-form', templateUrl: './oc-edit-user-form.component.html', styleUrls: ['./oc-edit-user-form.component.css'], }) export class OcEditUserFormComponent implements OnInit { /** * Configuration for Edit User form. */ @Input() formConfigs: OcEditUserFormConfig[]; /** * Show or not a form type dropdown. It is not shown by default. * By this dropdown different form configurations can be switched. * @default false */ @Input() enableTypesDropdown = false; /** * Add or not password field to the form. It is not shown by default. * @default false */ @Input() enablePasswordField = false; /** * URLs to the terms and privacy policy. * If they do not set - no checkbox with terms and policy agreement will be shown. * @default null */ @Input() enableTermsCheckbox: OcCheckboxData; /** * Text of the form type label. * @default 'Type' */ @Input() defaultTypeLabelText = 'Type'; /** * Data for the Account form. If not set - the form will be without default values. * @default null */ @Input() defaultAccountData: OCOrganization; /** * Data for the Organization form. If not set - the form will be without default values. * @default null */ @Input() defaultOrganizationData: OCOrganization; /** * Custom error template what will be shown when no {@link #formConfigs} is provided or not provided correctly. * @default null */ @Input() defaultEmptyConfigsErrorTemplate: TemplateRef<any>; /** * Error message what will be shown when no {@link #formConfigs} is provided or not provided correctly. * This message will be shown only when the {@link #defaultEmptyConfigsErrorTemplate} not set. * @default null */ @Input() defaultEmptyConfigsErrorMessage: string = 'There are no forms configured'; /** * Template for the Terms and Privacy policy agreement checkbox. * If not provided - the default template will be used. * @default null */ @Input() customTermsDescription: TemplateRef<any>; /** Current form ID. Used for modifying error messages. Look: {@link #ErrorMessageFormId} */ @Input() formId: ErrorMessageFormId = 'editUser'; /** * Emits the data form the form. */ @Output() readonly resultFormDataChange = new EventEmitter<OcEditUserResult>(); /** * Emits the link to the created and used in this component Form Group. */ @Output() readonly createdFormGroup = new EventEmitter<FormGroup>(); mainFormModel: AppFormModel; formGroup: FormGroup; termsControl: FormControl; currentFormConfig: OcEditUserFormConfig; private readonly ORG_PREFIX = 'org--'; private readonly PASSWORD_FILED_KEY = 'password'; ngOnInit(): void { this.buildFormByConfig(this.getCurrentFormConfig()); } /** * Creation of the Form group by provided config and mapping the default values. * @param formConfig config for the form fields */ buildFormByConfig(formConfig: OcEditUserFormConfig): void { this.clearPreviousValues(); const fieldsSorting = (field1, field2) => { const index1 = formConfig.fieldsOrder.indexOf(field1.id); const index2 = formConfig.fieldsOrder.indexOf(field2.id); return (index1 > -1 ? index1 : Infinity) - (index2 > -1 ? index2 : Infinity); }; if (formConfig) { this.currentFormConfig = formConfig; let tempForm: any = {}; if (formConfig.organization?.includeFields) { const config = formConfig?.organization; tempForm = TypeMergeUtils.mergeTypes( tempForm, this.defaultOrganizationData, config.typeData, this.ORG_PREFIX, config.includeFields, ); } if (formConfig.account?.includeFields) { const config = formConfig?.account; tempForm = TypeMergeUtils.mergeTypes(tempForm, this.defaultAccountData, config.typeData, '', config.includeFields); } if (this.enablePasswordField) { const passwordField: AppFormField = { id: this.PASSWORD_FILED_KEY, type: 'password', label: 'Password', attributes: { required: true, }, }; tempForm = TypeMergeUtils.mergeTypes(tempForm, this.defaultOrganizationData, { fields: [passwordField] }, '', ['password']); } if (formConfig.fieldsOrder) { tempForm.fields.sort(fieldsSorting); } this.mainFormModel = tempForm; } } /** * Getting data from the form, mapping and emitting to the parent * @param formData data from the form */ buildAndEmitResultData(formData: any): void { if (this.formGroup?.valid && this.currentFormConfig) { let account: OCOrganization; if (this.currentFormConfig?.account?.includeFields) { account = TypeMergeUtils.mergeDataAfterChanges( this.defaultAccountData, TypeMergeUtils.findFieldsWithoutCustomPrefixes(formData, [this.ORG_PREFIX]), ); account.type = this.currentFormConfig.account.type; } let organization: OCOrganization; if (this.currentFormConfig?.organization?.includeFields) { organization = TypeMergeUtils.mergeDataAfterChanges( this.defaultOrganizationData, TypeMergeUtils.findFieldsWithCustomPrefixes(formData, [this.ORG_PREFIX]), ); organization.type = this.currentFormConfig.organization.type; } this.resultFormDataChange.emit({ account, organization, password: formData?.password, }); } else { this.resultFormDataChange.emit(null); } } /** * Getting created form from the Form component and setting to the variable. * @param formGroup created form */ setFormGroup(formGroup: FormGroup): void { this.formGroup = formGroup; if (this.enableTermsCheckbox) { this.termsControl = new FormControl(false, Validators.requiredTrue); this.formGroup.addControl('terms', this.termsControl); } this.createdFormGroup.emit(formGroup); } private getCurrentFormConfig(): OcEditUserFormConfig { const accType = this.defaultAccountData ? this.defaultAccountData.type : null; const orgType = this.defaultOrganizationData ? this.defaultOrganizationData.type : null; if (this.formConfigs) { const newConfig = this.formConfigs.find( config => (accType && accType === config?.account.type) || (orgType && orgType === config?.organization.type), ); if (newConfig) { return newConfig; } else if (this.formConfigs[0]) { return this.formConfigs[0]; } else { return null; } } } private clearPreviousValues(): void { this.mainFormModel = null; this.formGroup = null; this.termsControl = null; } }
mukesh-openchannel/angular-template-libraries
src/form-modal.stories.ts
import { FileDetails, OcFormComponentsModule, OcFormModalComponent, FileUploaderService, } from '@openchannel/angular-common-components/src/lib/form-components'; import { moduleMetadata } from '@storybook/angular'; import { Observable, of } from 'rxjs'; import { EmbedVideoService } from 'ngx-embed-video'; import { HttpClient, HttpClientModule, HttpResponse, HttpUploadProgressEvent } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ERROR_MESSAGES_STORY_PROVIDER } from './utils.model'; class StubFileUploadDownloadService extends FileUploaderService { videoData: FileDetails = { uploadDate: 214213, fileId: 'fileId', name: 'test1.jpg', contentType: 'type', size: 123123, isPrivate: false, mimeCheck: 'PASSED', fileUrl: 'https://youtu.be/DGQwd1_dpuc', isError: false, fileUploadProgress: 100, virusScan: { started: 1457710762784, finished: 1457710769567, status: 'CLEAN', foundViruses: [], }, fileIconUrl: '', }; constructor() { super(); } fileUploadRequest( file: FormData, isPrivate: boolean, hash?: string[], ): Observable<HttpResponse<FileDetails> | HttpUploadProgressEvent> { return of(new HttpResponse({ body: this.videoData })); } fileDetailsRequest(fileId: string): Observable<FileDetails> { return of(this.videoData); } } const modules = { imports: [OcFormComponentsModule, HttpClientModule, BrowserAnimationsModule], providers: [ HttpClient, { provide: FileUploaderService, useClass: StubFileUploadDownloadService }, EmbedVideoService, ERROR_MESSAGES_STORY_PROVIDER, ], }; export default { title: 'Form Modal Component [BEM]', component: OcFormModalComponent, decorators: [moduleMetadata(modules)], argTypes: { formSubmitted: { action: 'Form Data' }, formDataUpdated: { action: 'Form Data Updates' } }, }; const FormModalComponent = (args: OcFormModalComponent) => ({ component: OcFormModalComponent, moduleMetadata: modules, props: args, }); export const FormWithTestData = FormModalComponent.bind({}); FormWithTestData.args = { formJsonData: { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { id: 'role', label: 'role', description: '', defaultValue: 'user', type: 'dropdownList', required: null, attributes: { required: true }, options: ['admin', 'user', 'test'], subFieldDefinitions: null, }, { id: 'aboutme', label: 'aboutme', description: '', defaultValue: null, type: 'richText', required: null, attributes: { maxChars: 150, required: null, minChars: 10, }, options: null, subFieldDefinitions: null, }, { id: 'skills', label: 'skills', description: 'skills', defaultValue: ['angular'], type: 'tags', required: null, attributes: { minCount: 1, maxCount: 5, required: true, }, options: ['angular', 'react', 'react native', 'spring'], subFieldDefinitions: null, }, ], }, };
mukesh-openchannel/angular-template-libraries
src/featured.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule, FullAppData, StatElement } from '@openchannel/angular-common-components/src/lib/common-components'; import { OcFeaturedAppsComponent } from '@openchannel/angular-common-components/src/lib/market-components'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; const modules = { imports: [OcCommonLibModule, BrowserAnimationsModule, RouterTestingModule], }; export default { title: 'Featured Apps [BEM]', component: OcFeaturedAppsComponent, decorators: [moduleMetadata(modules)], }; const FeaturedAppsComponent = (args: OcFeaturedAppsComponent) => ({ component: OcFeaturedAppsComponent, moduleMetadata: modules, props: args, }); const statElement: StatElement = { '90day': 20, '30day': 10, total: 20, }; const featuredApp: FullAppData = { appId: '34343-jjo-sgs-353-fgi-3423', icon: './assets/angular-common-components/get-started.svg', logo: './assets/angular-common-components/get-started.svg', name: 'Test App 1', model: [ { type: 'recurring', price: 5, trial: 1, license: 'single', modelId: '23235hfg4', currency: 'EUR', billingPeriod: 'monthly', }, ], rating: 4.2, reviewCount: 20, summary: '', description: 'With this plugin you can collaborate with teammates at any time.', lastUpdated: new Date(), version: 1.1, safeName: ['test-app'], developerId: '<PASSWORD>', submittedDate: new Date(), created: new Date().getMonth() - 2, status: { value: 'approved', lastUpdated: 1.1, modifiedBy: '', reason: '', }, statistics: { views: statElement, downloads: statElement, developerSales: statElement, totalSales: statElement, ownerships: statElement, reviews: statElement, }, isLive: true, }; export const Empty = FeaturedAppsComponent.bind({}); Empty.args = { data: [], label: 'Featured', emptyDataMessage: 'No Featured App', }; export const SingleApp = FeaturedAppsComponent.bind({}); SingleApp.args = { data: [featuredApp], label: 'Featured', emptyDataMessage: 'No Featured App', }; export const SomeApps = FeaturedAppsComponent.bind({}); SomeApps.args = { data: [featuredApp, featuredApp], label: 'Featured', emptyDataMessage: 'No Featured App', }; export const MaxApps = FeaturedAppsComponent.bind({}); MaxApps.args = { data: [featuredApp, featuredApp, featuredApp, featuredApp], label: 'Featured', emptyDataMessage: 'No Featured App', };