diff --git a/.eslintrc-angular.json b/.eslintrc-angular.json index 57c931b178..7fdd47d7cd 100644 --- a/.eslintrc-angular.json +++ b/.eslintrc-angular.json @@ -13,6 +13,8 @@ "plugin:@angular-eslint/template/process-inline-templates" ], "rules": { + // rules that need to be removed later on + "@angular-eslint/template/no-negated-async": "off", "@typescript-eslint/adjacent-overload-signatures": "warn", "@angular-eslint/directive-selector": [ diff --git a/.eslintrc.json b/.eslintrc.json index 69cfbd7609..37ac96e634 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -7,7 +7,6 @@ "@nrwl/nx", "ban", "unused-imports", - "simple-import-sort", "import", "prettier" ], @@ -61,70 +60,42 @@ "eslint:recommended" ], "rules": { - // ESLint rules - "array-bracket-spacing": "off", - "array-callback-return": "off", + // rules that need to be off for other configuration to work "arrow-body-style": "off", "arrow-parens": "off", - "curly": "off", + "implicit-arrow-linebreak": "off", + "operator-linebreak": "off", + "max-len": "off", + "@typescript-eslint/comma-dangle": "off", + "@typescript-eslint/indent": "off", + "@typescript-eslint/lines-between-class-members": "off", + // rules to work on later on + "class-methods-use-this": "off", "default-case": "off", "eqeqeq": "off", - "eol-last": "off", "consistent-return": "off", - "function-paren-newline": "off", "grouped-accessor-pairs": "off", "import/prefer-default-export": "off", - "import/first": "off", - "import/newline-after-import": "off", "import/no-cycle": "off", "import/order": ["error", { "alphabetize": { "order": "asc" } }], - "implicit-arrow-linebreak": "off", - "key-spacing": "off", - "linebreak-style": "off", "max-classes-per-file": "off", - "max-len": "off", - "new-parens": "off", - "no-confusing-arrow": "off", - "no-case-declarations": "warn", + "no-case-declarations": "off", "no-console": "off", "no-else-return": "off", - "no-floating-decimal": "off", - "no-lonely-if": "off", - "no-multiple-empty-lines": "off", - "no-multi-spaces": "off", "no-nested-ternary": "off", - "no-new": "off", "no-param-reassign": "off", "no-plusplus": "off", "no-prototype-builtins": "off", "no-redeclare": "off", - "no-restricted-globals": "off", - "no-restricted-properties": "off", "no-restricted-syntax": "off", - "no-return-assign": "off", "no-undef": "off", - "no-undef-init": "off", "no-underscore-dangle": "off", - "no-unneeded-ternary": "off", "no-unsafe-optional-chaining": "off", "no-unused-vars": "off", - "no-useless-rename": "off", - "no-useless-escape": "warn", - "nonblock-statement-body-position": "off", - "object-curly-newline": "off", - "object-shorthand": "off", - "operator-assignment": "off", - "operator-linebreak": "off", - "padded-blocks": "off", - "prefer-arrow-callback": "off", - "prefer-exponentiation-operator": "off", + "no-useless-escape": "off", "prefer-regex-literals": "off", - "prefer-template": "off", "prefer-destructuring": "off", "radix": "off", - "simple-import-sort/exports": "off", - "space-unary-ops": "off", - // eslint-plugin-unused-imports rules "unused-imports/no-unused-vars": [ "off", { @@ -134,22 +105,10 @@ "argsIgnorePattern": "^_" } ], - // TypeScript Eslint rules - "class-methods-use-this": "off", - "@typescript-eslint/comma-dangle": "off", - "@typescript-eslint/comma-spacing": "off", "@typescript-eslint/dot-notation": "off", - "@typescript-eslint/brace-style": "off", - "@typescript-eslint/lines-between-class-members": "off", "@typescript-eslint/naming-convention": "off", - "@typescript-eslint/no-shadow": "off", "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-namespace": "off", - "@typescript-eslint/no-redeclare": "off", - "@typescript-eslint/no-throw-literal": "off", - "@typescript-eslint/no-unused-vars": "off", - "@typescript-eslint/no-unused-expressions": "off", - "@typescript-eslint/no-use-before-define": "off" + "@typescript-eslint/no-unused-vars": "off" }, "parserOptions": { "project": "./tsconfig.eslint.json" diff --git a/apps/dateAdapter/src/app/app.component.ts b/apps/dateAdapter/src/app/app.component.ts index 81b7e390c1..4fadedc068 100644 --- a/apps/dateAdapter/src/app/app.component.ts +++ b/apps/dateAdapter/src/app/app.component.ts @@ -25,6 +25,7 @@ export class AppComponent { form3: UntypedFormGroup; form4: UntypedFormGroup; + // eslint-disable-next-line @typescript-eslint/no-use-before-define headerComponent = HeaderComponent; // October 13 1729 (Julian calendar) diff --git a/apps/dsp-app/src/app/main/action/sort-button/sort-button.component.ts b/apps/dsp-app/src/app/main/action/sort-button/sort-button.component.ts index 38f0d1a393..c4b6e6f2b7 100644 --- a/apps/dsp-app/src/app/main/action/sort-button/sort-button.component.ts +++ b/apps/dsp-app/src/app/main/action/sort-button/sort-button.component.ts @@ -66,7 +66,7 @@ export class SortButtonComponent implements OnInit { * @param key a string to sort by */ sortBy(key: string) { - this.activeKey = key ? key : this.sortProps[0].key; + this.activeKey = key || this.sortProps[0].key; this.sortKeyChange.emit(this.activeKey); } } diff --git a/apps/dsp-app/src/app/main/directive/admin-image/admin-image.directive.ts b/apps/dsp-app/src/app/main/directive/admin-image/admin-image.directive.ts index bcb1a8d8c3..04eee2ab82 100644 --- a/apps/dsp-app/src/app/main/directive/admin-image/admin-image.directive.ts +++ b/apps/dsp-app/src/app/main/directive/admin-image/admin-image.directive.ts @@ -1,3 +1,4 @@ +import { Location } from '@angular/common'; import { Directive, OnChanges, Input, Renderer2, ElementRef } from '@angular/core'; import { Md5 } from 'ts-md5'; import { AdminImageConfig } from './admin-image.config'; @@ -49,7 +50,9 @@ export class AdminImageDirective implements OnChanges { if (this.image === null || this.image === undefined) { this.source = AdminImageConfig.defaultUser; } else { - this.source = location.protocol + '//www.gravatar.com/avatar/' + Md5.hashStr(this.image) + '?d=mp&s=256'; + // TODO + // eslint-disable-next-line no-restricted-globals + this.source = `${location.protocol}//www.gravatar.com/avatar/${Md5.hashStr(this.image)}?d=mp&s=256`; } break; @@ -68,6 +71,6 @@ export class AdminImageDirective implements OnChanges { } this._renderer.setAttribute(this._ele.nativeElement, 'src', this.source); - this._renderer.setAttribute(this._ele.nativeElement, 'onError', "this.src='" + this.onError + "'"); + this._renderer.setAttribute(this._ele.nativeElement, 'onError', `this.src='${this.onError}'`); } } diff --git a/apps/dsp-app/src/app/main/directive/base-value.directive.ts b/apps/dsp-app/src/app/main/directive/base-value.directive.ts index 594a7f86de..b66919c819 100644 --- a/apps/dsp-app/src/app/main/directive/base-value.directive.ts +++ b/apps/dsp-app/src/app/main/directive/base-value.directive.ts @@ -116,6 +116,7 @@ export abstract class BaseValueDirective implements OnInit, OnDestroy { * @param initComment Initially given comment. * @param commentFormControl FormControl of the current comment. */ + standardValidatorFunc: (val: any, comment: string, commentCtrl: FormControl) => ValidatorFn = (initValue: any, initComment: string, commentFormControl: FormControl): ValidatorFn => (control: AbstractControl): { [key: string]: any } | null => { @@ -162,13 +163,10 @@ export abstract class BaseValueDirective implements OnInit, OnDestroy { this.standardValidatorFunc(initialValue, initialComment, this.commentFormControl), ].concat(this.customValidators) ); + } else if (this.valueRequiredValidator) { + this.valueFormControl.setValidators([Validators.required].concat(this.customValidators)); } else { - // console.log('reset read/create validators'); - if (this.valueRequiredValidator) { - this.valueFormControl.setValidators([Validators.required].concat(this.customValidators)); - } else { - this.valueFormControl.setValidators(this.customValidators); - } + this.valueFormControl.setValidators(this.customValidators); } this.valueFormControl.updateValueAndValidity(); diff --git a/apps/dsp-app/src/app/main/directive/external-links.directive.ts b/apps/dsp-app/src/app/main/directive/external-links.directive.ts index 16fdd700fa..e953be5b5b 100644 --- a/apps/dsp-app/src/app/main/directive/external-links.directive.ts +++ b/apps/dsp-app/src/app/main/directive/external-links.directive.ts @@ -17,7 +17,8 @@ export class ExternalLinksDirective implements OnChanges { // to check if we are running on the server, give a token value constructor( @Inject(PLATFORM_ID) private platformId: string, - private _sanitizer: DomSanitizer + private _sanitizer: DomSanitizer, + private location: Location ) {} ngOnChanges() { @@ -37,7 +38,7 @@ export class ExternalLinksDirective implements OnChanges { private _isLinkExternal() { return ( // get a token value from platformId to run the code only on the client and prevents errors - isPlatformBrowser(this.platformId) && !this.href.includes(location.hostname) + isPlatformBrowser(this.platformId) && !this.href.includes(this.location.hostname) ); } } diff --git a/apps/dsp-app/src/app/main/header/header.component.ts b/apps/dsp-app/src/app/main/header/header.component.ts index 715412ed15..9defa22be1 100644 --- a/apps/dsp-app/src/app/main/header/header.component.ts +++ b/apps/dsp-app/src/app/main/header/header.component.ts @@ -82,7 +82,7 @@ export class HeaderComponent implements OnInit, OnDestroy { )}`; if (this.searchParams.filter && this.searchParams.filter.limitToProject) { - doSearchRoute += '/' + encodeURIComponent(this.searchParams.filter.limitToProject); + doSearchRoute += `/${encodeURIComponent(this.searchParams.filter.limitToProject)}`; } this._router.navigate([doSearchRoute]); @@ -96,7 +96,7 @@ export class HeaderComponent implements OnInit, OnDestroy { position: { top: '112px', }, - data: { mode: mode, title: name, id: iri }, + data: { mode, title: name, id: iri }, }; this._dialog.open(DialogComponent, dialogConfig); diff --git a/apps/dsp-app/src/app/main/help/help.component.ts b/apps/dsp-app/src/app/main/help/help.component.ts index e572ae2e3b..061be33810 100644 --- a/apps/dsp-app/src/app/main/help/help.component.ts +++ b/apps/dsp-app/src/app/main/help/help.component.ts @@ -102,9 +102,9 @@ export class HelpComponent implements OnInit { ngOnInit() { this.dsp = this._appConfigService.dspConfig; - this.support[0].url += this.dsp.environment + ': ' + this.dsp.release; + this.support[0].url += `${this.dsp.environment}: ${this.dsp.release}`; - this.releaseNotesUrl = 'https://github.com/dasch-swiss/dsp-das/releases/tag/v' + this.appVersion; + this.releaseNotesUrl = `https://github.com/dasch-swiss/dsp-das/releases/tag/v${this.appVersion}`; this._dspApiConnection.system.versionEndpoint.getVersion().subscribe( (response: ApiResponseData) => { diff --git a/apps/dsp-app/src/app/main/pipes/formatting/knoradate.pipe.ts b/apps/dsp-app/src/app/main/pipes/formatting/knoradate.pipe.ts index 1a4ee4c79c..39222eafe0 100644 --- a/apps/dsp-app/src/app/main/pipes/formatting/knoradate.pipe.ts +++ b/apps/dsp-app/src/app/main/pipes/formatting/knoradate.pipe.ts @@ -23,7 +23,7 @@ export class KnoraDatePipe implements PipeTransform { // ensures that day and month are always two digits leftPadding(value: number): string { if (value !== undefined) { - return ('0' + value).slice(-2); + return `0${value}`.slice(-2); } else { return null; } @@ -34,21 +34,18 @@ export class KnoraDatePipe implements PipeTransform { switch (options) { case 'era': // displays date with era; era only in case of BCE - return value + (date.era === 'noEra' ? '' : date.era === 'BCE' || date.era === 'AD' ? ' ' + date.era : ''); + return value + (date.era === 'noEra' ? '' : date.era === 'BCE' || date.era === 'AD' ? ` ${date.era}` : ''); case 'calendar': // displays date without era but with calendar type - return value + ' ' + this._titleCase(date.calendar); + return `${value} ${this._titleCase(date.calendar)}`; case 'calendarOnly': // displays only the selected calendar type without any data return this._titleCase(date.calendar); case 'all': // displays date with era (only as BCE) and selected calendar type - return ( - value + - (date.era === 'noEra' ? '' : date.era === 'BCE' ? ' ' + date.era : '') + - ' ' + - this._titleCase(date.calendar) - ); + return `${value + (date.era === 'noEra' ? '' : date.era === 'BCE' ? ` ${date.era}` : '')} ${this._titleCase( + date.calendar + )}`; } } diff --git a/apps/dsp-app/src/app/main/pipes/isFalsy.piipe.ts b/apps/dsp-app/src/app/main/pipes/isFalsy.piipe.ts index d7b3c83897..f4aa5a20b3 100644 --- a/apps/dsp-app/src/app/main/pipes/isFalsy.piipe.ts +++ b/apps/dsp-app/src/app/main/pipes/isFalsy.piipe.ts @@ -6,6 +6,6 @@ import { Pipe, PipeTransform } from '@angular/core'; }) export class IsFalsyPipe implements PipeTransform { transform(value: any): any { - return value ? false : true; + return !value; } } diff --git a/apps/dsp-app/src/app/main/pipes/string-transformation/linkify.pipe.ts b/apps/dsp-app/src/app/main/pipes/string-transformation/linkify.pipe.ts index 4644564d58..4fae0482e9 100644 --- a/apps/dsp-app/src/app/main/pipes/string-transformation/linkify.pipe.ts +++ b/apps/dsp-app/src/app/main/pipes/string-transformation/linkify.pipe.ts @@ -13,7 +13,7 @@ export class LinkifyPipe implements PipeTransform { const match = value.match(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi); let final = value; if (match) { - match.map(url => { + match.forEach(url => { final = final.replace(url, `${url}`); }); } diff --git a/apps/dsp-app/src/app/main/pipes/string-transformation/stringify-string-literal.pipe.ts b/apps/dsp-app/src/app/main/pipes/string-transformation/stringify-string-literal.pipe.ts index 8ad7706861..9b0ccb7624 100644 --- a/apps/dsp-app/src/app/main/pipes/string-transformation/stringify-string-literal.pipe.ts +++ b/apps/dsp-app/src/app/main/pipes/string-transformation/stringify-string-literal.pipe.ts @@ -32,7 +32,7 @@ export class StringifyStringLiteralPipe implements PipeTransform { let i = 0; for (const sl of value) { const delimiter = i > 0 ? ' / ' : ''; - stringified += delimiter + sl.value + ' (' + sl.language + ')'; + stringified += `${delimiter + sl.value} (${sl.language})`; i++; } diff --git a/apps/dsp-app/src/app/main/pipes/time.pipe.ts b/apps/dsp-app/src/app/main/pipes/time.pipe.ts index f0897f5af6..2573f682cf 100644 --- a/apps/dsp-app/src/app/main/pipes/time.pipe.ts +++ b/apps/dsp-app/src/app/main/pipes/time.pipe.ts @@ -15,15 +15,11 @@ export class TimePipe implements PipeTransform { const seconds = dateObj.getSeconds(); if (hours === 0) { - return minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0'); + return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; } else { - return ( - hours.toString().padStart(2, '0') + - ':' + - minutes.toString().padStart(2, '0') + - ':' + - seconds.toString().padStart(2, '0') - ); + return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds + .toString() + .padStart(2, '0')}`; } } } diff --git a/apps/dsp-app/src/app/project/collaboration/add-user/add-user.component.ts b/apps/dsp-app/src/app/project/collaboration/add-user/add-user.component.ts index 03c66fcd7f..27a79fa874 100644 --- a/apps/dsp-app/src/app/project/collaboration/add-user/add-user.component.ts +++ b/apps/dsp-app/src/app/project/collaboration/add-user/add-user.component.ts @@ -152,9 +152,9 @@ export class AddUserComponent implements OnInit { // if the user is already member of the project // add the email to the list of existing - this.existingEmailInProject.push(new RegExp('(?:^|W)' + m.email.toLowerCase() + '(?:$|W)')); + this.existingEmailInProject.push(new RegExp(`(?:^|W)${m.email.toLowerCase()}(?:$|W)`)); // add username to the list of existing - this.existingUsernameInProject.push(new RegExp('(?:^|W)' + m.username.toLowerCase() + '(?:$|W)')); + this.existingUsernameInProject.push(new RegExp(`(?:^|W)${m.username.toLowerCase()}(?:$|W)`)); } } @@ -162,9 +162,9 @@ export class AddUserComponent implements OnInit { for (const u of response.body.users) { // if the user is already member of the project // add the email to the list of existing - this.existingEmails.push(new RegExp('(?:^|W)' + u.email.toLowerCase() + '(?:$|W)')); + this.existingEmails.push(new RegExp(`(?:^|W)${u.email.toLowerCase()}(?:$|W)`)); // add username to the list of existing - this.existingUsernames.push(new RegExp('(?:^|W)' + u.username.toLowerCase() + '(?:$|W)')); + this.existingUsernames.push(new RegExp(`(?:^|W)${u.username.toLowerCase()}(?:$|W)`)); let existsInProject = ''; @@ -175,12 +175,12 @@ export class AddUserComponent implements OnInit { this.users[i] = { iri: u.id, name: u.username, - label: existsInProject + u.username + ' | ' + u.email + ' | ' + u.givenName + ' ' + u.familyName, + label: `${existsInProject + u.username} | ${u.email} | ${u.givenName} ${u.familyName}`, }; i++; } - this.users.sort(function (u1: AutocompleteItem, u2: AutocompleteItem) { + this.users.sort((u1: AutocompleteItem, u2: AutocompleteItem) => { if (u1.label < u2.label) { return -1; } else if (u1.label > u2.label) { @@ -245,14 +245,14 @@ export class AddUserComponent implements OnInit { this.selectedUser = undefined; // check if the form is valid - Object.keys(this.selectUserErrors).map(field => { + Object.keys(this.selectUserErrors).forEach(field => { this.selectUserErrors[field] = ''; const control = this.selectUserForm.get(field); if (control.value.length >= 2) { if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map(key => { - this.selectUserErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach(key => { + this.selectUserErrors[field] += `${messages[key]} `; }); } } @@ -321,7 +321,7 @@ export class AddUserComponent implements OnInit { data: { project: this.projectUuid, name: this.selectUserForm.controls['username'].value, - mode: mode, + mode, }, }; diff --git a/apps/dsp-app/src/app/project/list/list-info-form/list-info-form.component.ts b/apps/dsp-app/src/app/project/list/list-info-form/list-info-form.component.ts index d299b50b5c..4a6304ea9f 100644 --- a/apps/dsp-app/src/app/project/list/list-info-form/list-info-form.component.ts +++ b/apps/dsp-app/src/app/project/list/list-info-form/list-info-form.component.ts @@ -165,7 +165,7 @@ export class ListInfoFormComponent implements OnInit { resetLists(ev: Event, list?: ListNodeInfo) { ev.preventDefault(); - list = list ? list : new ListNodeInfo(); + list = list || new ListNodeInfo(); this.buildLists(list); } diff --git a/apps/dsp-app/src/app/project/list/list-item-form/edit-list-item/edit-list-item.component.ts b/apps/dsp-app/src/app/project/list/list-item-form/edit-list-item/edit-list-item.component.ts index ec5c0f2c03..a4da2217e2 100644 --- a/apps/dsp-app/src/app/project/list/list-item-form/edit-list-item/edit-list-item.component.ts +++ b/apps/dsp-app/src/app/project/list/list-item-form/edit-list-item/edit-list-item.component.ts @@ -178,11 +178,9 @@ export class EditListItemComponent implements OnInit { */ insertChildNode() { const createChildNodeRequest: CreateChildNodeRequest = new CreateChildNodeRequest(); - createChildNodeRequest.name = - this._projectService.iriToUuid(this.projectIri) + - '-' + - Math.random().toString(36).substring(2) + - Math.random().toString(36).substring(2); + createChildNodeRequest.name = `${this._projectService.iriToUuid(this.projectIri)}-${Math.random() + .toString(36) + .substring(2)}${Math.random().toString(36).substring(2)}`; createChildNodeRequest.parentNodeIri = this.parentIri; createChildNodeRequest.labels = this.labels; createChildNodeRequest.comments = this.comments.length > 0 ? this.comments : undefined; diff --git a/apps/dsp-app/src/app/project/list/list-item-form/list-item-form.component.ts b/apps/dsp-app/src/app/project/list/list-item-form/list-item-form.component.ts index 3d5b5f53b1..ea6393aefd 100644 --- a/apps/dsp-app/src/app/project/list/list-item-form/list-item-form.component.ts +++ b/apps/dsp-app/src/app/project/list/list-item-form/list-item-form.component.ts @@ -161,8 +161,9 @@ export class ListItemFormComponent implements OnInit { const childNode: CreateChildNodeRequest = new CreateChildNodeRequest(); childNode.parentNodeIri = this.parentIri; childNode.projectIri = this.projectIri; - childNode.name = - this.projectUuid + '-' + Math.random().toString(36).substring(2) + Math.random().toString(36).substring(2); + childNode.name = `${this.projectUuid}-${Math.random().toString(36).substring(2)}${Math.random() + .toString(36) + .substring(2)}`; // initialize labels let i = 0; @@ -235,7 +236,7 @@ export class ListItemFormComponent implements OnInit { top: '112px', }, data: { - mode: mode, + mode, title: mode === 'editListNode' || mode === 'deleteListNode' ? name : '', id: iri, project: this.projectIri, diff --git a/apps/dsp-app/src/app/project/list/list.component.ts b/apps/dsp-app/src/app/project/list/list.component.ts index d1f095ed16..a75476b40c 100644 --- a/apps/dsp-app/src/app/project/list/list.component.ts +++ b/apps/dsp-app/src/app/project/list/list.component.ts @@ -111,7 +111,7 @@ export class ListComponent extends ProjectBase implements OnInit, OnDestroy { top: '112px', }, data: { - mode: mode, + mode, title: name, id: iri, project: this.projectUuid, diff --git a/apps/dsp-app/src/app/project/ontology-classes/ontology-class-instance/ontology-class-instance.component.ts b/apps/dsp-app/src/app/project/ontology-classes/ontology-class-instance/ontology-class-instance.component.ts index a1ec03f215..f321a019a0 100644 --- a/apps/dsp-app/src/app/project/ontology-classes/ontology-class-instance/ontology-class-instance.component.ts +++ b/apps/dsp-app/src/app/project/ontology-classes/ontology-class-instance/ontology-class-instance.component.ts @@ -42,9 +42,7 @@ export class OntologyClassInstanceComponent extends ProjectBase implements OnIni get instanceId$(): Observable { return this._route.params.pipe( takeUntil(this.ngUnsubscribe), - map(params => { - return params[RouteConstants.instanceParameter]; - }) + map(params => params[RouteConstants.instanceParameter]) ); } @@ -159,10 +157,8 @@ export class OntologyClassInstanceComponent extends ProjectBase implements OnIni if (!res || res.count <= 1) { this.viewMode = 'single'; - } else { - if (this.viewMode !== 'compare') { - this.viewMode = res && res.count > 0 ? 'intermediate' : 'single'; - } + } else if (this.viewMode !== 'compare') { + this.viewMode = res && res.count > 0 ? 'intermediate' : 'single'; } this._cdr.detectChanges(); } diff --git a/apps/dsp-app/src/app/project/ontology/ontology-form/ontology-form.component.ts b/apps/dsp-app/src/app/project/ontology/ontology-form/ontology-form.component.ts index 7b0f07fe20..22fd45a716 100644 --- a/apps/dsp-app/src/app/project/ontology/ontology-form/ontology-form.component.ts +++ b/apps/dsp-app/src/app/project/ontology/ontology-form/ontology-form.component.ts @@ -83,15 +83,15 @@ export class OntologyFormComponent implements OnInit, OnDestroy { validationMessages = { name: { required: 'Name is required.', - minlength: 'Name must be at least ' + this.nameMinLength + ' characters long.', - maxlength: 'Name cannot be more than ' + this.nameMaxLength + ' characters long.', + minlength: `Name must be at least ${this.nameMinLength} characters long.`, + maxlength: `Name cannot be more than ${this.nameMaxLength} characters long.`, pattern: "Name shouldn't start with a number or v + number and spaces or special characters (except dash, dot and underscore) are not allowed.", existingName: 'This name is not allowed or exists already.', }, label: { required: 'Label is required.', - minlength: 'Label must be at least ' + this.nameMinLength + ' characters long.', + minlength: `Label must be at least ${this.nameMinLength} characters long.`, }, }; @@ -172,7 +172,7 @@ export class OntologyFormComponent implements OnInit, OnDestroy { // name has to be unique; if it already exists // show an error message for (const name of this.existingOntologyNames) { - this.existingNames.push(new RegExp('(?:^|W)' + name + '(?:$|W)')); + this.existingNames.push(new RegExp(`(?:^|W)${name}(?:$|W)`)); } for (const name of this.forbiddenNames) { @@ -222,13 +222,13 @@ export class OntologyFormComponent implements OnInit, OnDestroy { return; } - Object.keys(this.formErrors).map(field => { + Object.keys(this.formErrors).forEach(field => { this.formErrors[field] = ''; const control = this.ontologyForm.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map(key => { - this.formErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach(key => { + this.formErrors[field] += `${messages[key]} `; }); } }); @@ -265,7 +265,7 @@ export class OntologyFormComponent implements OnInit, OnDestroy { } else { // create mode const ontologyData = new CreateOntology(); - ontologyData.label = this.project.shortname + ': ' + this.ontologyForm.controls['label'].value; + ontologyData.label = `${this.project.shortname}: ${this.ontologyForm.controls['label'].value}`; ontologyData.name = this.ontologyForm.controls['name'].value; ontologyData.comment = this.ontologyForm.controls['comment'].value; ontologyData.attachedToProject = this.project.id; @@ -285,7 +285,7 @@ export class OntologyFormComponent implements OnInit, OnDestroy { }, (error: ApiResponseError) => { // in case of an error... e.g. because the ontolog iri is not unique, rebuild the form including the error message - this.formErrors['name'] += this.validationMessages['name']['existingName'] + ' '; + this.formErrors['name'] += `${this.validationMessages['name']['existingName']} `; this.loading = false; this._errorHandler.showMessage(error); diff --git a/apps/dsp-app/src/app/project/ontology/ontology.component.ts b/apps/dsp-app/src/app/project/ontology/ontology.component.ts index 0092f482b4..91495b9e8e 100644 --- a/apps/dsp-app/src/app/project/ontology/ontology.component.ts +++ b/apps/dsp-app/src/app/project/ontology/ontology.component.ts @@ -138,9 +138,7 @@ export class OntologyComponent extends ProjectBase implements OnInit, OnDestroy get isLoading$(): Observable { return combineLatest([this.isOntologiesLoading$, this.isProjectsLoading$]).pipe( takeUntil(this.ngUnsubscribe), - map(([isOntologiesLoading, isProjectsLoading]) => { - return isOntologiesLoading === true || isProjectsLoading === true; - }) + map(([isOntologiesLoading, isProjectsLoading]) => isOntologiesLoading === true || isProjectsLoading === true) ); } @@ -439,8 +437,8 @@ export class OntologyComponent extends ProjectBase implements OnInit, OnDestroy top: '112px', }, data: { - mode: mode, - title: title, + mode, + title, id: iri, project: uuid, existing: existingOntologyNames, @@ -470,7 +468,7 @@ export class OntologyComponent extends ProjectBase implements OnInit, OnDestroy id: resClassInfo.iri, title: resClassInfo.label, subtitle: 'Customize resource class', - mode: mode, + mode, }, }; @@ -491,7 +489,7 @@ export class OntologyComponent extends ProjectBase implements OnInit, OnDestroy openPropertyForm(mode: 'createProperty' | 'editProperty', propertyInfo: PropertyInfoObject): void { const title = propertyInfo.propDef ? propertyInfo.propDef.label - : propertyInfo.propType.group + ': ' + propertyInfo.propType.label; + : `${propertyInfo.propType.group}: ${propertyInfo.propType.label}`; const dialogConfig: MatDialogConfig = { width: '640px', @@ -501,9 +499,9 @@ export class OntologyComponent extends ProjectBase implements OnInit, OnDestroy }, data: { propInfo: propertyInfo, - title: title, + title, subtitle: 'Customize property', - mode: mode, + mode, }, }; @@ -534,7 +532,7 @@ export class OntologyComponent extends ProjectBase implements OnInit, OnDestroy position: { top: '112px', }, - data: { mode: 'delete' + mode, title: info.label }, + data: { mode: `delete${mode}`, title: info.label }, }; const dialogRef = this._dialog.open(DialogComponent, dialogConfig); diff --git a/apps/dsp-app/src/app/project/ontology/property-form/property-form.component.ts b/apps/dsp-app/src/app/project/ontology/property-form/property-form.component.ts index 69603209bc..56fa1a3b46 100644 --- a/apps/dsp-app/src/app/project/ontology/property-form/property-form.component.ts +++ b/apps/dsp-app/src/app/project/ontology/property-form/property-form.component.ts @@ -201,13 +201,13 @@ export class PropertyFormComponent implements OnInit, OnDestroy { // set list of all existing resource property names to avoid same name twice resourceProperties.forEach((resProp: PropertyDefinition) => { const name = this._os.getNameFromIri(resProp.id); - this.existingNames.push(new RegExp('(?:^|W)' + name.toLowerCase() + '(?:$|W)')); + this.existingNames.push(new RegExp(`(?:^|W)${name.toLowerCase()}(?:$|W)`)); }); // add all resource classes to the same list getAllEntityDefinitionsAsArray(response.classes).forEach((resClass: ClassDefinition) => { const name = this._os.getNameFromIri(resClass.id); - this.existingNames.push(new RegExp('(?:^|W)' + name.toLowerCase() + '(?:$|W)')); + this.existingNames.push(new RegExp(`(?:^|W)${name.toLowerCase()}(?:$|W)`)); }); }); @@ -336,13 +336,13 @@ export class PropertyFormComponent implements OnInit, OnDestroy { return; } - Object.keys(this.formErrors).map(field => { + Object.keys(this.formErrors).forEach(field => { this.formErrors[field] = ''; const control = this.propertyForm.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map(key => { - this.formErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach(key => { + this.formErrors[field] += `${messages[key]} `; }); } }); @@ -806,21 +806,21 @@ export class PropertyFormComponent implements OnInit, OnDestroy { switch (this.propertyInfo.propType.guiEle) { case Constants.GuiColorPicker: - guiAttributes = ['ncolors=' + guiAttr]; + guiAttributes = [`ncolors=${guiAttr}`]; break; case Constants.GuiList: case Constants.GuiPulldown: case Constants.GuiRadio: - guiAttributes = ['hlist=<' + guiAttr + '>']; + guiAttributes = [`hlist=<${guiAttr}>`]; break; case Constants.GuiSimpleText: // --> TODO could have two guiAttr fields: size and maxlength // we suggest to use default value for size; we do not support this guiAttr in DSP-App - guiAttributes = ['maxlength=' + guiAttr]; + guiAttributes = [`maxlength=${guiAttr}`]; break; case Constants.GuiSpinbox: // --> TODO could have two guiAttr fields: min and max - guiAttributes = ['min=' + guiAttr, 'max=' + guiAttr]; + guiAttributes = [`min=${guiAttr}`, `max=${guiAttr}`]; break; case Constants.GuiTextarea: // --> TODO could have four guiAttr fields: width, cols, rows, wrap @@ -845,17 +845,13 @@ export class PropertyFormComponent implements OnInit, OnDestroy { if (this.targetGuiCardinality.key === 'multiple' && this.targetGuiCardinality.value === false) { // there are instances which have that property multiple times and do not allow to set multiple to false reason.detail = `At least one ${classLabel} has multiple ${pLabel} properties in your data.`; - reason.hint = - `In order to change the data model and set the property ${pLabel} from multiple to ` + - `single, every ${classLabel} must have only one ${pLabel} in the data.`; + reason.hint = `In order to change the data model and set the property ${pLabel} from multiple to single, every ${classLabel} must have only one ${pLabel} in the data.`; } if (this.targetGuiCardinality.key === 'required' && this.targetGuiCardinality.value === true) { // setting from multiple to single is not possible because there are instances which have that property // multiple times and do not allow to set multiple to false reason.detail = `At least one ${classLabel} does not have a ${pLabel} property in your data.`; - reason.hint = - `In order to change the data model and set the property ${pLabel} to required ` + - `every ${classLabel} needs to have a ${pLabel} in the data.`; + reason.hint = `In order to change the data model and set the property ${pLabel} to required every ${classLabel} needs to have a ${pLabel} in the data.`; } } return reason; diff --git a/apps/dsp-app/src/app/project/ontology/property-info/property-info.component.ts b/apps/dsp-app/src/app/project/ontology/property-info/property-info.component.ts index 4d586e8e14..4ac391fd4f 100644 --- a/apps/dsp-app/src/app/project/ontology/property-info/property-info.component.ts +++ b/apps/dsp-app/src/app/project/ontology/property-info/property-info.component.ts @@ -188,7 +188,7 @@ export class PropertyInfoComponent implements OnChanges, AfterContentInit { const propOfClass: ShortInfo = { id: resClass.id, label: resClass.label, - comment: onto.label + (resClass.comment ? ': ' + resClass.comment : ''), + comment: onto.label + (resClass.comment ? `: ${resClass.comment}` : ''), }; this.resClasses.push(propOfClass); } diff --git a/apps/dsp-app/src/app/project/ontology/resource-class-form/resource-class-form.component.ts b/apps/dsp-app/src/app/project/ontology/resource-class-form/resource-class-form.component.ts index 7f4d9557c3..026a187404 100644 --- a/apps/dsp-app/src/app/project/ontology/resource-class-form/resource-class-form.component.ts +++ b/apps/dsp-app/src/app/project/ontology/resource-class-form/resource-class-form.component.ts @@ -160,13 +160,13 @@ export class ResourceClassFormComponent implements OnInit, AfterViewChecked { // set list of all existing resource class names to avoid same name twice resourceClasses.forEach((resClass: ClassDefinition) => { const name = this._os.getNameFromIri(resClass.id); - this.existingNames.push(new RegExp('(?:^|W)' + name.toLowerCase() + '(?:$|W)')); + this.existingNames.push(new RegExp(`(?:^|W)${name.toLowerCase()}(?:$|W)`)); }); // add all resource properties to the same list resourceProperties.forEach((resProp: PropertyDefinition) => { const name = this._os.getNameFromIri(resProp.id); - this.existingNames.push(new RegExp('(?:^|W)' + name.toLowerCase() + '(?:$|W)')); + this.existingNames.push(new RegExp(`(?:^|W)${name.toLowerCase()}(?:$|W)`)); }); this.buildForm(); @@ -230,13 +230,13 @@ export class ResourceClassFormComponent implements OnInit, AfterViewChecked { return; } - Object.keys(this.formErrors).map(field => { + Object.keys(this.formErrors).forEach(field => { this.formErrors[field] = ''; const control = this.resourceClassForm.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map(key => { - this.formErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach(key => { + this.formErrors[field] += `${messages[key]} `; }); } }); diff --git a/apps/dsp-app/src/app/project/ontology/resource-class-info/resource-class-info.component.ts b/apps/dsp-app/src/app/project/ontology/resource-class-info/resource-class-info.component.ts index eadb8e3713..8b5ab626c7 100644 --- a/apps/dsp-app/src/app/project/ontology/resource-class-info/resource-class-info.component.ts +++ b/apps/dsp-app/src/app/project/ontology/resource-class-info/resource-class-info.component.ts @@ -296,7 +296,7 @@ export class ResourceClassInfoComponent implements OnInit, OnDestroy { const propertyAssignment: PropertyAssignment = { resClass: this.resourceClass, property: { - propType: propType, + propType, }, }; this.assignProperty(propertyAssignment, currentOntologyPropertiesToDisplay); @@ -344,13 +344,13 @@ export class ResourceClassInfoComponent implements OnInit, OnDestroy { const classLabel = propertyAssignment.resClass.label; let mode: 'createProperty' | 'editProperty' = 'createProperty'; - let propLabel = propertyAssignment.property.propType.group + ': ' + propertyAssignment.property.propType.label; - let title = 'Add new property of type "' + propLabel + '" to class "' + classLabel + '"'; + let propLabel = `${propertyAssignment.property.propType.group}: ${propertyAssignment.property.propType.label}`; + let title = `Add new property of type "${propLabel}" to class "${classLabel}"`; if (propertyAssignment.property.propDef) { // the property already exists. To assign an existing property simply open the dialog in edit mode mode = 'editProperty'; propLabel = propertyAssignment.property.propDef.label; - title = 'Add existing property "' + propLabel + '" to class "' + classLabel + '"'; + title = `Add existing property "${propLabel}" to class "${classLabel}"`; } const dialogConfig: MatDialogConfig = { @@ -361,9 +361,9 @@ export class ResourceClassInfoComponent implements OnInit, OnDestroy { }, data: { propInfo: propertyAssignment.property, - title: title, + title, subtitle: 'Customize property and cardinality', - mode: mode, + mode, parentIri: propertyAssignment.resClass.id, position: currentOntologyPropertiesToDisplay.length + 1, }, @@ -489,7 +489,7 @@ OFFSET 0`; const existingProperties: PropToAdd[] = []; const currentProjectOntologies = this._store.selectSnapshot(OntologiesSelectors.currentProjectOntologies); ontoProperties.forEach((op: OntologyProperties, i: number) => { - const onto = currentProjectOntologies.find(i => i?.id === op.ontology); + const onto = currentProjectOntologies.find(j => j?.id === op.ontology); existingProperties.push({ ontologyId: op.ontology, ontologyLabel: onto?.label, @@ -509,7 +509,7 @@ OFFSET 0`; }); const propToAdd: PropertyInfoObject = { - propType: propType, + propType, propDef: availableProp, }; diff --git a/apps/dsp-app/src/app/project/project-base.ts b/apps/dsp-app/src/app/project/project-base.ts index 20dfb65928..e5a4897102 100644 --- a/apps/dsp-app/src/app/project/project-base.ts +++ b/apps/dsp-app/src/app/project/project-base.ts @@ -73,12 +73,10 @@ export class ProjectBase implements OnInit, OnDestroy { // get current project data, project members and project groups // and set the project state here this.loadProject(); - } else { - if (!this.isOntologiesAvailable()) { - this.isProjectsLoading$.pipe(takeWhile(isLoading => isLoading === false)).subscribe((isLoading: boolean) => { - this._store.dispatch(new LoadProjectOntologiesAction(this.projectUuid)); - }); - } + } else if (!this.isOntologiesAvailable()) { + this.isProjectsLoading$.pipe(takeWhile(isLoading => isLoading === false)).subscribe((isLoading: boolean) => { + this._store.dispatch(new LoadProjectOntologiesAction(this.projectUuid)); + }); } } diff --git a/apps/dsp-app/src/app/project/project-form/project-form.component.ts b/apps/dsp-app/src/app/project/project-form/project-form.component.ts index 40e8aa75f4..673e45f09e 100644 --- a/apps/dsp-app/src/app/project/project-form/project-form.component.ts +++ b/apps/dsp-app/src/app/project/project-form/project-form.component.ts @@ -106,8 +106,8 @@ export class ProjectFormComponent implements OnInit { validationMessages = { shortname: { required: 'Short name is required.', - minlength: 'Short name must be at least ' + this.shortnameMinLength + ' characters long.', - maxlength: 'Short name cannot be more than ' + this.shortnameMaxLength + ' characters long.', + minlength: `Short name must be at least ${this.shortnameMinLength} characters long.`, + maxlength: `Short name cannot be more than ${this.shortnameMaxLength} characters long.`, pattern: "Short name shouldn't start with a number; Spaces are not allowed.", existingName: 'This short name is already taken.', }, @@ -116,14 +116,14 @@ export class ProjectFormComponent implements OnInit { }, shortcode: { required: 'Shortcode is required', - maxlength: 'Shortcode cannot be more than ' + this.shortcodeMaxLength + ' characters long.', - minlength: 'Shortcode cannot be less than ' + this.shortcodeMinLength + ' characters long.', + maxlength: `Shortcode cannot be more than ${this.shortcodeMaxLength} characters long.`, + minlength: `Shortcode cannot be less than ${this.shortcodeMinLength} characters long.`, pattern: 'This is not a hexadecimal value!', existingName: 'This shortcode is already taken.', }, description: { required: 'A description is required.', - maxlength: 'Description cannot be more than ' + this.descriptionMaxLength + ' characters long.', + maxlength: `Description cannot be more than ${this.descriptionMaxLength} characters long.`, }, keywords: { required: 'At least one keyword is required.', @@ -182,10 +182,10 @@ export class ProjectFormComponent implements OnInit { this._projectApiService.list().subscribe( response => { for (const project of response.projects) { - this.existingShortNames.push(new RegExp('(?:^|W)' + project.shortname.toLowerCase() + '(?:$|W)')); + this.existingShortNames.push(new RegExp(`(?:^|W)${project.shortname.toLowerCase()}(?:$|W)`)); if (project.shortcode !== null) { - this.existingShortcodes.push(new RegExp('(?:^|W)' + project.shortcode.toLowerCase() + '(?:$|W)')); + this.existingShortcodes.push(new RegExp(`(?:^|W)${project.shortcode.toLowerCase()}(?:$|W)`)); } } }, @@ -246,7 +246,7 @@ export class ProjectFormComponent implements OnInit { longname: new UntypedFormControl( { value: project.longname, - disabled: disabled, + disabled, }, [Validators.required] ), @@ -265,14 +265,14 @@ export class ProjectFormComponent implements OnInit { ), logo: new UntypedFormControl({ value: project.logo, - disabled: disabled, + disabled, }), status: [true], selfjoin: [false], keywords: new UntypedFormControl({ // must be empty (even in edit mode), because of the mat-chip-list value: [], - disabled: disabled, + disabled, }), }); @@ -295,13 +295,13 @@ export class ProjectFormComponent implements OnInit { const form = this.form; - Object.keys(this.formErrors).map(field => { + Object.keys(this.formErrors).forEach(field => { this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map(key => { - this.formErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach(key => { + this.formErrors[field] += `${messages[key]} `; }); } }); diff --git a/apps/dsp-app/src/app/project/project.component.ts b/apps/dsp-app/src/app/project/project.component.ts index a87d376557..2ff749eec3 100644 --- a/apps/dsp-app/src/app/project/project.component.ts +++ b/apps/dsp-app/src/app/project/project.component.ts @@ -83,9 +83,7 @@ export class ProjectComponent extends ProjectBase implements OnInit { get isLoading$(): Observable { return combineLatest([this.isOntologiesLoading$, this.isProjectsLoading$]).pipe( - map(([isOntologiesLoading, isProjectsLoading]) => { - return isOntologiesLoading === true || isProjectsLoading === true; - }) + map(([isOntologiesLoading, isProjectsLoading]) => isOntologiesLoading === true || isProjectsLoading === true) ); } @@ -143,10 +141,9 @@ export class ProjectComponent extends ProjectBase implements OnInit { } } - this.componentCommsSubscription = this._componentCommsService.on( - Events.unselectedListItem, - () => (this.listItemSelected = '') - ); + this.componentCommsSubscription = this._componentCommsService.on(Events.unselectedListItem, () => { + this.listItemSelected = ''; + }); } ngOnDestroy() { diff --git a/apps/dsp-app/src/app/system/projects/projects-list/projects-list.component.ts b/apps/dsp-app/src/app/system/projects/projects-list/projects-list.component.ts index a6db70bf8c..49a666a6eb 100644 --- a/apps/dsp-app/src/app/system/projects/projects-list/projects-list.component.ts +++ b/apps/dsp-app/src/app/system/projects/projects-list/projects-list.component.ts @@ -110,9 +110,7 @@ export class ProjectsListComponent implements OnInit, OnDestroy { userHasPermission$(projectIri: string): Observable { return combineLatest([this.user$, this.userProjectAdminGroups$]).pipe( takeUntil(this.ngUnsubscribe), - map(([user, userProjectGroups]) => { - return ProjectService.IsProjectAdminOrSysAdmin(user, userProjectGroups, projectIri); - }) + map(([user, userProjectGroups]) => ProjectService.IsProjectAdminOrSysAdmin(user, userProjectGroups, projectIri)) ); } @@ -125,9 +123,7 @@ export class ProjectsListComponent implements OnInit, OnDestroy { return combineLatest([this.user$, this.userProjectAdminGroups$]).pipe( takeUntil(this.ngUnsubscribe), // eslint-disable-next-line @typescript-eslint/no-unused-vars - map(([user, userProjectGroups]) => { - return ProjectService.IsInProjectGroup(userProjectGroups, projectIri); - }) + map(([user, userProjectGroups]) => ProjectService.IsInProjectGroup(userProjectGroups, projectIri)) ); } @@ -160,7 +156,7 @@ export class ProjectsListComponent implements OnInit, OnDestroy { position: { top: '112px', }, - data: { name: name, mode: mode, project: id }, + data: { name, mode, project: id }, }; const dialogRef = this._dialog.open(DialogComponent, dialogConfig); diff --git a/apps/dsp-app/src/app/system/projects/projects.component.ts b/apps/dsp-app/src/app/system/projects/projects.component.ts index 7532f516ad..fcdeef2bfd 100644 --- a/apps/dsp-app/src/app/system/projects/projects.component.ts +++ b/apps/dsp-app/src/app/system/projects/projects.component.ts @@ -59,7 +59,11 @@ export class ProjectsComponent implements OnInit, OnDestroy { ) {} ngOnInit() { - this.username ? this._titleService.setTitle('Your projects') : this._titleService.setTitle('All projects from DSP'); + if (this.username) { + this._titleService.setTitle('Your projects'); + } else { + this._titleService.setTitle('All projects from DSP'); + } if (this._store.selectSnapshot(ProjectsSelectors.allProjects).length === 0) { this.refresh(); diff --git a/apps/dsp-app/src/app/user/account/account.component.ts b/apps/dsp-app/src/app/user/account/account.component.ts index a753d84508..a3ce5b66d9 100644 --- a/apps/dsp-app/src/app/user/account/account.component.ts +++ b/apps/dsp-app/src/app/user/account/account.component.ts @@ -54,7 +54,7 @@ export class AccountComponent implements OnInit { position: { top: '112px', }, - data: { name: name, mode: mode }, + data: { name, mode }, }) .afterClosed() .subscribe(response => { diff --git a/apps/dsp-app/src/app/user/membership/membership.component.ts b/apps/dsp-app/src/app/user/membership/membership.component.ts index 3e405f7a3f..65ba475148 100644 --- a/apps/dsp-app/src/app/user/membership/membership.component.ts +++ b/apps/dsp-app/src/app/user/membership/membership.component.ts @@ -100,28 +100,32 @@ export class MembershipComponent implements OnDestroy { } private getProjects(projects: StoredProject[], user: ReadUser): AutocompleteItem[] { - return projects - .map(p => { - if ( - p.id !== Constants.SystemProjectIRI && - p.id !== Constants.DefaultSharedOntologyIRI && - p.status === true && - user.projects.findIndex(i => i.id === p.id) === -1 - ) { - return { - iri: p.id, - name: `${p.longname} (${p.shortname})`, - }; - } - }) - .sort(function (u1: AutocompleteItem, u2: AutocompleteItem) { - if (u1.name < u2.name) { - return -1; - } else if (u1.name > u2.name) { - return 1; - } else { - return 0; - } - }); + // TODO code smell, next line should not be disabled!!! + return ( + projects + // eslint-disable-next-line array-callback-return + .map(p => { + if ( + p.id !== Constants.SystemProjectIRI && + p.id !== Constants.DefaultSharedOntologyIRI && + p.status === true && + user.projects.findIndex(i => i.id === p.id) === -1 + ) { + return { + iri: p.id, + name: `${p.longname} (${p.shortname})`, + }; + } + }) + .sort((u1: AutocompleteItem, u2: AutocompleteItem) => { + if (u1.name < u2.name) { + return -1; + } else if (u1.name > u2.name) { + return 1; + } else { + return 0; + } + }) + ); } } diff --git a/apps/dsp-app/src/app/user/user-form/password-form/password-form.component.ts b/apps/dsp-app/src/app/user/user-form/password-form/password-form.component.ts index 18ab5c7e3a..047d02c7ee 100644 --- a/apps/dsp-app/src/app/user/user-form/password-form/password-form.component.ts +++ b/apps/dsp-app/src/app/user/user-form/password-form/password-form.component.ts @@ -88,14 +88,16 @@ export class PasswordFormComponent implements OnInit { if (usernameFromState === this.user.username) { // update own password this.updateOwn = true; - } else { + } else if (userFromState.systemAdmin) { // update not own password, if logged-in user is system admin - if (userFromState.systemAdmin) { - this.updateOwn = false; - } + this.updateOwn = false; } this.showPasswordForm = this.updateOwn; - this.updateOwn ? this.buildForm() : this.buildConfirmForm(); + if (this.updateOwn) { + this.buildForm(); + } else { + this.buildConfirmForm(); + } } else { // create new password this.updateOwn = false; @@ -185,13 +187,13 @@ export class PasswordFormComponent implements OnInit { onValueChanged(form: UntypedFormGroup) { // const form = this.userPasswordForm; - Object.keys(this.formErrors).map(field => { + Object.keys(this.formErrors).forEach(field => { this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map(key => { - this.formErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach(key => { + this.formErrors[field] += `${messages[key]} `; }); } }); @@ -235,7 +237,7 @@ export class PasswordFormComponent implements OnInit { this._userApiService.updatePassword(this.user.id, requesterPassword, this.form.controls.password.value).subscribe( () => { - const successResponse = 'You have successfully updated ' + (this.updateOwn ? 'your' : "user's") + ' password.'; + const successResponse = `You have successfully updated ${this.updateOwn ? 'your' : "user's"} password.`; this._notification.openSnackBar(successResponse); this.closeDialog.emit(); this.form.reset(); diff --git a/apps/dsp-app/src/app/user/user-form/user-form.component.ts b/apps/dsp-app/src/app/user/user-form/user-form.component.ts index d40551a2ce..7b9700733d 100644 --- a/apps/dsp-app/src/app/user/user-form/user-form.component.ts +++ b/apps/dsp-app/src/app/user/user-form/user-form.component.ts @@ -118,7 +118,7 @@ export class UserFormComponent implements OnInit, OnChanges { username: { required: 'Username is required.', pattern: 'Spaces and special characters are not allowed in username', - minlength: 'Username must be at least ' + this.usernameMinLength + ' characters long.', + minlength: `Username must be at least ${this.usernameMinLength} characters long.`, existingName: 'This user exists already. If you want to edit it, ask a system administrator.', member: 'This user is already a member of the project.', }, @@ -175,10 +175,10 @@ export class UserFormComponent implements OnInit, OnChanges { for (const user of allUsers) { // email address of the user should be unique. // therefore we create a list of existing email addresses to avoid multiple use of user names - this.existingEmails.push(new RegExp('(?:^|W)' + user.email.toLowerCase() + '(?:$|W)')); + this.existingEmails.push(new RegExp(`(?:^|W)${user.email.toLowerCase()}(?:$|W)`)); // username should also be unique. // therefore we create a list of existingUsernames to avoid multiple use of user names - this.existingUsernames.push(new RegExp('(?:^|W)' + user.username.toLowerCase() + '(?:$|W)')); + this.existingUsernames.push(new RegExp(`(?:^|W)${user.username.toLowerCase()}(?:$|W)`)); } const newUser: ReadUser = new ReadUser(); @@ -283,13 +283,13 @@ export class UserFormComponent implements OnInit, OnChanges { const form = this.userForm; - Object.keys(this.formErrors).map(field => { + Object.keys(this.formErrors).forEach(field => { this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map(key => { - this.formErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach(key => { + this.formErrors[field] += `${messages[key]} `; }); } }); diff --git a/apps/dsp-app/src/app/workspace/intermediate/intermediate.component.ts b/apps/dsp-app/src/app/workspace/intermediate/intermediate.component.ts index 946183ee8c..6c4031e343 100644 --- a/apps/dsp-app/src/app/workspace/intermediate/intermediate.component.ts +++ b/apps/dsp-app/src/app/workspace/intermediate/intermediate.component.ts @@ -35,7 +35,7 @@ export class IntermediateComponent { * @param data */ openDialog(type: 'link', data: FilteredResources) { - const title = 'Create a collection of ' + data.count + ' resources'; + const title = `Create a collection of ${data.count} resources`; const dialogConfig: MatDialogConfig = { width: '640px', @@ -45,7 +45,7 @@ export class IntermediateComponent { }, data: { mode: 'linkResources', - title: title, + title, selectedResources: data, }, }; diff --git a/apps/dsp-app/src/app/workspace/resource/operations/display-edit/display-edit.component.ts b/apps/dsp-app/src/app/workspace/resource/operations/display-edit/display-edit.component.ts index 642ce09687..8bbbd28670 100644 --- a/apps/dsp-app/src/app/workspace/resource/operations/display-edit/display-edit.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/operations/display-edit/display-edit.component.ts @@ -158,13 +158,13 @@ export class DisplayEditComponent implements OnInit { .getPropertyDefinitionsByType(ResourcePropertyDefinition) .filter((propDef: ResourcePropertyDefinition) => propDef.id === this.displayValue.property); - if (resPropDef[0].guiElement === Constants.SalsahGui + Constants.HashDelimiter + 'Textarea') { + if (resPropDef[0].guiElement === `${Constants.SalsahGui + Constants.HashDelimiter}Textarea`) { this.textArea = true; } if (resPropDef.length !== 1) { // this should never happen because we always have the property info for the given value - throw new Error('Resource Property Definition could not be found: ' + this.displayValue.property); + throw new Error(`Resource Property Definition could not be found: ${this.displayValue.property}`); } this.readOnlyValue = this._valueService.isReadOnly(this.valueTypeOrClass, this.displayValue, resPropDef[0]); @@ -178,9 +178,9 @@ export class DisplayEditComponent implements OnInit { } getTooltipText(): string { - const creationDate = 'Creation date: ' + this.displayValue.valueCreationDate; + const creationDate = `Creation date: ${this.displayValue.valueCreationDate}`; - const creatorInfo = this.user ? '\n Value creator: ' + this.user?.givenName + ' ' + this.user?.familyName : ''; + const creatorInfo = this.user ? `\n Value creator: ${this.user?.givenName} ${this.user?.familyName}` : ''; return creationDate + creatorInfo; } diff --git a/apps/dsp-app/src/app/workspace/resource/permission-info/permission-info.component.ts b/apps/dsp-app/src/app/workspace/resource/permission-info/permission-info.component.ts index 474e99b328..57926a1b74 100644 --- a/apps/dsp-app/src/app/workspace/resource/permission-info/permission-info.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/permission-info/permission-info.component.ts @@ -189,18 +189,16 @@ export class PermissionInfoComponent implements OnInit { const index = this.listOfPermissions.findIndex((object: PermissionGroup) => object.group === group); const permission: PermissionGroup = { - group: group, - restriction: restriction, + group, + restriction, }; // add to list of Permissions if it does not exist yet if (index === -1) { this.listOfPermissions.push(permission); - } else { + } else if (this.listOfPermissions[index].restriction.length < restriction.length) { // if it exists, compare the permission level and replace if it's higher - if (this.listOfPermissions[index].restriction.length < restriction.length) { - this.listOfPermissions[index] = permission; - } + this.listOfPermissions[index] = permission; } } } diff --git a/apps/dsp-app/src/app/workspace/resource/properties/properties.component.ts b/apps/dsp-app/src/app/workspace/resource/properties/properties.component.ts index e0146c0d1f..8546737b74 100644 --- a/apps/dsp-app/src/app/workspace/resource/properties/properties.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/properties/properties.component.ts @@ -266,7 +266,7 @@ export class PropertiesComponent implements OnInit, OnChanges, OnDestroy { */ openProject(project: ReadProject) { const uuid = this._projectService.iriToUuid(project.id); - window.open('/project/' + uuid, '_blank'); + window.open(`/project/${uuid}`, '_blank'); } previewProject() { @@ -305,7 +305,7 @@ export class PropertiesComponent implements OnInit, OnChanges, OnDestroy { openResource(linkValue: ReadLinkValue | string) { const iri = typeof linkValue == 'string' ? linkValue : linkValue.linkedResourceIri; const path = this._resourceService.getResourcePath(iri); - window.open('/resource' + path, '_blank'); + window.open(`/resource${path}`, '_blank'); } previewResource() { @@ -319,7 +319,7 @@ export class PropertiesComponent implements OnInit, OnChanges, OnDestroy { position: { top: '112px', }, - data: { mode: type + 'Resource', title: this.resource.res.label }, + data: { mode: `${type}Resource`, title: this.resource.res.label }, }; const dialogRef = this._dialog.open(DialogComponent, dialogConfig); @@ -377,33 +377,31 @@ export class PropertiesComponent implements OnInit, OnChanges, OnDestroy { ); break; } - } else { + } else if (this.resource.res.label !== answer.comment) { // update resource's label if it has changed - if (this.resource.res.label !== answer.comment) { - // get the correct lastModificationDate from the resource - this._dspApiConnection.v2.res.getResource(this.resource.res.id).subscribe((res: ReadResource) => { - const payload = new UpdateResourceMetadata(); - payload.id = this.resource.res.id; - payload.type = this.resource.res.type; - payload.lastModificationDate = res.lastModificationDate; - payload.label = answer.comment; - - this._dspApiConnection.v2.res.updateResourceMetadata(payload).subscribe( - (response: UpdateResourceMetadataResponse) => { - this.resource.res.label = payload.label; - this.lastModificationDate = response.lastModificationDate; - // if annotations tab is active; a label of a region has been changed --> update regions - if (this.isAnnotation) { - this.regionChanged.emit(); - } - this._cd.markForCheck(); - }, - (error: ApiResponseError) => { - this._errorHandler.showMessage(error); + // get the correct lastModificationDate from the resource + this._dspApiConnection.v2.res.getResource(this.resource.res.id).subscribe((res: ReadResource) => { + const payload = new UpdateResourceMetadata(); + payload.id = this.resource.res.id; + payload.type = this.resource.res.type; + payload.lastModificationDate = res.lastModificationDate; + payload.label = answer.comment; + + this._dspApiConnection.v2.res.updateResourceMetadata(payload).subscribe( + (response: UpdateResourceMetadataResponse) => { + this.resource.res.label = payload.label; + this.lastModificationDate = response.lastModificationDate; + // if annotations tab is active; a label of a region has been changed --> update regions + if (this.isAnnotation) { + this.regionChanged.emit(); } - ); - }); - } + this._cd.markForCheck(); + }, + (error: ApiResponseError) => { + this._errorHandler.showMessage(error); + } + ); + }); } } }); diff --git a/apps/dsp-app/src/app/workspace/resource/representation/archive/archive.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/archive/archive.component.ts index 0206f2a017..0f34111b2f 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/archive/archive.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/archive/archive.component.ts @@ -51,8 +51,12 @@ export class ArchiveComponent implements OnInit, AfterViewInit { ngOnInit(): void { this._rs.getFileInfo(this.src.fileValue.fileUrl).subscribe( - res => (this.originalFilename = res['originalFilename']), - () => (this.failedToLoad = true) + res => { + this.originalFilename = res['originalFilename']; + }, + () => { + this.failedToLoad = true; + } ); } diff --git a/apps/dsp-app/src/app/workspace/resource/representation/audio/audio.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/audio/audio.component.ts index ee367a2c87..7ffc82ea9c 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/audio/audio.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/audio/audio.component.ts @@ -54,8 +54,12 @@ export class AudioComponent implements OnInit, AfterViewInit { ngOnInit(): void { this._rs.getFileInfo(this.src.fileValue.fileUrl).subscribe( - res => (this.originalFilename = res['originalFilename']), - () => (this.failedToLoad = true) + res => { + this.originalFilename = res['originalFilename']; + }, + () => { + this.failedToLoad = true; + } ); this.audio = this._sanitizer.bypassSecurityTrustUrl(this.src.fileValue.fileUrl); } @@ -85,20 +89,20 @@ export class AudioComponent implements OnInit, AfterViewInit { } parseTime(time) { - if (isNaN(time)) { + if (Number.isNaN(time)) { return '00:00'; } const minutes = Math.floor(time / 60); const seconds = Math.floor(time - minutes * 60); let minutesString = minutes.toString(); if (minutes < 10) { - minutesString = '0' + minutesString; + minutesString = `0${minutesString}`; } let secondsString = seconds.toString(); if (seconds < 10) { - secondsString = '0' + secondsString; + secondsString = `0${secondsString}`; } - return minutesString + ':' + secondsString; + return `${minutesString}:${secondsString}`; } openReplaceFileDialog() { @@ -183,9 +187,9 @@ export class AudioComponent implements OnInit, AfterViewInit { this.audio = this._sanitizer.bypassSecurityTrustUrl(this.src.fileValue.fileUrl); - this._rs - .getFileInfo(this.src.fileValue.fileUrl) - .subscribe(res => (this.originalFilename = res['originalFilename'])); + this._rs.getFileInfo(this.src.fileValue.fileUrl).subscribe(res => { + this.originalFilename = res['originalFilename']; + }); this._valueOperationEventService.emit( new EmitEvent( diff --git a/apps/dsp-app/src/app/workspace/resource/representation/av-timeline/av-timeline.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/av-timeline/av-timeline.component.ts index 13151a5ba1..a8cdbe28d7 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/av-timeline/av-timeline.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/av-timeline/av-timeline.component.ts @@ -96,11 +96,9 @@ export class AvTimelineComponent implements OnChanges { if (!this.timelineDimension) { // calculate timeline dimension if it doesn't exist this.timelineDimension = this._getTimelineDimensions(); - } else { + } else if (changes.resized) { // recalculate timeline dimension because resized parameter has changed - if (changes.resized) { - this.timelineDimension = this._getResizedTimelineDimensions(); - } + this.timelineDimension = this._getResizedTimelineDimensions(); } // emit the dimension to the parent @@ -136,12 +134,12 @@ export class AvTimelineComponent implements OnChanges { if (!this.dragging) { // update thumb position if not dragging - this.thumbEle.nativeElement.style.transform = 'translateX(' + pos + 'px) scale(.7)'; + this.thumbEle.nativeElement.style.transform = `translateX(${pos}px) scale(.7)`; } // adjust progress width / fill already played time - this.progressEle.nativeElement.children[0].style.transform = 'translateX(0px) scale3d(' + bgPos + ', 1, 1)'; + this.progressEle.nativeElement.children[0].style.transform = `translateX(0px) scale3d(${bgPos}, 1, 1)`; // adjust progress width / progress background - this.progressEle.nativeElement.children[2].style.transform = 'translateX(0px) scale3d(' + fillPos + ', 1, 1)'; + this.progressEle.nativeElement.children[2].style.transform = `translateX(0px) scale3d(${fillPos}, 1, 1)`; } /** diff --git a/apps/dsp-app/src/app/workspace/resource/representation/document/document.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/document/document.component.ts index dfbc94e2a2..45cea76bc4 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/document/document.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/document/document.component.ts @@ -66,10 +66,13 @@ export class DocumentComponent implements OnInit, AfterViewInit { this.fileType = this._getFileType(this.src.fileValue.filename); this._rs.getFileInfo(this.src.fileValue.fileUrl).subscribe( - res => (this.originalFilename = res['originalFilename']), - () => + res => { + this.originalFilename = res['originalFilename']; + }, + () => { // error already handled by getFileInfo - (this.failedToLoad = true) + this.failedToLoad = true; + } ); } @@ -200,9 +203,9 @@ export class DocumentComponent implements OnInit, AfterViewInit { this.elem = document.getElementsByClassName('pdf-viewer')[0]; } - this._rs - .getFileInfo(this.src.fileValue.fileUrl) - .subscribe(res => (this.originalFilename = res['originalFilename'])); + this._rs.getFileInfo(this.src.fileValue.fileUrl).subscribe(res => { + this.originalFilename = res['originalFilename']; + }); this.zoomFactor = 1.0; this.pdfQuery = ''; diff --git a/apps/dsp-app/src/app/workspace/resource/representation/replace-file-form/replace-file-form.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/replace-file-form/replace-file-form.component.ts index 331154b60d..b206b73f51 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/replace-file-form/replace-file-form.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/replace-file-form/replace-file-form.component.ts @@ -63,7 +63,7 @@ export class ReplaceFileFormComponent implements OnInit { const capitalized = repType[0].toUpperCase() + repType.substring(1).toLowerCase(); - this.warningMessages.push(capitalized + ' will be replaced.'); - this.warningMessages.push('Please note that you are about to replace the ' + repType + '.'); + this.warningMessages.push(`${capitalized} will be replaced.`); + this.warningMessages.push(`Please note that you are about to replace the ${repType}.`); } } diff --git a/apps/dsp-app/src/app/workspace/resource/representation/representation.service.ts b/apps/dsp-app/src/app/workspace/resource/representation/representation.service.ts index 3124594fe9..da2671bd1a 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/representation.service.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/representation.service.ts @@ -41,9 +41,9 @@ export class RepresentationService { if (imageFilename) { const index = url.indexOf(imageFilename); - pathToJson = url.substring(0, index + imageFilename.length) + '/knora.json'; + pathToJson = `${url.substring(0, index + imageFilename.length)}/knora.json`; } else { - pathToJson = url.substring(0, url.lastIndexOf('/')) + '/knora.json'; + pathToJson = `${url.substring(0, url.lastIndexOf('/'))}/knora.json`; } return this._http.get(pathToJson, requestOptions).pipe( diff --git a/apps/dsp-app/src/app/workspace/resource/representation/still-image/still-image.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/still-image/still-image.component.ts index ba4136788f..fed6a4bfab 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/still-image/still-image.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/still-image/still-image.component.ts @@ -320,11 +320,11 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit // collect all geometries belonging to this page const geometries: GeometryForRegion[] = []; - image.annotations.map(reg => { + image.annotations.forEach(reg => { this._regions[reg.regionResource.id] = []; const geoms = reg.getGeometries(); - geoms.map(geom => { + geoms.forEach(geom => { const geomForReg = new GeometryForRegion(geom.geometry, reg.regionResource); geometries.push(geomForReg); @@ -512,18 +512,7 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit const x2 = Math.max(Math.min(endPoint.x, imageSize.x), 0) / imageSize.x; const y1 = Math.max(Math.min(startPoint.y, imageSize.y), 0) / imageSize.y; const y2 = Math.max(Math.min(endPoint.y, imageSize.y), 0) / imageSize.y; - const geomStr = - '{"status":"active","lineColor":"' + - color + - '","lineWidth":2,"points":[{"x":' + - x1.toString() + - ',"y":' + - y1.toString() + - '},{"x":' + - x2.toString() + - ',"y":' + - y2.toString() + - '}],"type":"rectangle"}'; + const geomStr = `{"status":"active","lineColor":"${color}","lineWidth":2,"points":[{"x":${x1.toString()},"y":${y1.toString()}},{"x":${x2.toString()},"y":${y2.toString()}}],"type":"rectangle"}`; const createResource = new CreateResource(); createResource.label = label; createResource.type = Constants.Region; @@ -561,6 +550,7 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit * set up function for the region drawer */ private _addRegionDrawer() { + // eslint-disable-next-line no-new new OpenSeadragon.MouseTracker({ element: this._viewer.canvas, pressHandler: event => { @@ -572,7 +562,7 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit const viewportPos = this._viewer.viewport.pointFromPixel((event as OpenSeadragon.ViewerEvent).position); this._viewer.addOverlay(overlayElement, new OpenSeadragon.Rect(viewportPos.x, viewportPos.y, 0, 0)); this._regionDragInfo = { - overlayElement: overlayElement, + overlayElement, startPos: viewportPos, }; }, @@ -727,7 +717,7 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit // let i = 0; for (const image of images) { - const sipiBasePath = image.iiifBaseUrl + '/' + image.filename; + const sipiBasePath = `${image.iiifBaseUrl}/${image.filename}`; const width = image.dimX; const height = image.dimY; // construct OpenSeadragon tileSources according to https://openseadragon.github.io/docs/OpenSeadragon.Viewer.html#open @@ -737,8 +727,8 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit // eslint-disable-next-line @typescript-eslint/naming-convention '@context': 'http://iiif.io/api/image/3/context.json', id: sipiBasePath, - height: height, - width: width, + height, + width, profile: ['level2'], protocol: 'http://iiif.io/api/image', tiles: [ @@ -780,9 +770,9 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit const lineWidth = geometry.lineWidth; const regEle: HTMLElement = this._renderer.createElement('div'); - regEle.id = 'region-overlay-' + Math.random() * 10000; + regEle.id = `region-overlay-${Math.random() * 10000}`; regEle.className = 'region'; - regEle.setAttribute('style', 'outline: solid ' + lineColor + ' ' + lineWidth + 'px;'); + regEle.setAttribute('style', `outline: solid ${lineColor} ${lineWidth}px;`); const diffX = geometry.points[1].x - geometry.points[0].x; const diffY = geometry.points[1].y - geometry.points[0].y; @@ -794,7 +784,7 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit Math.abs(diffY * aspectRatio) ); - loc.y = loc.y * aspectRatio; + loc.y *= aspectRatio; this._viewer.addOverlay({ element: regEle, @@ -809,7 +799,7 @@ export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit regEle.append(comEle); regEle.addEventListener('mousemove', (event: MouseEvent) => { - comEle.setAttribute('style', 'display: block; left: ' + event.clientX + 'px; top: ' + event.clientY + 'px'); + comEle.setAttribute('style', `display: block; left: ${event.clientX}px; top: ${event.clientY}px`); }); regEle.addEventListener('mouseleave', () => { comEle.setAttribute('style', 'display: none'); diff --git a/apps/dsp-app/src/app/workspace/resource/representation/text/text.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/text/text.component.ts index 4ddbb2048a..e0099bf99f 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/text/text.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/text/text.component.ts @@ -51,8 +51,12 @@ export class TextComponent implements OnInit, AfterViewInit { ngOnInit(): void { this._rs.getFileInfo(this.src.fileValue.fileUrl).subscribe( - res => (this.originalFilename = res['originalFilename']), - () => (this.failedToLoad = true) + res => { + this.originalFilename = res['originalFilename']; + }, + () => { + this.failedToLoad = true; + } ); } @@ -111,9 +115,9 @@ export class TextComponent implements OnInit, AfterViewInit { this.src.fileValue.filename = (res2.properties[Constants.HasTextFileValue][0] as ReadTextFileValue).filename; this.src.fileValue.strval = (res2.properties[Constants.HasTextFileValue][0] as ReadTextFileValue).strval; - this._rs - .getFileInfo(this.src.fileValue.fileUrl) - .subscribe(res => (this.originalFilename = res['originalFilename'])); + this._rs.getFileInfo(this.src.fileValue.fileUrl).subscribe(res => { + this.originalFilename = res['originalFilename']; + }); this._valueOperationEventService.emit( new EmitEvent( diff --git a/apps/dsp-app/src/app/workspace/resource/representation/video/video-preview/video-preview.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/video/video-preview/video-preview.component.ts index 1da35409c2..2ec54f2b90 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/video/video-preview/video-preview.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/video/video-preview/video-preview.component.ts @@ -106,7 +106,7 @@ export class VideoPreviewComponent implements OnChanges { x = i * this.matrixFrameWidth; y = j * this.matrixFrameHeight; - cssParams = '-' + x + 'px -' + y + 'px'; + cssParams = `-${x}px -${y}px`; this.frame.nativeElement.style['background-position'] = cssParams; i++; @@ -172,10 +172,10 @@ export class VideoPreviewComponent implements OnChanges { this.frameHeight = Math.round(this.matrixFrameHeight / this.proportion); // set the size of the matrix file - this.frame.nativeElement.style['background-image'] = 'url(' + this.matrix + ')'; - this.frame.nativeElement.style['background-size'] = Math.round(this.matrixWidth / this.proportion) + 'px auto'; - this.frame.nativeElement.style['width'] = this.frameWidth + 'px'; - this.frame.nativeElement.style['height'] = this.frameHeight + 'px'; + this.frame.nativeElement.style['background-image'] = `url(${this.matrix})`; + this.frame.nativeElement.style['background-size'] = `${Math.round(this.matrixWidth / this.proportion)}px auto`; + this.frame.nativeElement.style['width'] = `${this.frameWidth}px`; + this.frame.nativeElement.style['height'] = `${this.frameHeight}px`; this.loaded.emit(true); }, () => { @@ -240,9 +240,9 @@ export class VideoPreviewComponent implements OnChanges { // calculate current line and column number in the matrix and get current frame / preview image position const curLineNr: number = Math.floor(curFrameNr / 6); const curColNr: number = Math.floor(curFrameNr - curLineNr * 6); - const cssParams: string = '-' + curColNr * this.frameWidth + 'px -' + curLineNr * this.frameHeight + 'px'; + const cssParams: string = `-${curColNr * this.frameWidth}px -${curLineNr * this.frameHeight}px`; - this.frame.nativeElement.style['background-image'] = 'url(' + this.matrix + ')'; + this.frame.nativeElement.style['background-image'] = `url(${this.matrix})`; this.frame.nativeElement.style['background-position'] = cssParams; } } @@ -262,8 +262,7 @@ export class VideoPreviewComponent implements OnChanges { // => 5AiQkeJNbQn-ClrXWkJVFvB const fileName = basePath.substring(basePath.lastIndexOf('/') + 1); - const matrixUrl = basePath + '/' + fileName + '_m_' + fileNumber + '.jpg/file'; - + const matrixUrl = `${basePath}/${fileName}_m_${fileNumber}.jpg/file`; // if the new matrix url is different than the current one, the current one will be replaced if (this.matrix !== matrixUrl) { this.matrix = matrixUrl; diff --git a/apps/dsp-app/src/app/workspace/resource/representation/video/video.component.ts b/apps/dsp-app/src/app/workspace/resource/representation/video/video.component.ts index a47cc88026..a71695f3e1 100644 --- a/apps/dsp-app/src/app/workspace/resource/representation/video/video.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/representation/video/video.component.ts @@ -294,7 +294,7 @@ export class VideoComponent implements OnChanges, AfterViewInit { } // set preview positon on x axis - this.preview.nativeElement.style.left = leftPosition + 'px'; + this.preview.nativeElement.style.left = `${leftPosition}px`; } /** diff --git a/apps/dsp-app/src/app/workspace/resource/resource-instance-form/resource-instance-form.component.ts b/apps/dsp-app/src/app/workspace/resource/resource-instance-form/resource-instance-form.component.ts index 2a31a4f085..0f3636bfb8 100644 --- a/apps/dsp-app/src/app/workspace/resource/resource-instance-form/resource-instance-form.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/resource-instance-form/resource-instance-form.component.ts @@ -132,8 +132,7 @@ export class ResourceInstanceFormComponent implements OnInit, OnChanges { // set label from resource class const defaultClassLabel = this.defaultClasses.find(i => i.iri === this.resourceClass.subClassOf[0]); - this.resourceLabel = - this.resourceClass.label + (defaultClassLabel ? ' (' + defaultClassLabel.label + ')' : ''); + this.resourceLabel = this.resourceClass.label + (defaultClassLabel ? ` (${defaultClassLabel.label})` : ''); // filter out all props that cannot be edited or are link props but also the hasFileValue props this.properties = onto.getPropertyDefinitionsByType(ResourcePropertyDefinition).filter( diff --git a/apps/dsp-app/src/app/workspace/resource/resource-instance-form/select-properties/select-properties.component.ts b/apps/dsp-app/src/app/workspace/resource/resource-instance-form/select-properties/select-properties.component.ts index 06f93bf54c..0794b99ee5 100644 --- a/apps/dsp-app/src/app/workspace/resource/resource-instance-form/select-properties/select-properties.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/resource-instance-form/select-properties/select-properties.component.ts @@ -59,12 +59,12 @@ export class SelectPropertiesComponent implements OnInit { // each property will also have a filtered array to be used when deleting a value. // see the deleteValue method below for more info - this.propertyValuesKeyValuePair[prop.id + '-filtered'] = [0]; + this.propertyValuesKeyValuePair[`${prop.id}-filtered`] = [0]; // each property will also have a cardinality array to be used when marking a field as required // see the isPropRequired method below for more info this.isPropRequired(prop.id); - this.propertyValuesKeyValuePair[prop.id + '-cardinality'] = [this.isRequiredProp ? 1 : 0]; + this.propertyValuesKeyValuePair[`${prop.id}-cardinality`] = [this.isRequiredProp ? 1 : 0]; } } } @@ -94,6 +94,8 @@ export class SelectPropertiesComponent implements OnInit { */ isPropRequired(propId: string): boolean { if (this.selectedResourceClass !== undefined && propId) { + // TODO FOLLOWING LINE IS A BUG ARRAY-CALLBACK-RETURN SHOULDNT BE DISABLED + // eslint-disable-next-line array-callback-return this.selectedResourceClass.propertiesList.filter((card: IHasProperty) => { if (card.propertyIndex === propId) { // cardinality 1 or 1-N @@ -124,7 +126,7 @@ export class SelectPropertiesComponent implements OnInit { // add a new element to the corresponding filtered property values array as well. // if this array contains more than one element, the delete button with be shown - this.propertyValuesKeyValuePair[prop.id + '-filtered'].push(length); + this.propertyValuesKeyValuePair[`${prop.id}-filtered`].push(length); } deleteValue(prop: ResourcePropertyDefinition, index: number, ev: Event) { @@ -137,7 +139,7 @@ export class SelectPropertiesComponent implements OnInit { // update the filtered version of the corresponding property values array. // used in the template to calculate if the delete button should be shown. // i.e. don't show the delete button if there is only one value - this.propertyValuesKeyValuePair[prop.id + '-filtered'] = this._filterValueArray( + this.propertyValuesKeyValuePair[`${prop.id}-filtered`] = this._filterValueArray( this.propertyValuesKeyValuePair[prop.id] ); } diff --git a/apps/dsp-app/src/app/workspace/resource/resource-instance-form/select-properties/switch-properties/switch-properties.component.ts b/apps/dsp-app/src/app/workspace/resource/resource-instance-form/select-properties/switch-properties/switch-properties.component.ts index 95df32f222..337eea2836 100644 --- a/apps/dsp-app/src/app/workspace/resource/resource-instance-form/select-properties/switch-properties/switch-properties.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/resource-instance-form/select-properties/switch-properties/switch-properties.component.ts @@ -2,6 +2,7 @@ import { Component, Input, OnInit, ViewChild } from '@angular/core'; import { UntypedFormGroup } from '@angular/forms'; import { Constants, ReadResource, ResourcePropertyDefinition } from '@dasch-swiss/dsp-js'; import { BaseValueDirective } from '@dsp-app/src/app/main/directive/base-value.directive'; + @Component({ selector: 'app-switch-properties', templateUrl: './switch-properties.component.html', @@ -33,7 +34,7 @@ export class SwitchPropertiesComponent implements OnInit { // a conversion from a number to a boolean is required by the input valueRequiredValidator this.isRequiredProp = !!+this.isRequiredProp; - if (this.property.guiElement === Constants.SalsahGui + Constants.HashDelimiter + 'Textarea') { + if (this.property.guiElement === `${Constants.SalsahGui + Constants.HashDelimiter}Textarea`) { this.textArea = true; } } diff --git a/apps/dsp-app/src/app/workspace/resource/resource-link-form/resource-link-form.component.ts b/apps/dsp-app/src/app/workspace/resource/resource-link-form/resource-link-form.component.ts index 86c27387b1..2285553d6e 100644 --- a/apps/dsp-app/src/app/workspace/resource/resource-link-form/resource-link-form.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/resource-link-form/resource-link-form.component.ts @@ -116,13 +116,13 @@ export class ResourceLinkFormComponent implements OnInit, OnDestroy { const form = this.form; - Object.keys(this.formErrors).map(field => { + Object.keys(this.formErrors).forEach(field => { this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map(key => { - this.formErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach(key => { + this.formErrors[field] += `${messages[key]} `; }); } }); @@ -168,7 +168,7 @@ export class ResourceLinkFormComponent implements OnInit, OnDestroy { this._dspApiConnection.v2.res.createResource(linkObj).subscribe( (res: ReadResource) => { const path = this._resourceService.getResourcePath(res.id); - const goto = '/resource' + path; + const goto = `/resource${path}`; this._router.navigate([]).then(() => window.open(goto, '_blank')); this.closeDialog.emit(); }, diff --git a/apps/dsp-app/src/app/workspace/resource/resource.component.ts b/apps/dsp-app/src/app/workspace/resource/resource.component.ts index ed6ebe3d99..70b49ca000 100644 --- a/apps/dsp-app/src/app/workspace/resource/resource.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/resource.component.ts @@ -262,11 +262,9 @@ export class ResourceComponent implements OnChanges, OnDestroy { } getResource(iri: string): Observable { - return this._dspApiConnection.v2.res.getResource(iri).pipe( - map((response: ReadResource) => { - return new DspResource(response); - }) - ); + return this._dspApiConnection.v2.res + .getResource(iri) + .pipe(map((response: ReadResource) => new DspResource(response))); } renderResource(resource: DspResource) { @@ -457,6 +455,8 @@ export class ResourceComponent implements OnChanges, OnDestroy { .sort((a, b) => (a.guiDef.guiOrder > b.guiDef.guiOrder ? 1 : -1)) // to get equal results on all browser engines which implements sorting in different way // properties list has to be sorted again, pushing all "has..." properties to the bottom + // TODO FOLLOWING LINE IS A BUG ARRAY-CALLBACK-RETURN SHOULDNT BE DISABLED + // eslint-disable-next-line array-callback-return .sort(a => { if (a.guiDef.guiOrder === undefined) { return 1; diff --git a/apps/dsp-app/src/app/workspace/resource/services/geoname.service.ts b/apps/dsp-app/src/app/workspace/resource/services/geoname.service.ts index 573f9c2f74..71eb460c04 100644 --- a/apps/dsp-app/src/app/workspace/resource/services/geoname.service.ts +++ b/apps/dsp-app/src/app/workspace/resource/services/geoname.service.ts @@ -58,11 +58,7 @@ export class GeonameService { resolveGeonameID(id: string): Observable { return this._http .get( - 'https://ws.geonames.net/getJSON?geonameId=' + - id + - '&username=' + - this._appConfigService.dspAppConfig.geonameToken + - '&style=short' + `https://ws.geonames.net/getJSON?geonameId=${id}&username=${this._appConfigService.dspAppConfig.geonameToken}&style=short` ) .pipe( map( @@ -82,8 +78,9 @@ export class GeonameService { } return { - displayName: - geo.name + (geo.adminName1 !== undefined ? ', ' + geo.adminName1 : '') + ', ' + geo.countryName, + displayName: `${geo.name + (geo.adminName1 !== undefined ? `, ${geo.adminName1}` : '')}, ${ + geo.countryName + }`, name: geo.name, administrativeName: geo.adminName1, country: geo.countryName, @@ -114,22 +111,20 @@ export class GeonameService { }&lang=en&style=full&maxRows=12&name_startsWith=${encodeURIComponent(searchString)}`; return this._http.get(url).pipe( - map(response => { - return response.geonames + map(response => + response.geonames .filter(geo => geo.geonameId && geo.name && geo.countryName && geo.fclName) // only map those with required properties to avoid duplicates - .map(geo => { - return { - id: geo.geonameId.toString(), - displayName: `${geo.name}${geo.adminName1 ? ', ' + geo.adminName1 : ''}${ - geo.countryName ? ', ' + geo.countryName : '' - }`, - name: geo.name, - administrativeName: geo.adminName1, - country: geo.countryName, - locationType: geo.fclName, - }; - }); - }), + .map(geo => ({ + id: geo.geonameId.toString(), + displayName: `${geo.name}${geo.adminName1 ? `, ${geo.adminName1}` : ''}${ + geo.countryName ? `, ${geo.countryName}` : '' + }`, + name: geo.name, + administrativeName: geo.adminName1, + country: geo.countryName, + locationType: geo.fclName, + })) + ), catchError(error => throwError(error)) ); } diff --git a/apps/dsp-app/src/app/workspace/resource/services/resource.service.ts b/apps/dsp-app/src/app/workspace/resource/services/resource.service.ts index 1fa050e75d..087ab607fc 100644 --- a/apps/dsp-app/src/app/workspace/resource/services/resource.service.ts +++ b/apps/dsp-app/src/app/workspace/resource/services/resource.service.ts @@ -36,7 +36,7 @@ export class ResourceService { * @returns resource iri --> http://rdfh.ch/082B/SQkTPdHdTzq_gqbwj6QR-A */ getResourceIri(shortcode: string, uuid: string): string { - return this.iriBase + '/' + shortcode + '/' + uuid; + return `${this.iriBase}/${shortcode}/${uuid}`; } /** diff --git a/apps/dsp-app/src/app/workspace/resource/services/value.service.ts b/apps/dsp-app/src/app/workspace/resource/services/value.service.ts index 10ac8fa6b2..a48f331cda 100644 --- a/apps/dsp-app/src/app/workspace/resource/services/value.service.ts +++ b/apps/dsp-app/src/app/workspace/resource/services/value.service.ts @@ -157,7 +157,7 @@ export class ValueService { const calDate = new IslamicCalendarDate(new CalendarPeriod(date, date)); return calDate.daysInMonth(date); } else { - throw Error('Unknown calendar ' + calendar); + throw Error(`Unknown calendar ${calendar}`); } } diff --git a/apps/dsp-app/src/app/workspace/resource/values/color-value/color-value.component.ts b/apps/dsp-app/src/app/workspace/resource/values/color-value/color-value.component.ts index 5b7d308a74..3c329fe035 100644 --- a/apps/dsp-app/src/app/workspace/resource/values/color-value/color-value.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/values/color-value/color-value.component.ts @@ -95,9 +95,7 @@ export class ColorValueComponent extends BaseValueDirective implements OnInit, O // convert hexadicemal color value into rgb color value const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; - hex = hex.replace(shorthandRegex, function (m, r, g, b) { - return r + r + g + g + b + b; - }); + hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b); const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); const rgb: { r: number; g: number; b: number } = result @@ -109,9 +107,9 @@ export class ColorValueComponent extends BaseValueDirective implements OnInit, O : null; // calculate luminance - const a = [rgb.r, rgb.g, rgb.b].map(function (v) { + const a = [rgb.r, rgb.g, rgb.b].map(v => { v /= 255; - return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); + return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; }); const luminance = a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722; diff --git a/apps/dsp-app/src/app/workspace/resource/values/geoname-value/geoname-value.component.ts b/apps/dsp-app/src/app/workspace/resource/values/geoname-value/geoname-value.component.ts index 3536a1e89b..fb40ef6965 100644 --- a/apps/dsp-app/src/app/workspace/resource/values/geoname-value/geoname-value.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/values/geoname-value/geoname-value.component.ts @@ -88,8 +88,12 @@ export class GeonameValueComponent extends BaseValueDirective implements OnInit, if (typeof searchTerm === 'string' && searchTerm.length >= 3) { // console.log('searching for ' + searchTerm); this._geonameService.searchPlace(searchTerm).subscribe( - places => (this.places = places), - () => (this.places = []) + places => { + this.places = places; + }, + () => { + this.places = []; + } ); } else { this.places = []; diff --git a/apps/dsp-app/src/app/workspace/resource/values/link-value/link-value.component.ts b/apps/dsp-app/src/app/workspace/resource/values/link-value/link-value.component.ts index 5d07c325e8..07c4eff05d 100644 --- a/apps/dsp-app/src/app/workspace/resource/values/link-value/link-value.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/values/link-value/link-value.component.ts @@ -245,7 +245,7 @@ export class LinkValueComponent extends BaseValueDirective implements OnInit, On top: '112px', }, data: { - mode: mode, + mode, title: resClass.label, id: iri, parentResource: this.parentResource, diff --git a/apps/dsp-app/src/app/workspace/resource/values/time-value/time-input/time-input.component.ts b/apps/dsp-app/src/app/workspace/resource/values/time-value/time-input/time-input.component.ts index 6331ef9b3f..3f5ef85771 100644 --- a/apps/dsp-app/src/app/workspace/resource/values/time-value/time-input/time-input.component.ts +++ b/apps/dsp-app/src/app/workspace/resource/values/time-value/time-input/time-input.component.ts @@ -289,7 +289,7 @@ export class TimeInputComponent Number(splitTime[1]) ); - return updateDate.toISOString().split('.')[0] + 'Z'; + return `${updateDate.toISOString().split('.')[0]}Z`; } // converts and returns a unix timestamp string as an array consisting of a GregorianCalendarDate and a string diff --git a/apps/dsp-app/src/app/workspace/results/list-view/list-view.component.ts b/apps/dsp-app/src/app/workspace/results/list-view/list-view.component.ts index 51b6bbbe76..89635627aa 100644 --- a/apps/dsp-app/src/app/workspace/results/list-view/list-view.component.ts +++ b/apps/dsp-app/src/app/workspace/results/list-view/list-view.component.ts @@ -328,7 +328,7 @@ export class ListViewComponent implements OnChanges, OnInit, OnDestroy { // build the gravsearch query let gravsearch = this.search.query; gravsearch = gravsearch.substring(0, gravsearch.search('OFFSET')); - gravsearch = gravsearch + 'OFFSET ' + index; + gravsearch = `${gravsearch}OFFSET ${index}`; this._dspApiConnection.v2.search .doExtendedSearch(gravsearch) diff --git a/apps/dsp-app/src/app/workspace/results/list-view/list-view.service.ts b/apps/dsp-app/src/app/workspace/results/list-view/list-view.service.ts index d1332510f1..4f70a40568 100644 --- a/apps/dsp-app/src/app/workspace/results/list-view/list-view.service.ts +++ b/apps/dsp-app/src/app/workspace/results/list-view/list-view.service.ts @@ -64,10 +64,9 @@ export class ListViewService { }; } else { // else condition when single resource is clicked for viewing - // unselect checkboxes if any if (resChecks) { - resChecks.forEach(function (ckb) { + resChecks.forEach(ckb => { if (ckb.checked) { ckb.checked = false; } diff --git a/apps/dsp-app/src/app/workspace/results/list-view/resource-list/resource-list.component.ts b/apps/dsp-app/src/app/workspace/results/list-view/resource-list/resource-list.component.ts index 46be8baaab..6a14e4ff05 100644 --- a/apps/dsp-app/src/app/workspace/results/list-view/resource-list/resource-list.component.ts +++ b/apps/dsp-app/src/app/workspace/results/list-view/resource-list/resource-list.component.ts @@ -67,7 +67,7 @@ export class ResourceListComponent implements OnInit { openResource(linkValue: ReadLinkValue | string) { const iri = typeof linkValue == 'string' ? linkValue : linkValue.linkedResourceIri; const path = this._resourceService.getResourcePath(iri); - window.open('/resource' + path, '_blank'); + window.open(`/resource${path}`, '_blank'); } selectResource(status: CheckboxUpdate) { diff --git a/apps/dsp-app/src/app/workspace/results/results.component.ts b/apps/dsp-app/src/app/workspace/results/results.component.ts index 4ae8fca2b6..95cfc5dec4 100644 --- a/apps/dsp-app/src/app/workspace/results/results.component.ts +++ b/apps/dsp-app/src/app/workspace/results/results.component.ts @@ -47,12 +47,10 @@ export class ResultsComponent implements AfterViewChecked { const params$ = this._route.paramMap; const combinedParams$ = combineLatest([parentParams$, params$]).pipe( - map(([parentParams, params]) => { - return { - parentParams: parentParams, - params: params, - }; - }) + map(([parentParams, params]) => ({ + parentParams, + params, + })) ); combinedParams$.subscribe(data => { @@ -62,7 +60,7 @@ export class ResultsComponent implements AfterViewChecked { this._handleParentParams(parentParams); this._handleSearchParams(params); - this._titleService.setTitle('Search results for ' + this.searchParams.mode + ' search'); + this._titleService.setTitle(`Search results for ${this.searchParams.mode} search`); }); } @@ -76,10 +74,8 @@ export class ResultsComponent implements AfterViewChecked { if (!res || res.count <= 1) { this.viewMode = 'single'; - } else { - if (this.viewMode !== 'compare') { - this.viewMode = res && res.count > 0 ? 'intermediate' : 'single'; - } + } else if (this.viewMode !== 'compare') { + this.viewMode = res && res.count > 0 ? 'intermediate' : 'single'; } } diff --git a/apps/dsp-app/src/app/workspace/search/advanced-search/advanced-search-container.component.ts b/apps/dsp-app/src/app/workspace/search/advanced-search/advanced-search-container.component.ts index c352345f65..e90d041483 100644 --- a/apps/dsp-app/src/app/workspace/search/advanced-search/advanced-search-container.component.ts +++ b/apps/dsp-app/src/app/workspace/search/advanced-search/advanced-search-container.component.ts @@ -43,20 +43,18 @@ export class AdvancedSearchContainerComponent implements OnInit { logProperties(propFormList: PropertyFormItem[]): void { // strip any irrelevant data from the PropertyFormList for logging const logObject = propFormList.map(propertyForm => { - let valueObject: object | undefined = undefined; + let valueObject: object | undefined; if (Array.isArray(propertyForm.searchValue)) { - valueObject = propertyForm.searchValue.map(v => { - return { - property: v.selectedProperty, - operator: v.selectedOperator, - value: v.searchValue, - }; - }); + valueObject = propertyForm.searchValue.map(v => ({ + property: v.selectedProperty, + operator: v.selectedOperator, + value: v.searchValue, + })); } return { property: propertyForm.selectedProperty, operator: propertyForm.selectedOperator, - value: valueObject ? valueObject : propertyForm.searchValue, + value: valueObject || propertyForm.searchValue, }; }); diff --git a/apps/dsp-app/src/app/workspace/search/search-panel/search-panel.component.ts b/apps/dsp-app/src/app/workspace/search/search-panel/search-panel.component.ts index fd83a30353..ec9b4673a9 100644 --- a/apps/dsp-app/src/app/workspace/search/search-panel/search-panel.component.ts +++ b/apps/dsp-app/src/app/workspace/search/search-panel/search-panel.component.ts @@ -75,7 +75,7 @@ export class SearchPanelComponent { const uuid = params.get('uuid'); const navigationExtras = { - state: { uuid: uuid }, + state: { uuid }, }; this._router.navigate(['advanced-search'], navigationExtras); diff --git a/libs/jdnconvertiblecalendar/src/lib/CalendarDate.ts b/libs/jdnconvertiblecalendar/src/lib/CalendarDate.ts index f5180c9091..565a917dc9 100644 --- a/libs/jdnconvertiblecalendar/src/lib/CalendarDate.ts +++ b/libs/jdnconvertiblecalendar/src/lib/CalendarDate.ts @@ -34,10 +34,10 @@ export class CalendarDate { ) { // check validity of daytime if (daytime !== undefined && daytime >= 1) - throw new JDNConvertibleCalendarError('Invalid daytime: ' + daytime + ', valid range: 0 - 0.9…'); + throw new JDNConvertibleCalendarError(`Invalid daytime: ${daytime}, valid range: 0 - 0.9…`); // TODO: When other calendar than Gregorian or Julian are implemented, this may have to be changed if (dayOfWeek !== undefined && (!Utils.isInteger(dayOfWeek) || dayOfWeek < 0 || dayOfWeek > 6)) - throw new JDNConvertibleCalendarError('Invalid day of week: ' + dayOfWeek); + throw new JDNConvertibleCalendarError(`Invalid day of week: ${dayOfWeek}`); } } diff --git a/libs/jdnconvertiblecalendar/src/lib/JDNCalendarConversion.ts b/libs/jdnconvertiblecalendar/src/lib/JDNCalendarConversion.ts index 7c8701db06..86520574d5 100644 --- a/libs/jdnconvertiblecalendar/src/lib/JDNCalendarConversion.ts +++ b/libs/jdnconvertiblecalendar/src/lib/JDNCalendarConversion.ts @@ -6,6 +6,7 @@ import { CalendarDate } from './CalendarDate'; import { TypeDefinitionsModule } from './TypeDefinitions'; +// eslint-disable-next-line @typescript-eslint/no-namespace export namespace JDNConvertibleConversionModule { /** * Removes the fraction from a given number (). @@ -17,9 +18,7 @@ export namespace JDNConvertibleConversionModule { * @param num the number whose fraction is to be removed. * @returns given number without fractions. */ - const truncateDecimals = (num: number): number => { - return Math[num < 0 ? 'ceil' : 'floor'](num); - }; + const truncateDecimals = (num: number): number => Math[num < 0 ? 'ceil' : 'floor'](num); /** * Converts a Gregorian calendar date to a JDC. @@ -38,7 +37,7 @@ export namespace JDNConvertibleConversionModule { let day = calendarDate.day; if (calendarDate.daytime !== undefined) { - day = day + calendarDate.daytime; + day += calendarDate.daytime; } if (calendarDate.month > 2) { @@ -95,7 +94,7 @@ export namespace JDNConvertibleConversionModule { * @returns the Gregorian calendar date created from the given JDC. */ export const JDCToGregorian = (jdc: TypeDefinitionsModule.JDC): CalendarDate => { - jdc = jdc + 0.5; + jdc += 0.5; const z = truncateDecimals(jdc); const f = jdc - z; @@ -132,9 +131,7 @@ export namespace JDNConvertibleConversionModule { * @param jdn the given JDN. * @returns the Gregorian calendar date created from the given JDN. */ - export const JDNToGregorian = (jdn: TypeDefinitionsModule.JDN): CalendarDate => { - return JDCToGregorian(jdn); - }; + export const JDNToGregorian = (jdn: TypeDefinitionsModule.JDN): CalendarDate => JDCToGregorian(jdn); /** * Converts a Julian calendar date to a JDC. @@ -155,7 +152,7 @@ export namespace JDNConvertibleConversionModule { let day = calendarDate.day; if (calendarDate.daytime !== undefined) { - day = day + calendarDate.daytime; + day += calendarDate.daytime; } if (calendarDate.month > 2) { @@ -209,7 +206,7 @@ export namespace JDNConvertibleConversionModule { * @returns Julian calendar date created from given JDC. */ export const JDCToJulian = (jdc: TypeDefinitionsModule.JDC): CalendarDate => { - jdc = jdc + 0.5; + jdc += 0.5; const z = truncateDecimals(jdc); const f = jdc - z; const a = z; // it's a julian calendar @@ -243,9 +240,7 @@ export namespace JDNConvertibleConversionModule { * @param jdn JDN to be converted to a Julian calendar date. * @returns Julian calendar date created from given JDN. */ - export const JDNToJulian = (jdn: TypeDefinitionsModule.JDN): CalendarDate => { - return JDCToJulian(jdn); - }; + export const JDNToJulian = (jdn: TypeDefinitionsModule.JDN): CalendarDate => JDCToJulian(jdn); /** * Determine the day of week from the given JDN. Works only for calendars which use @@ -257,9 +252,7 @@ export namespace JDNConvertibleConversionModule { * @param jdc given JDC. * @returns the number of the day of the week for the given JDC (0 Sunday, 1 Monday, 2 Tuesday, 3 Wednesday, 4 Thursday, 5 Friday, 6 Saturday). */ - export const dayOfWeekFromJDC = (jdc: TypeDefinitionsModule.JDC) => { - return truncateDecimals(jdc + 1.5) % 7; - }; + export const dayOfWeekFromJDC = (jdc: TypeDefinitionsModule.JDC) => truncateDecimals(jdc + 1.5) % 7; /** * Converts an Islamic calendar date to a JDC. @@ -290,21 +283,21 @@ export namespace JDNConvertibleConversionModule { let d = calendarDate.day; if (calendarDate.daytime !== undefined) { - d = d + calendarDate.daytime; + d += calendarDate.daytime; } const n = d + Math.floor(29.5001 * (m - 1) + 0.99); const q = Math.floor(h / 30); let r = h % 30; if (r < 0) { - r = r + 30; + r += 30; } const a = Math.floor((11 * r + 3) / 30); const w = 404 * q + 354 * r + 208 + a; const q1 = Math.floor(w / 1461); let q2 = w % 1461; if (q2 < 0) { - q2 = q2 + 1461; + q2 += 1461; } const g = 621 + 4 * Math.floor(7 * q + q1); const k = Math.floor(q2 / 365.2422); @@ -313,11 +306,11 @@ export namespace JDNConvertibleConversionModule { let x = g + k; if (j > 366 && x % 4 == 0) { - j = j - 366; - x = x + 1; + j -= 366; + x += 1; } else if (j > 365 && x % 4 > 0) { - j = j - 365; - x = x + 1; + j -= 365; + x += 1; } const jdc = truncateDecimals(365.25 * (x - 1)) + 1721423 + j - 0.5; @@ -384,19 +377,19 @@ export namespace JDNConvertibleConversionModule { let c2 = Math.floor(c1); if (c1 - c2 > 0.5) { - c2 = c2 + 1; + c2 += 1; } const d_ = 1461 * b + 170 + c2; const q = Math.floor(d_ / 10631); let r = d_ % 10631; if (r < 0) { - r = r + 10631; + r += 10631; } const j = Math.floor(r / 354); let k = r % 354; if (k < 0) { - k = k + 354; + k += 354; } const o = Math.floor((11 * j + 14) / 30); let h = 30 * q + j + 1; @@ -405,25 +398,25 @@ export namespace JDNConvertibleConversionModule { if (jj > 354) { let cl = h % 30; if (cl < 0) { - cl = cl + 30; + cl += 30; } let dl = (11 * cl + 3) % 30; if (dl < 0) { - dl = dl + 30; + dl += 30; } if (dl < 19) { - jj = jj - 354; - h = h + 1; + jj -= 354; + h += 1; } if (dl > 18) { - jj = jj - 355; - h = h + 1; + jj -= 355; + h += 1; } if (jj == 0) { jj = 355; - h = h - 1; + h -= 1; } } @@ -447,7 +440,5 @@ export namespace JDNConvertibleConversionModule { * @param jdn JDN to be converted to an Islamic calendar date. * @returns @returns Islamic calendar date created from given JDN. */ - export const JDNToIslamic = (jdn: TypeDefinitionsModule.JDN): CalendarDate => { - return JDCToIslamic(jdn); - }; + export const JDNToIslamic = (jdn: TypeDefinitionsModule.JDN): CalendarDate => JDCToIslamic(jdn); } diff --git a/libs/jdnconvertiblecalendar/src/lib/JDNCalendarNames.ts b/libs/jdnconvertiblecalendar/src/lib/JDNCalendarNames.ts index 733731c0cb..08377cff7a 100644 --- a/libs/jdnconvertiblecalendar/src/lib/JDNCalendarNames.ts +++ b/libs/jdnconvertiblecalendar/src/lib/JDNCalendarNames.ts @@ -46,6 +46,7 @@ interface Calendars { [calendar: string]: Names; } +// eslint-disable-next-line @typescript-eslint/no-namespace export namespace JDNConvertibleCalendarNames { const defaultLocale = 'en'; diff --git a/libs/jdnconvertiblecalendar/src/lib/JDNConvertibleCalendar.ts b/libs/jdnconvertiblecalendar/src/lib/JDNConvertibleCalendar.ts index f29091f65d..b71f631129 100644 --- a/libs/jdnconvertiblecalendar/src/lib/JDNConvertibleCalendar.ts +++ b/libs/jdnconvertiblecalendar/src/lib/JDNConvertibleCalendar.ts @@ -253,7 +253,7 @@ export abstract class JDNConvertibleCalendar { */ public convertCalendar(toCalendarType: 'Gregorian' | 'Julian' | 'Islamic'): JDNConvertibleCalendar { if (JDNConvertibleCalendar.supportedCalendars.indexOf(toCalendarType) == -1) { - throw new JDNConvertibleCalendarError('Target calendar not supported: ' + toCalendarType); + throw new JDNConvertibleCalendarError(`Target calendar not supported: ${toCalendarType}`); } if (this.calendarName == toCalendarType) return this; // no conversion needed @@ -263,12 +263,15 @@ export abstract class JDNConvertibleCalendar { // call constructor of subclass representing the target calendar switch (toCalendarType) { case JDNConvertibleCalendar.gregorian: + // eslint-disable-next-line @typescript-eslint/no-use-before-define return new GregorianCalendarDate(jdnPeriod); case JDNConvertibleCalendar.julian: + // eslint-disable-next-line @typescript-eslint/no-use-before-define return new JulianCalendarDate(jdnPeriod); case JDNConvertibleCalendar.islamic: + // eslint-disable-next-line @typescript-eslint/no-use-before-define return new IslamicCalendarDate(jdnPeriod); } } @@ -281,7 +284,7 @@ export abstract class JDNConvertibleCalendar { public transposePeriodByDay(days: number): void { if (days === 0) return; - if (!Utils.isInteger(days)) throw new JDNConvertibleCalendarError(`parameter "days" is expected to be an integer`); + if (!Utils.isInteger(days)) throw new JDNConvertibleCalendarError('parameter "days" is expected to be an integer'); const currentPeriod = this.toJDNPeriod(); @@ -301,8 +304,9 @@ export abstract class JDNConvertibleCalendar { public transposePeriodByYear(years: number): void { if (years === 0) return; - if (!Utils.isInteger(years)) - throw new JDNConvertibleCalendarError(`parameter "years" is expected to be an integer`); + if (!Utils.isInteger(years)) { + throw new JDNConvertibleCalendarError('parameter "years" is expected to be an integer'); + } const currentCalendarPeriod = this.toCalendarPeriod(); @@ -444,8 +448,9 @@ export abstract class JDNConvertibleCalendar { protected handleMonthTransposition(calendarDate: CalendarDate, months: number): CalendarDate { if (months === 0) return calendarDate; - if (!Utils.isInteger(months)) - throw new JDNConvertibleCalendarError(`parameter "months" is expected to be an integer`); + if (!Utils.isInteger(months)) { + throw new JDNConvertibleCalendarError('parameter "months" is expected to be an integer'); + } // indicates if the shifting is towards the future or the past const intoTheFuture: boolean = months > 0; @@ -492,40 +497,38 @@ export abstract class JDNConvertibleCalendar { calendarDate.day > maxDaysInNewMonth ? maxDaysInNewMonth : calendarDate.day ); } - } else { + } else if (calendarDate.month - monthsToShift < 1) { // switch to the previous year if the number of months does not fit - if (calendarDate.month - monthsToShift < 1) { - // months to be subtracted from the previous year - const newMonth = this.monthsInYear - (monthsToShift - calendarDate.month); + // months to be subtracted from the previous year + const newMonth = this.monthsInYear - (monthsToShift - calendarDate.month); - // when switching from a positive to a negative year and the year zero does not exist in the calendar used, correct it. - let yearZeroCorrection = 0; - if (!this.yearZeroExists && calendarDate.year > -1 && calendarDate.year - yearsToShift - 1 < 1) { - yearZeroCorrection = -1; - } + // when switching from a positive to a negative year and the year zero does not exist in the calendar used, correct it. + let yearZeroCorrection = 0; + if (!this.yearZeroExists && calendarDate.year > -1 && calendarDate.year - yearsToShift - 1 < 1) { + yearZeroCorrection = -1; + } - // determine max. number of days in the new month - const maxDaysInNewMonth = this.daysInMonth( - new CalendarDate(calendarDate.year - yearsToShift - 1 + yearZeroCorrection, newMonth, 1) - ); + // determine max. number of days in the new month + const maxDaysInNewMonth = this.daysInMonth( + new CalendarDate(calendarDate.year - yearsToShift - 1 + yearZeroCorrection, newMonth, 1) + ); - newCalendarDate = new CalendarDate( - calendarDate.year - yearsToShift - 1 + yearZeroCorrection, // subtract an extra year - newMonth, - calendarDate.day > maxDaysInNewMonth ? maxDaysInNewMonth : calendarDate.day - ); - } else { - // determine max. number of days in the new month - const maxDaysInNewMonth = this.daysInMonth( - new CalendarDate(calendarDate.year - yearsToShift, calendarDate.month - monthsToShift, 1) - ); + newCalendarDate = new CalendarDate( + calendarDate.year - yearsToShift - 1 + yearZeroCorrection, // subtract an extra year + newMonth, + calendarDate.day > maxDaysInNewMonth ? maxDaysInNewMonth : calendarDate.day + ); + } else { + // determine max. number of days in the new month + const maxDaysInNewMonth = this.daysInMonth( + new CalendarDate(calendarDate.year - yearsToShift, calendarDate.month - monthsToShift, 1) + ); - newCalendarDate = new CalendarDate( - calendarDate.year - yearsToShift, - calendarDate.month - monthsToShift, - calendarDate.day > maxDaysInNewMonth ? maxDaysInNewMonth : calendarDate.day - ); - } + newCalendarDate = new CalendarDate( + calendarDate.year - yearsToShift, + calendarDate.month - monthsToShift, + calendarDate.day > maxDaysInNewMonth ? maxDaysInNewMonth : calendarDate.day + ); } return newCalendarDate; @@ -542,8 +545,9 @@ export abstract class JDNConvertibleCalendar { public transposePeriodByMonth(months: number): void { if (months === 0) return; - if (!Utils.isInteger(months)) - throw new JDNConvertibleCalendarError(`parameter "months" is expected to be an integer`); + if (!Utils.isInteger(months)) { + throw new JDNConvertibleCalendarError('parameter "months" is expected to be an integer'); + } const currentCalendarPeriod = this.toCalendarPeriod(); diff --git a/libs/jdnconvertiblecalendar/src/lib/TypeDefinitions.ts b/libs/jdnconvertiblecalendar/src/lib/TypeDefinitions.ts index ae82b31f95..09859292ad 100644 --- a/libs/jdnconvertiblecalendar/src/lib/TypeDefinitions.ts +++ b/libs/jdnconvertiblecalendar/src/lib/TypeDefinitions.ts @@ -3,6 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ +// eslint-disable-next-line @typescript-eslint/no-namespace export namespace TypeDefinitionsModule { /** * Type alias for a Julian Day Number (JDN). diff --git a/libs/jdnconvertiblecalendar/src/lib/Utils.ts b/libs/jdnconvertiblecalendar/src/lib/Utils.ts index fc6419aee0..9b2db4bb86 100644 --- a/libs/jdnconvertiblecalendar/src/lib/Utils.ts +++ b/libs/jdnconvertiblecalendar/src/lib/Utils.ts @@ -3,6 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ +// eslint-disable-next-line @typescript-eslint/no-namespace export namespace Utils { /** * Checks if a given number is an integer. @@ -10,8 +11,7 @@ export namespace Utils { * @param num number to check for. * @returns true if the given number is an integer, returns false otherwise. */ - export const isInteger = (num: number): boolean => { + export const isInteger = (num: number): boolean => // https://stackoverflow.com/questions/3885817/how-do-i-check-that-a-number-is-float-or-integer - return num % 1 === 0; - }; + num % 1 === 0; } diff --git a/libs/jdnconvertiblecalendardateadapter/src/lib/jdnconvertible-calendar-date-adapter.spec.ts b/libs/jdnconvertiblecalendardateadapter/src/lib/jdnconvertible-calendar-date-adapter.spec.ts index 41e5458e25..a21f23827f 100644 --- a/libs/jdnconvertiblecalendardateadapter/src/lib/jdnconvertible-calendar-date-adapter.spec.ts +++ b/libs/jdnconvertiblecalendardateadapter/src/lib/jdnconvertible-calendar-date-adapter.spec.ts @@ -37,7 +37,7 @@ describe('JDNConvertibleCalendarDateAdapter', () => { assertValidDate = (d: JDNConvertibleCalendar | null, valid: boolean) => { expect(adapter.isDateInstance(d)).withContext(`Expected ${d} to be a date instance`).not.toBeNull(); - expect(adapter.isValid(d!)) + expect(adapter.isValid()) .withContext(`Expected ${d} to be ${valid ? 'valid' : 'invalid'},` + ` but was ${valid ? 'invalid' : 'valid'}`) .toBe(valid); }; diff --git a/libs/jdnconvertiblecalendardateadapter/src/lib/jdnconvertible-calendar-date-adapter.ts b/libs/jdnconvertiblecalendardateadapter/src/lib/jdnconvertible-calendar-date-adapter.ts index 02e1671e2c..2eb4e751e7 100644 --- a/libs/jdnconvertiblecalendardateadapter/src/lib/jdnconvertible-calendar-date-adapter.ts +++ b/libs/jdnconvertiblecalendardateadapter/src/lib/jdnconvertible-calendar-date-adapter.ts @@ -62,7 +62,7 @@ export class JDNConvertibleCalendarDateAdapter extends DateAdapter { if (JDNConvertibleCalendar.supportedCalendars.indexOf(activeCal) === -1) { - throw Error('Invalid value for token ACTIVE_CALENDAR: ' + activeCal); + throw Error(`Invalid value for token ACTIVE_CALENDAR: ${activeCal}`); } this.activeCalendar = activeCal; @@ -403,7 +403,7 @@ export class JDNConvertibleCalendarDateAdapter extends DateAdapter => { - return this._ontologyV2Api.getMetadata().pipe( - map(response => - response['@graph'] - .filter(onto => onto['knora-api:attachedToProject'] !== Constants.SystemProjectIRI) - .map(onto => { - return { iri: onto['@id'], label: onto['rdfs:label'] }; - }) - ) - ); - }; + allOntologiesList = (): Observable => + this._ontologyV2Api + .getMetadata() + .pipe( + map(response => + response['@graph'] + .filter(onto => onto['knora-api:attachedToProject'] !== Constants.SystemProjectIRI) + .map(onto => ({ iri: onto['@id'], label: onto['rdfs:label'] })) + ) + ); // API call to get the list of ontologies within the specified project iri - ontologiesInProjectList = (projectIri: string): Observable => { - return this._dspApiConnection.v2.onto.getOntologiesByProjectIri(projectIri).pipe( + ontologiesInProjectList = (projectIri: string): Observable => + this._dspApiConnection.v2.onto.getOntologiesByProjectIri(projectIri).pipe( map((response: OntologiesMetadata | ApiResponseError) => { if (response instanceof ApiResponseError) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal throw response; // caught by catchError operator } - return response.ontologies.map((onto: { id: string; label: string }) => { - return { iri: onto.id, label: onto.label }; - }); + return response.ontologies.map((onto: { id: string; label: string }) => ({ iri: onto.id, label: onto.label })); }), catchError(err => { this._handleError(err); return []; // return an empty array on error }) ); - }; // API call to get the list of resource classes - resourceClassesList = (ontologyIri: string, restrictToClass?: string): Observable => { - return this._dspApiConnection.v2.onto.getOntology(ontologyIri).pipe( + resourceClassesList = (ontologyIri: string, restrictToClass?: string): Observable => + this._dspApiConnection.v2.onto.getOntology(ontologyIri).pipe( map((response: ApiResponseError | ReadOntology) => { if (response instanceof ApiResponseError) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal throw response; // caught by catchError operator } @@ -125,7 +123,7 @@ export class AdvancedSearchService { .map((resClassDef: ResourceClassDefinition) => { // label can be undefined const label = resClassDef.label || ''; - return { iri: resClassDef.id, label: label }; + return { iri: resClassDef.id, label }; }); }), catchError(err => { @@ -133,11 +131,10 @@ export class AdvancedSearchService { return []; // return an empty array on error }) ); - }; // API call to get the list of properties - propertiesList = (ontologyIri: string): Observable => { - return this._dspApiConnection.v2.ontologyCache.getOntology(ontologyIri).pipe( + propertiesList = (ontologyIri: string): Observable => + this._dspApiConnection.v2.ontologyCache.getOntology(ontologyIri).pipe( map((onto: Map) => { const ontology = onto.get(ontologyIri); @@ -169,8 +166,8 @@ export class AdvancedSearchService { const listNodeIri = guiAttr[0].substring(7, guiAttr[0].length - 1); return { iri: propDef.id, - label: label, - objectType: objectType, + label, + objectType, isLinkedResourceProperty: linkProperty, listIri: listNodeIri, }; @@ -181,8 +178,8 @@ export class AdvancedSearchService { return { iri: propDef.id, - label: label, - objectType: objectType, + label, + objectType, isLinkedResourceProperty: linkProperty, }; }); @@ -192,11 +189,10 @@ export class AdvancedSearchService { return []; // return an empty array on error }) ); - }; // API call to get the list of properties filtered by resource class - filteredPropertiesList = (resourceClassIri: string): Observable => { - return this._dspApiConnection.v2.ontologyCache.getResourceClassDefinition(resourceClassIri).pipe( + filteredPropertiesList = (resourceClassIri: string): Observable => + this._dspApiConnection.v2.ontologyCache.getResourceClassDefinition(resourceClassIri).pipe( map((onto: ResourceClassAndPropertyDefinitions) => { // filter out properties that shouldn't be able to be selected // this is a bit different than how the propertiesList method does it @@ -225,8 +221,8 @@ export class AdvancedSearchService { const listNodeIri = guiAttr[0].substring(7, guiAttr[0].length - 1); return { iri: propDef.id, - label: label, - objectType: objectType, + label, + objectType, isLinkedResourceProperty: linkProperty, listIri: listNodeIri, }; @@ -237,8 +233,8 @@ export class AdvancedSearchService { return { iri: propDef.id, - label: label, - objectType: objectType, + label, + objectType, isLinkedResourceProperty: linkProperty, }; }); @@ -248,7 +244,6 @@ export class AdvancedSearchService { return []; // return an empty array on error }) ); - }; getResourcesListCount(searchValue: string, resourceClassIri: string): Observable { // Cancel the previous count request @@ -264,6 +259,7 @@ export class AdvancedSearchService { takeUntil(this.cancelPreviousCountRequest$), // Cancel previous request switchMap((response: CountQueryResponse | ApiResponseError) => { if (response instanceof ApiResponseError) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal throw response; // caught by catchError operator } return of(response.numberOfResults); @@ -289,6 +285,7 @@ export class AdvancedSearchService { takeUntil(this.cancelPreviousSearchRequest$), // Cancel previous request switchMap((response: ReadResourceSequence | ApiResponseError) => { if (response instanceof ApiResponseError) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal throw response; // caught by catchError operator } return of( @@ -309,6 +306,7 @@ export class AdvancedSearchService { return this._dspApiConnection.v2.list.getList(rootNodeIri).pipe( map((response: ListNodeV2 | ApiResponseError) => { if (response instanceof ApiResponseError) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal throw response; // caught by catchError operator } return response; diff --git a/libs/vre/advanced-search/src/lib/data-access/advanced-search-store/advanced-search-store.service.ts b/libs/vre/advanced-search/src/lib/data-access/advanced-search-store/advanced-search-store.service.ts index e21bab700f..290ea1c446 100644 --- a/libs/vre/advanced-search/src/lib/data-access/advanced-search-store/advanced-search-store.service.ts +++ b/libs/vre/advanced-search/src/lib/data-access/advanced-search-store/advanced-search-store.service.ts @@ -197,9 +197,7 @@ export class AdvancedSearchStoreService extends ComponentStore { - return this.isPropertyFormItemListInvalid(childProp); - }); + return prop.searchValue.some(childProp => this.isPropertyFormItemListInvalid(childProp)); } // selected operator is NOT 'exists' or 'does not exist' AND diff --git a/libs/vre/advanced-search/src/lib/data-access/gravsearch-service/gravsearch.service.ts b/libs/vre/advanced-search/src/lib/data-access/gravsearch-service/gravsearch.service.ts index 46b53f6763..03df53f3ef 100644 --- a/libs/vre/advanced-search/src/lib/data-access/gravsearch-service/gravsearch.service.ts +++ b/libs/vre/advanced-search/src/lib/data-access/gravsearch-service/gravsearch.service.ts @@ -2,6 +2,7 @@ import { Injectable } from '@angular/core'; import { Constants } from '@dasch-swiss/dsp-js'; import { GravsearchPropertyString, ResourceLabel } from '../advanced-search-service/advanced-search.service'; import { PropertyFormItem, OrderByItem, Operators } from '../advanced-search-store/advanced-search-store.service'; + @Injectable({ providedIn: 'root', }) @@ -71,7 +72,7 @@ export class GravsearchService { property.selectedProperty?.objectType.includes(Constants.KnoraApiV2) && property.selectedProperty?.objectType !== ResourceLabel ) { - constructString = '?mainRes <' + property.selectedProperty?.iri + '> ?prop' + index + ' .'; + constructString = `?mainRes <${property.selectedProperty?.iri}> ?prop${index} .`; whereString = constructString; } @@ -81,7 +82,7 @@ export class GravsearchService { property.selectedProperty?.objectType !== ResourceLabel ) { if (property.selectedOperator !== Operators.NotEquals) { - constructString = '?mainRes <' + property.selectedProperty?.iri + '> ?prop' + index + ' .'; + constructString = `?mainRes <${property.selectedProperty?.iri}> ?prop${index} .`; whereString = constructString; } // if search value is an array that means that it's a linked resource with child properties @@ -123,14 +124,14 @@ export class GravsearchService { } if (!(property.selectedOperator === Operators.Exists || property.selectedOperator === Operators.NotExists)) { - whereString += '\n' + this._valueStringHelper(property, index, '?prop', '?mainRes'); + whereString += `\n${this._valueStringHelper(property, index, '?prop', '?mainRes')}`; } else if (property.selectedOperator === Operators.NotExists) { - whereString = 'FILTER NOT EXISTS { \n' + whereString + '\n}\n'; + whereString = `FILTER NOT EXISTS { \n${whereString}\n}\n`; } return { - constructString: constructString, - whereString: whereString, + constructString, + whereString, }; } @@ -168,7 +169,7 @@ export class GravsearchService { if (Array.isArray(property.searchValue)) { property.searchValue.forEach((value, i) => { if (value.selectedOperator !== Operators.Exists && value.selectedOperator !== Operators.NotExists) { - valueString += this._valueStringHelper(value, i, '?linkProp' + index, '?prop' + index); + valueString += this._valueStringHelper(value, i, `?linkProp${index}`, `?prop${index}`); } }); } diff --git a/libs/vre/advanced-search/src/lib/feature/advanced-search/advanced-search.component.ts b/libs/vre/advanced-search/src/lib/feature/advanced-search/advanced-search.component.ts index 14c262b349..c77dc258c4 100644 --- a/libs/vre/advanced-search/src/lib/feature/advanced-search/advanced-search.component.ts +++ b/libs/vre/advanced-search/src/lib/feature/advanced-search/advanced-search.component.ts @@ -90,7 +90,7 @@ export class AdvancedSearchComponent implements OnInit { ontologiesLoading: false, resourceClasses: [], resourceClassesLoading: false, - selectedProject: this.uuid ? 'http://rdfh.ch/projects/' + this.uuid : undefined, + selectedProject: this.uuid ? `http://rdfh.ch/projects/${this.uuid}` : undefined, selectedOntology: undefined, selectedResourceClass: undefined, propertyFormList: [], diff --git a/libs/vre/advanced-search/src/lib/ui/property-form/property-form-link-match-property/property-form-link-match-property.component.ts b/libs/vre/advanced-search/src/lib/ui/property-form/property-form-link-match-property/property-form-link-match-property.component.ts index 2329f0f472..45690093fc 100644 --- a/libs/vre/advanced-search/src/lib/ui/property-form/property-form-link-match-property/property-form-link-match-property.component.ts +++ b/libs/vre/advanced-search/src/lib/ui/property-form/property-form-link-match-property/property-form-link-match-property.component.ts @@ -138,8 +138,8 @@ export class PropertyFormLinkMatchPropertyComponent implements AfterViewInit { const objectType = this.values[index].selectedProperty?.objectType; if (objectType) { this.emitResourceSearchValueChanged.emit({ - value: value, - objectType: objectType, + value, + objectType, }); } } @@ -150,8 +150,8 @@ export class PropertyFormLinkMatchPropertyComponent implements AfterViewInit { const objectType = this.values[index].selectedProperty?.objectType; if (objectType) { this.emitLoadMoreSearchResults.emit({ - value: value, - objectType: objectType, + value, + objectType, }); } } diff --git a/libs/vre/advanced-search/src/lib/ui/property-form/property-form-link-value/property-form-link-value.component.ts b/libs/vre/advanced-search/src/lib/ui/property-form/property-form-link-value/property-form-link-value.component.ts index 519670c910..5c09feff69 100644 --- a/libs/vre/advanced-search/src/lib/ui/property-form/property-form-link-value/property-form-link-value.component.ts +++ b/libs/vre/advanced-search/src/lib/ui/property-form/property-form-link-value/property-form-link-value.component.ts @@ -7,6 +7,7 @@ import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { ApiData } from '../../../data-access/advanced-search-service/advanced-search.service'; import { PropertyFormItem } from '../../../data-access/advanced-search-store/advanced-search-store.service'; import { MatAutocompleteOptionsScrollDirective } from '../../directives/mat-autocomplete-options-scroll.directive'; + @Component({ selector: 'dasch-swiss-property-form-link-value', standalone: true, diff --git a/libs/vre/advanced-search/src/lib/ui/property-form/property-form-value/property-form-value.component.ts b/libs/vre/advanced-search/src/lib/ui/property-form/property-form-value/property-form-value.component.ts index 2bd998126e..a8977b1a18 100644 --- a/libs/vre/advanced-search/src/lib/ui/property-form/property-form-value/property-form-value.component.ts +++ b/libs/vre/advanced-search/src/lib/ui/property-form/property-form-value/property-form-value.component.ts @@ -11,6 +11,25 @@ import { AppDatePickerComponent } from '@dasch-swiss/vre/shared/app-date-picker' import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { ResourceLabel } from '../../../data-access/advanced-search-service/advanced-search.service'; import { PropertyFormItem } from '../../../data-access/advanced-search-store/advanced-search-store.service'; + +class CustomRegex { + public static readonly INT_REGEX = /^-?\d+$/; + + public static readonly DECIMAL_REGEX = /^[-+]?[0-9]*\.?[0-9]*$/; + + public static readonly URI_REGEX = + /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,63}(:[0-9]{1,5})?(\/.*)?$/; +} + +class ValueErrorStateMatcher implements ErrorStateMatcher { + isErrorState(control: FormControl | null): boolean { + if (!control) { + return false; + } + return control && control.invalid && (control.dirty || control.touched); + } +} + @Component({ selector: 'dasch-swiss-property-form-value', standalone: true, @@ -74,7 +93,7 @@ export class PropertyFormValueComponent implements OnInit, AfterViewInit { const [datePart, eraPart] = dateAndEra.split(' '); const [year, month, day] = datePart.split('-').map(part => parseInt(part)); - era = eraPart ? eraPart : 'CE'; + era = eraPart || 'CE'; if (day) { return new KnoraDate(calendar, era, year, month, day); @@ -112,21 +131,3 @@ export class PropertyFormValueComponent implements OnInit, AfterViewInit { else this.emitValueChanged.emit(undefined); } } - -class ValueErrorStateMatcher implements ErrorStateMatcher { - isErrorState(control: FormControl | null): boolean { - if (!control) { - return false; - } - return control && control.invalid && (control.dirty || control.touched); - } -} - -class CustomRegex { - public static readonly INT_REGEX = /^-?\d+$/; - - public static readonly DECIMAL_REGEX = /^[-+]?[0-9]*\.?[0-9]*$/; - - public static readonly URI_REGEX = - /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,63}(:[0-9]{1,5})?(\/.*)?$/; -} diff --git a/libs/vre/advanced-search/src/lib/ui/property-form/property-form.component.ts b/libs/vre/advanced-search/src/lib/ui/property-form/property-form.component.ts index f55008addc..5c46136c96 100644 --- a/libs/vre/advanced-search/src/lib/ui/property-form/property-form.component.ts +++ b/libs/vre/advanced-search/src/lib/ui/property-form/property-form.component.ts @@ -206,28 +206,28 @@ export class PropertyFormComponent implements AfterViewInit { onRemoveChildPropertyFormClicked(childProperty: PropertyFormItem) { this.emitRemoveChildPropertyForm.emit({ parentProperty: this.propertyFormItem, - childProperty: childProperty, + childProperty, }); } onChildSelectedPropertyChanged(childProperty: PropertyFormItem): void { this.emitChildSelectedPropertyChanged.emit({ parentProperty: this.propertyFormItem, - childProperty: childProperty, + childProperty, }); } onChildSelectedOperatorChanged(childProperty: PropertyFormItem): void { this.emitChildSelectedOperatorChanged.emit({ parentProperty: this.propertyFormItem, - childProperty: childProperty, + childProperty, }); } onChildValueChanged(childProperty: PropertyFormItem): void { this.emitChildValueChanged.emit({ parentProperty: this.propertyFormItem, - childProperty: childProperty, + childProperty, }); } diff --git a/libs/vre/shared/app-analytics/src/lib/pendo-analytics/pendo-analytics.service.ts b/libs/vre/shared/app-analytics/src/lib/pendo-analytics/pendo-analytics.service.ts index 0f3259eff6..02a7ee9491 100644 --- a/libs/vre/shared/app-analytics/src/lib/pendo-analytics/pendo-analytics.service.ts +++ b/libs/vre/shared/app-analytics/src/lib/pendo-analytics/pendo-analytics.service.ts @@ -30,7 +30,7 @@ export class PendoAnalyticsService { // @ts-ignore pendo.initialize({ visitor: { - id: id, // Required if user is logged in, default creates anonymous ID + id, // Required if user is logged in, default creates anonymous ID environment: this.environment, // email: // Recommended if using Pendo Feedback, or NPS Email // full_name: // Recommended if using Pendo Feedback @@ -41,7 +41,7 @@ export class PendoAnalyticsService { }, account: { - id: id, // Required if using Pendo Feedback, default uses the value 'ACCOUNT-UNIQUE-ID' + id, // Required if using Pendo Feedback, default uses the value 'ACCOUNT-UNIQUE-ID' environment: this.environment, // name: // Optional // is_paying: // Recommended if using Pendo Feedback diff --git a/libs/vre/shared/app-config/src/lib/app-config/app-config.ts b/libs/vre/shared/app-config/src/lib/app-config/app-config.ts index 12f6520459..d50acdc1e2 100644 --- a/libs/vre/shared/app-config/src/lib/app-config/app-config.ts +++ b/libs/vre/shared/app-config/src/lib/app-config/app-config.ts @@ -23,6 +23,7 @@ export const Datadog = z.discriminatedUnion('enabled', [ service: z.string().optional(), }), ]); +// eslint-disable-next-line @typescript-eslint/no-redeclare export type Datadog = z.infer; /** @@ -36,6 +37,7 @@ export const Rollbar = z.discriminatedUnion('enabled', [ }), z.object({ enabled: z.literal(false), accessToken: z.string().optional() }), ]); +// eslint-disable-next-line @typescript-eslint/no-redeclare export type Rollbar = z.infer; export const Instrumentation = z.object({ @@ -97,4 +99,5 @@ export const AppConfig = z.object({ /** * Definition of the AppConfig type, which can be inferred from the schema. */ +// eslint-disable-next-line @typescript-eslint/no-redeclare export type AppConfig = z.infer; diff --git a/libs/vre/shared/app-config/src/lib/app-config/dsp-api-tokens.ts b/libs/vre/shared/app-config/src/lib/app-config/dsp-api-tokens.ts index ca2a93a77d..fc07dea22e 100644 --- a/libs/vre/shared/app-config/src/lib/app-config/dsp-api-tokens.ts +++ b/libs/vre/shared/app-config/src/lib/app-config/dsp-api-tokens.ts @@ -29,7 +29,5 @@ export const DspInstrumentationToken = new InjectionToken(entityDefs: { [index: string]: T }): T[] => { const entityIndexes = Object.keys(entityDefs); - return entityIndexes.map((entityIndex: string) => { - return entityDefs[entityIndex]; - }); + return entityIndexes.map((entityIndex: string) => entityDefs[entityIndex]); }; diff --git a/libs/vre/shared/app-config/src/lib/app-config/dsp-iiif-config.ts b/libs/vre/shared/app-config/src/lib/app-config/dsp-iiif-config.ts index 11e3f4529c..eed8d0163c 100644 --- a/libs/vre/shared/app-config/src/lib/app-config/dsp-iiif-config.ts +++ b/libs/vre/shared/app-config/src/lib/app-config/dsp-iiif-config.ts @@ -32,8 +32,8 @@ export class DspIiifConfig { * the full IIIF URL */ get iiifUrl(): string { - return ( - this.iiifProtocol + '://' + this.iiifHost + (this.iiifPort !== null ? ':' + this.iiifPort : '') + this.iiifPath - ); + return `${this.iiifProtocol}://${this.iiifHost}${this.iiifPort !== null ? `:${this.iiifPort}` : ''}${ + this.iiifPath + }`; } } diff --git a/libs/vre/shared/app-date-picker/src/lib/app-date-picker/app-date-picker.component.ts b/libs/vre/shared/app-date-picker/src/lib/app-date-picker/app-date-picker.component.ts index 28c40cf2ac..0945ba1ba4 100644 --- a/libs/vre/shared/app-date-picker/src/lib/app-date-picker/app-date-picker.component.ts +++ b/libs/vre/shared/app-date-picker/src/lib/app-date-picker/app-date-picker.component.ts @@ -391,7 +391,7 @@ export class AppDatePickerComponent leftPadding(value: number | undefined): string { if (value !== undefined) { - return ('0' + value).slice(-2); + return `0${value}`.slice(-2); } else { return ''; } @@ -403,10 +403,10 @@ export class AppDatePickerComponent switch (options) { case 'era': // displays date with era; era only in case of BCE - return value + (date.era === 'noEra' ? '' : date.era === 'BCE' || date.era === 'AD' ? ' ' + date.era : ''); + return value + (date.era === 'noEra' ? '' : date.era === 'BCE' || date.era === 'AD' ? ` ${date.era}` : ''); case 'calendar': // displays date without era but with calendar type - return value + ' ' + this.titleCase(date.calendar); + return `${value} ${this.titleCase(date.calendar)}`; case 'calendarOnly': // displays only the selected calendar type without any data return this.titleCase(date.calendar); @@ -414,15 +414,12 @@ export class AppDatePickerComponent // GREGORIAN:2023-8-2 // CE is default era so no need to add it era = date.era === 'BCE' ? ' BCE' : ''; - return date.calendar + ':' + value + era; + return `${date.calendar}:${value}${era}`; case 'all': // displays date with era (only as BCE) and selected calendar type - return ( - value + - (date.era === 'noEra' ? '' : date.era === 'BCE' ? ' ' + date.era : '') + - ' ' + - this.titleCase(date.calendar) - ); + return `${value + (date.era === 'noEra' ? '' : date.era === 'BCE' ? ` ${date.era}` : '')} ${this.titleCase( + date.calendar + )}`; default: return ''; } @@ -516,13 +513,13 @@ export class AppDatePickerComponent const form = this.form; - Object.keys(this.formErrors).map((field: string) => { + Object.keys(this.formErrors).forEach((field: string) => { this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid && control.errors !== null) { const messages = this.validationMessages[field]; - Object.keys(control.errors).map((key: string) => { - this.formErrors[field] += messages[key] + ' '; + Object.keys(control.errors).forEach((key: string) => { + this.formErrors[field] += `${messages[key]} `; }); } }); @@ -539,7 +536,7 @@ export class AppDatePickerComponent this.era, this.form.controls['year'].value, this.form.controls['month'].value ? this.form.controls['month'].value : undefined, - day ? day : undefined + day || undefined ); this.value = this.date; @@ -587,7 +584,7 @@ export class AppDatePickerComponent // found solution and formula here: // https://sciencing.com/convert-julian-date-calender-date-6017669.html julianDate = new Date(); - difference = parseInt((julianDate.getFullYear() + '').substring(0, 2), 10) * 0.75 - 1.25; + difference = parseInt(`${julianDate.getFullYear()}`.substring(0, 2), 10) * 0.75 - 1.25; julianDate.setDate(julianDate.getDate() - Math.floor(difference)); day = julianDate.getDate(); month = julianDate.getMonth() + 1; @@ -662,7 +659,7 @@ export class AppDatePickerComponent const calDate = new IslamicCalendarDate(new CalendarPeriod(date, date)); return calDate.daysInMonth(date); } else { - throw Error('Unknown calendar ' + calendar); + throw Error(`Unknown calendar ${calendar}`); } } diff --git a/libs/vre/shared/app-helper-services/src/lib/ontology.service.ts b/libs/vre/shared/app-helper-services/src/lib/ontology.service.ts index 5840e9e917..a11653ce9a 100644 --- a/libs/vre/shared/app-helper-services/src/lib/ontology.service.ts +++ b/libs/vre/shared/app-helper-services/src/lib/ontology.service.ts @@ -33,18 +33,14 @@ export class OntologyService { if (label && type) { // build name from label // normalize and replace spaces and special chars - return ( - type + - '-' + - label - .normalize('NFD') - .replace(/[\u0300-\u036f]/g, '') - .replace(/[\u00a0-\u024f]/g, '') - .replace(/[\])}[{(]/g, '') - .replace(/\s+/g, '-') - .replace(/\//g, '-') - .toLowerCase() - ); + return `${type}-${label + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/[\u00a0-\u024f]/g, '') + .replace(/[\])}[{(]/g, '') + .replace(/\s+/g, '-') + .replace(/\//g, '-') + .toLowerCase()}`; } else { // build randomized name // the name starts with the three first character of ontology iri to avoid a start with a number followed by randomized string @@ -142,7 +138,7 @@ export class OntologyService { } } - return superPropIri ? superPropIri : undefined; + return superPropIri || undefined; } /** @@ -160,24 +156,22 @@ export class OntologyService { propType = group.elements.find( (i: DefaultProperty) => i.guiEle === property.guiElement && i.subPropOf === subProp ); + } else if (property.objectType === Constants.IntValue && subProp === Constants.SeqNum) { + // if the property is of type number, but sub property of SeqNum, + // select the correct default prop params + propType = group.elements.find( + (i: DefaultProperty) => i.objectType === property.objectType && i.subPropOf === Constants.SeqNum + ); + } else if (property.objectType === Constants.TextValue) { + // if the property is of type text value, we have to check the gui element + // to get the correct default prop params + propType = group.elements.find( + (i: DefaultProperty) => i.guiEle === property.guiElement && i.objectType === property.objectType + ); } else { - if (property.objectType === Constants.IntValue && subProp === Constants.SeqNum) { - // if the property is of type number, but sub property of SeqNum, - // select the correct default prop params - propType = group.elements.find( - (i: DefaultProperty) => i.objectType === property.objectType && i.subPropOf === Constants.SeqNum - ); - } else if (property.objectType === Constants.TextValue) { - // if the property is of type text value, we have to check the gui element - // to get the correct default prop params - propType = group.elements.find( - (i: DefaultProperty) => i.guiEle === property.guiElement && i.objectType === property.objectType - ); - } else { - // in all other cases the gui-element resp. the subProp is not relevant - // because the object type is unique - propType = group.elements.find((i: DefaultProperty) => i.objectType === property.objectType); - } + // in all other cases the gui-element resp. the subProp is not relevant + // because the object type is unique + propType = group.elements.find((i: DefaultProperty) => i.objectType === property.objectType); } if (propType) { break; @@ -210,11 +204,8 @@ export class OntologyService { * TODO: move to DSP-JS-Lib similar to `get ApiUrl` */ getIriBaseUrl(): string { - return ( - 'http://' + - this._dspApiConfig.apiHost + - (this._dspApiConfig.apiPort !== null ? ':' + this._dspApiConfig.apiPort : '') + - this._dspApiConfig.apiPath - ); + return `http://${this._dspApiConfig.apiHost}${ + this._dspApiConfig.apiPort !== null ? `:${this._dspApiConfig.apiPort}` : '' + }${this._dspApiConfig.apiPath}`; } } diff --git a/libs/vre/shared/app-helper-services/src/lib/sorting.service.ts b/libs/vre/shared/app-helper-services/src/lib/sorting.service.ts index 65870df9c7..7b867d3469 100644 --- a/libs/vre/shared/app-helper-services/src/lib/sorting.service.ts +++ b/libs/vre/shared/app-helper-services/src/lib/sorting.service.ts @@ -22,18 +22,16 @@ export class SortingService { return -1; } else if (String(a[firstSortKey]).toLowerCase() > String(b[firstSortKey]).toLowerCase()) { return 1; - } else { - if (secondSortKey) { - if (String(a[secondSortKey]).toLowerCase() < String(b[secondSortKey]).toLowerCase()) { - return -1; - } else if (String(a[secondSortKey]).toLowerCase() > String(b[secondSortKey]).toLowerCase()) { - return 1; - } else { - return 0; - } + } else if (secondSortKey) { + if (String(a[secondSortKey]).toLowerCase() < String(b[secondSortKey]).toLowerCase()) { + return -1; + } else if (String(a[secondSortKey]).toLowerCase() > String(b[secondSortKey]).toLowerCase()) { + return 1; } else { return 0; } + } else { + return 0; } }); return sortedArray; diff --git a/libs/vre/shared/app-notification/src/lib/app-notification/app-notification.service.ts b/libs/vre/shared/app-notification/src/lib/app-notification/app-notification.service.ts index a2e3858f5b..9377fe4b4d 100644 --- a/libs/vre/shared/app-notification/src/lib/app-notification/app-notification.service.ts +++ b/libs/vre/shared/app-notification/src/lib/app-notification/app-notification.service.ts @@ -24,11 +24,11 @@ export class NotificationService { duration: 5000, horizontalPosition: 'center', verticalPosition: 'top', - panelClass: type ? type : 'error', + panelClass: type || 'error', }; if (notification instanceof ApiResponseError) { - conf.panelClass = type ? type : 'error'; + conf.panelClass = type || 'error'; notification = notification as ApiResponseError; if ( notification.error && @@ -51,7 +51,7 @@ export class NotificationService { } } } else { - conf.panelClass = type ? type : 'success'; + conf.panelClass = type || 'success'; if (notification instanceof HttpErrorResponse) { message = notification.message; // sipi error diff --git a/libs/vre/shared/app-session/src/lib/app-session.ts b/libs/vre/shared/app-session/src/lib/app-session.ts index 79501c97bd..55c5533602 100644 --- a/libs/vre/shared/app-session/src/lib/app-session.ts +++ b/libs/vre/shared/app-session/src/lib/app-session.ts @@ -66,7 +66,7 @@ export class SessionService { * @param type 'email' or 'username' */ setSession(jwt: string, identifier: string, type: 'email' | 'username'): Observable { - this._dspApiConnection.v2.jsonWebToken = jwt ? jwt : ''; + this._dspApiConnection.v2.jsonWebToken = jwt || ''; // get user information return this._userApiService.get(identifier, type).pipe( @@ -98,9 +98,9 @@ export class SessionService { // check if the api credentials are still valid return this._dspApiConnection.v2.auth.checkCredentials().pipe( - map((credentials: ApiResponseData | ApiResponseError) => { - return this._updateSessionId(credentials, session, tsNow); - }), + map((credentials: ApiResponseData | ApiResponseError) => + this._updateSessionId(credentials, session, tsNow) + ), catchError(() => { // if there is any error checking the credentials (mostly a 401 for after // switching the server where this session/the credentials are unknown), we destroy the session @@ -169,10 +169,10 @@ export class SessionService { id: this._setTimestamp(), user: { name: response.user.username, - jwt: jwt, + jwt, lang: response.user.lang, - sysAdmin: sysAdmin, - projectAdmin: projectAdmin, + sysAdmin, + projectAdmin, }, }; diff --git a/libs/vre/shared/app-session/src/lib/auth.service.ts b/libs/vre/shared/app-session/src/lib/auth.service.ts index 1977cfcf8b..4ae0ece8e4 100644 --- a/libs/vre/shared/app-session/src/lib/auth.service.ts +++ b/libs/vre/shared/app-session/src/lib/auth.service.ts @@ -65,9 +65,9 @@ export class AuthService { // the internal session has expired // check if the api credentials are still valid return this._dspApiConnection.v2.auth.checkCredentials().pipe( - map((credentials: ApiResponseData | ApiResponseError) => { - return this._updateSessionId(credentials); - }), + map((credentials: ApiResponseData | ApiResponseError) => + this._updateSessionId(credentials) + ), catchError(() => { // if there is any error checking the credentials (mostly a 401 for after // switching the server where this session/the credentials are unknown), we destroy the session @@ -132,23 +132,20 @@ export class AuthService { switchMap((response: ApiResponseData | ApiResponseError) => { if (response instanceof ApiResponseData) { return of(true); + } else if (response.status === 401 || response.status === 403) { + // wrong credentials + return throwError({ + type: 'login', + status: response.status, + msg: 'Wrong credentials', + }); } else { - // error handling - if (response.status === 401 || response.status === 403) { - // wrong credentials - return throwError({ - type: 'login', - status: response.status, - msg: 'Wrong credentials', - }); - } else { - // server error - return throwError({ - type: 'server', - status: response.status, - msg: 'Server error', - }); - } + // server error + return throwError({ + type: 'server', + status: response.status, + msg: 'Server error', + }); } }) ); @@ -170,9 +167,7 @@ export class AuthService { .logout() .pipe( take(1), - catchError((error: ApiResponseError) => { - return of(error?.status === 200); - }) + catchError((error: ApiResponseError) => of(error?.status === 200)) ) .subscribe((response: any) => { if (!(response instanceof ApiResponseData)) { diff --git a/libs/vre/shared/app-state-service/src/lib/app-state.service.ts b/libs/vre/shared/app-state-service/src/lib/app-state.service.ts index 1f2c01c1c6..a6021b6cd9 100644 --- a/libs/vre/shared/app-state-service/src/lib/app-state.service.ts +++ b/libs/vre/shared/app-state-service/src/lib/app-state.service.ts @@ -30,12 +30,12 @@ export class ApplicationStateService { // content should never be undefined but we'll check anyway // if it is undefined, it means the app is in an invalid state if (content === undefined) { - return throwError('Requested key "' + key + '" has value of undefined in the application state'); + return throwError(`Requested key "${key}" has value of undefined in the application state`); } else { return of(content.value); } } else { - return throwError('Requested key "' + key + '" is not available in the application state'); + return throwError(`Requested key "${key}" is not available in the application state`); } } @@ -48,7 +48,7 @@ export class ApplicationStateService { key: string, value: ReadUser | ReadUser[] | ReadProject | ReadOntology | ReadOntology[] | ReadGroup[] | ListNodeInfo[] ): void { - this._applicationState.set(key, { value: value }); + this._applicationState.set(key, { value }); } /** diff --git a/libs/vre/shared/app-state/src/lib/current-page/current-page.state.ts b/libs/vre/shared/app-state/src/lib/current-page/current-page.state.ts index 8cab5da1ac..9e33fc0fbd 100644 --- a/libs/vre/shared/app-state/src/lib/current-page/current-page.state.ts +++ b/libs/vre/shared/app-state/src/lib/current-page/current-page.state.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { Action, State, StateContext, Store } from '@ngxs/store'; +import { Action, State, StateContext, Store, Select } from '@ngxs/store'; import { AppInitAction, ReloadCurrentPageAction, diff --git a/libs/vre/shared/app-state/src/lib/ontologies/ontologies.state.ts b/libs/vre/shared/app-state/src/lib/ontologies/ontologies.state.ts index b940d2bb77..7e8151bb49 100644 --- a/libs/vre/shared/app-state/src/lib/ontologies/ontologies.state.ts +++ b/libs/vre/shared/app-state/src/lib/ontologies/ontologies.state.ts @@ -109,9 +109,7 @@ export class OntologiesState { // get all project ontologies return this._dspApiConnection.v2.onto.getOntologiesByProjectIri(projectIri).pipe( take(1), - map((response: OntologiesMetadata | ApiResponseError) => { - return response as OntologiesMetadata; - }), + map((response: OntologiesMetadata | ApiResponseError) => response as OntologiesMetadata), tap({ next: (ontoMeta: OntologiesMetadata) => { if (!ontoMeta.ontologies.length) { @@ -164,14 +162,12 @@ export class OntologiesState { @Action(LoadOntologyAction) loadOntologyAction( ctx: StateContext, - { ontologyIri: ontologyIri, projectUuid, stopLoadingWhenCompleted }: LoadOntologyAction + { ontologyIri, projectUuid, stopLoadingWhenCompleted }: LoadOntologyAction ) { ctx.patchState({ isLoading: true }); return this._dspApiConnection.v2.onto.getOntology(ontologyIri, true).pipe( take(1), - map((response: ReadOntology | ApiResponseError) => { - return response as ReadOntology; - }), + map((response: ReadOntology | ApiResponseError) => response as ReadOntology), tap({ next: (ontology: ReadOntology) => { const projectIri = this._projectService.uuidToIri(projectUuid); @@ -210,9 +206,7 @@ export class OntologiesState { ctx.patchState({ isLoading: true }); return this._dspApiConnection.v2.onto.updateOntology(ontologyMetadata).pipe( take(1), - map((response: OntologyMetadata | ApiResponseError) => { - return response as OntologyMetadata; - }), + map((response: OntologyMetadata | ApiResponseError) => response as OntologyMetadata), tap({ next: () => { const projectIri = this._projectService.uuidToIri(projectUuid); @@ -382,9 +376,7 @@ export class OntologiesState { return this._dspApiConnection.v2.onto.canDeleteOntology(state.currentOntology.id).pipe( take(1), - map((response: CanDoResponse | ApiResponseError) => { - return response as CanDoResponse; - }), + map((response: CanDoResponse | ApiResponseError) => response as CanDoResponse), tap({ next: (response: CanDoResponse) => { ctx.setState({ diff --git a/libs/vre/shared/app-state/src/lib/projects/projects.selectors.ts b/libs/vre/shared/app-state/src/lib/projects/projects.selectors.ts index eeecc8c114..29426414da 100644 --- a/libs/vre/shared/app-state/src/lib/projects/projects.selectors.ts +++ b/libs/vre/shared/app-state/src/lib/projects/projects.selectors.ts @@ -69,7 +69,7 @@ export class ProjectsSelectors { @Selector([ProjectsState, RouterSelectors.params]) static currentProject(state: ProjectsStateModel, params: Params): ReadProject | undefined { const uuid = params[`${RouteConstants.uuidParameter}`]; - const project = state.readProjects.find(project => ProjectService.IriToUuid(project.id) === uuid); + const project = state.readProjects.find(p => ProjectService.IriToUuid(p.id) === uuid); return project; } diff --git a/libs/vre/shared/app-state/src/lib/projects/projects.state.ts b/libs/vre/shared/app-state/src/lib/projects/projects.state.ts index a8e82408e3..4c352517fc 100644 --- a/libs/vre/shared/app-state/src/lib/projects/projects.state.ts +++ b/libs/vre/shared/app-state/src/lib/projects/projects.state.ts @@ -61,9 +61,10 @@ export class ProjectsState { ctx.patchState({ isLoading: true }); return this._dspApiConnection.admin.projectsEndpoint.getProjects().pipe( take(1), - map((projectsResponse: ApiResponseData | ApiResponseError) => { - return projectsResponse as ApiResponseData; - }), + map( + (projectsResponse: ApiResponseData | ApiResponseError) => + projectsResponse as ApiResponseData + ), tap({ next: (projectsResponse: ApiResponseData) => { ctx.setState({ @@ -84,7 +85,7 @@ export class ProjectsState { } @Action(LoadProjectAction, { cancelUncompleted: true }) - loadProjectAction(ctx: StateContext, { projectUuid, isCurrentProject }: LoadProjectAction) { + loadProjectAction(ctx: StateContext, { projectUuid }: LoadProjectAction) { ctx.patchState({ isLoading: true }); const projectIri = this.projectService.uuidToIri(projectUuid); @@ -92,9 +93,10 @@ export class ProjectsState { // and set the project state here return this._dspApiConnection.admin.projectsEndpoint.getProjectByIri(projectIri).pipe( take(1), - map((projectsResponse: ApiResponseData | ApiResponseError) => { - return projectsResponse as ApiResponseData; - }), + map( + (projectsResponse: ApiResponseData | ApiResponseError) => + projectsResponse as ApiResponseData + ), tap({ next: (response: ApiResponseData) => { const project = response.body.project; @@ -106,7 +108,11 @@ export class ProjectsState { state = produce(state, draft => { const index = draft.readProjects.findIndex(p => p.id === project.id); - index > -1 ? (draft.readProjects[index] = project) : draft.readProjects.push(project); + if (index > -1) { + draft.readProjects[index] = project; + } else { + draft.readProjects.push(project); + } draft.isLoading = false; }); @@ -143,9 +149,7 @@ export class ProjectsState { ctx.patchState({ isLoading: true }); return this._dspApiConnection.admin.usersEndpoint.removeUserFromProjectMembership(userId, projectIri).pipe( take(1), - map((response: ApiResponseData | ApiResponseError) => { - return response as ApiResponseData; - }), + map((response: ApiResponseData | ApiResponseError) => response as ApiResponseData), tap({ next: (response: ApiResponseData) => { ctx.dispatch([new SetUserAction(response.body.user), new LoadProjectMembersAction(projectIri)]); @@ -166,9 +170,7 @@ export class ProjectsState { ctx.patchState({ isLoading: true, hasLoadingErrors: false }); return this._dspApiConnection.admin.usersEndpoint.addUserToProjectMembership(userId, projectIri).pipe( take(1), - map((response: ApiResponseData | ApiResponseError) => { - return response as ApiResponseData; - }), + map((response: ApiResponseData | ApiResponseError) => response as ApiResponseData), tap({ next: (response: ApiResponseData) => { ctx.dispatch([new SetUserAction(response.body.user), new LoadProjectMembersAction(projectIri)]); @@ -192,9 +194,10 @@ export class ProjectsState { const projectIri = this.projectService.uuidToIri(projectUuid); return this._dspApiConnection.admin.projectsEndpoint.getProjectMembersByIri(projectIri).pipe( take(1), - map((membersResponse: ApiResponseData | ApiResponseError) => { - return membersResponse as ApiResponseData; - }), + map( + (membersResponse: ApiResponseData | ApiResponseError) => + membersResponse as ApiResponseData + ), tap({ next: (response: ApiResponseData) => { ctx.setState({ @@ -218,9 +221,10 @@ export class ProjectsState { ctx.patchState({ isLoading: true }); return this._dspApiConnection.admin.groupsEndpoint.getGroups().pipe( take(1), - map((groupsResponse: ApiResponseData | ApiResponseError) => { - return groupsResponse as ApiResponseData; - }), + map( + (groupsResponse: ApiResponseData | ApiResponseError) => + groupsResponse as ApiResponseData + ), tap({ next: (response: ApiResponseData) => { const groups: IKeyValuePairs = {}; @@ -251,9 +255,9 @@ export class ProjectsState { ctx.patchState({ isLoading: true }); return this._dspApiConnection.admin.projectsEndpoint.updateProject(projectUuid, projectData).pipe( take(1), - map((response: ApiResponseData | ApiResponseError) => { - return response as ApiResponseData; - }), + map( + (response: ApiResponseData | ApiResponseError) => response as ApiResponseData + ), tap({ next: (response: ApiResponseData) => { ctx.dispatch(new LoadProjectsAction()); diff --git a/libs/vre/shared/app-state/src/lib/router/router-state.serializer.ts b/libs/vre/shared/app-state/src/lib/router/router-state.serializer.ts index 1e056e6af3..ba5bd82417 100644 --- a/libs/vre/shared/app-state/src/lib/router/router-state.serializer.ts +++ b/libs/vre/shared/app-state/src/lib/router/router-state.serializer.ts @@ -21,7 +21,7 @@ export class CustomRouterStateSerializer implements RouterStateSerializer Object.keys(v.params).length).map(v => v.params)[0]; - params = params ? params : route.params; + params = params || route.params; return { url, params, queryParams, data }; } diff --git a/libs/vre/shared/app-state/src/lib/user/user.state.ts b/libs/vre/shared/app-state/src/lib/user/user.state.ts index 94925a0ea9..2433e7771d 100644 --- a/libs/vre/shared/app-state/src/lib/user/user.state.ts +++ b/libs/vre/shared/app-state/src/lib/user/user.state.ts @@ -14,7 +14,7 @@ import { LoadUsersAction, LogUserOutAction, RemoveUserAction, - ResetUsersAction as ResetUsersAction, + ResetUsersAction, SetUserAction, SetUserProjectGroupsAction, } from './user.actions'; diff --git a/libs/vre/shared/app-string-literal/src/lib/app-string-literal/dasch-swiss-string-literal.component.ts b/libs/vre/shared/app-string-literal/src/lib/app-string-literal/dasch-swiss-string-literal.component.ts index f4c71aaae3..6362e3d0a0 100644 --- a/libs/vre/shared/app-string-literal/src/lib/app-string-literal/dasch-swiss-string-literal.component.ts +++ b/libs/vre/shared/app-string-literal/src/lib/app-string-literal/dasch-swiss-string-literal.component.ts @@ -133,7 +133,7 @@ export class AppStringLiteralComponent implements OnInit, OnChanges { // set selected language, if it's not defined yet if (!this.language) { const usersLanguage = this._store.selectSnapshot(UserSelectors.language) as string; - this.language = usersLanguage ? usersLanguage : navigator.language.substring(0, 2); // get default language from browser + this.language = usersLanguage || navigator.language.substring(0, 2); // get default language from browser } // does the defined language exists in our supported languages list? @@ -261,7 +261,7 @@ export class AppStringLiteralComponent implements OnInit, OnChanges { if (index < 0 && value) { // value doesn't exist in stringLiterals: add one const newValue: StringLiteral = { - value: value, + value, language: lang, }; this.value.push(newValue); diff --git a/package.json b/package.json index 1067ac22e9..688ad04c02 100644 --- a/package.json +++ b/package.json @@ -113,7 +113,6 @@ "eslint-plugin-import": "^2.27.5", "eslint-plugin-jsdoc": "^46.4.4", "eslint-plugin-prettier": "^5.0.1", - "eslint-plugin-simple-import-sort": "^10.0.0", "eslint-plugin-unused-imports": "^3.0.0", "jasmine-core": "~4.6.0", "jasmine-spec-reporter": "~7.0.0",