Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
|---|---|---|---|---|---|---|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/form-modal/form-modal.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed, FixtureHelper, FormHelper } from '~/testing/unit-test-helper';
import { FormModalComponent } from './form-modal.component';
describe('InputModalComponent', () => {
let component: FormModalComponent;
let fixture: ComponentFixture<FormModalComponent>;
let fh: FixtureHelper;
let formHelper: FormHelper;
let submitted: object;
const initialState = {
titleText: 'Some title',
message: 'Some description',
fields: [
{
type: 'text',
name: 'requiredField',
value: 'some-value',
required: true
},
{
type: 'number',
name: 'optionalField',
label: 'Optional',
errors: { min: 'Value has to be above zero!' },
validators: [Validators.min(0), Validators.max(10)]
},
{
type: 'binary',
name: 'dimlessBinary',
label: 'Size',
value: 2048,
validators: [CdValidators.binaryMin(1024), CdValidators.binaryMax(3072)]
}
],
submitButtonText: 'Submit button name',
onSubmit: (values: object) => (submitted = values)
};
configureTestBed({
imports: [RouterTestingModule, ReactiveFormsModule, SharedModule],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(FormModalComponent);
component = fixture.componentInstance;
Object.assign(component, initialState);
fixture.detectChanges();
fh = new FixtureHelper(fixture);
formHelper = new FormHelper(component.formGroup);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('has the defined title', () => {
fh.expectTextToBe('.modal-title', 'Some title');
});
it('has the defined description', () => {
fh.expectTextToBe('.modal-body > p', 'Some description');
});
it('should display both inputs', () => {
fh.expectElementVisible('#requiredField', true);
fh.expectElementVisible('#optionalField', true);
});
it('has one defined label field', () => {
fh.expectTextToBe('.cd-col-form-label', 'Optional');
});
it('has a predefined values for requiredField', () => {
fh.expectFormFieldToBe('#requiredField', 'some-value');
});
it('gives back all form values on submit', () => {
component.onSubmitForm(component.formGroup.value);
expect(submitted).toEqual({
dimlessBinary: 2048,
requiredField: 'some-value',
optionalField: null
});
});
it('tests required field validation', () => {
formHelper.expectErrorChange('requiredField', '', 'required');
});
it('tests required field message', () => {
formHelper.setValue('requiredField', '', true);
fh.expectTextToBe('.cd-requiredField-form-group .invalid-feedback', 'This field is required.');
});
it('tests custom validator on number field', () => {
formHelper.expectErrorChange('optionalField', -1, 'min');
formHelper.expectErrorChange('optionalField', 11, 'max');
});
it('tests custom validator error message', () => {
formHelper.setValue('optionalField', -1, true);
fh.expectTextToBe(
'.cd-optionalField-form-group .invalid-feedback',
'Value has to be above zero!'
);
});
it('tests default error message', () => {
formHelper.setValue('optionalField', 11, true);
fh.expectTextToBe('.cd-optionalField-form-group .invalid-feedback', 'An error occurred.');
});
it('tests binary error messages', () => {
formHelper.setValue('dimlessBinary', '4 K', true);
fh.expectTextToBe(
'.cd-dimlessBinary-form-group .invalid-feedback',
'Size has to be at most 3 KiB or less'
);
formHelper.setValue('dimlessBinary', '0.5 K', true);
fh.expectTextToBe(
'.cd-dimlessBinary-form-group .invalid-feedback',
'Size has to be at least 1 KiB or more'
);
});
it('shows result of dimlessBinary pipe', () => {
fh.expectFormFieldToBe('#dimlessBinary', '2 KiB');
});
it('changes dimlessBinary value and the result will still be a number', () => {
formHelper.setValue('dimlessBinary', '3 K', true);
component.onSubmitForm(component.formGroup.value);
expect(submitted).toEqual({
dimlessBinary: 3072,
requiredField: 'some-value',
optionalField: null
});
});
});
| 4,646
| 29.98
| 99
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/form-modal/form-modal.component.ts
|
import { Component, OnInit } from '@angular/core';
import { FormControl, ValidatorFn, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdFormModalFieldConfig } from '~/app/shared/models/cd-form-modal-field-config';
import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe';
import { FormatterService } from '~/app/shared/services/formatter.service';
@Component({
selector: 'cd-form-modal',
templateUrl: './form-modal.component.html',
styleUrls: ['./form-modal.component.scss']
})
export class FormModalComponent implements OnInit {
// Input
titleText: string;
message: string;
fields: CdFormModalFieldConfig[];
submitButtonText: string;
onSubmit: Function;
// Internal
formGroup: CdFormGroup;
constructor(
public activeModal: NgbActiveModal,
private formBuilder: CdFormBuilder,
private formatter: FormatterService,
private dimlessBinaryPipe: DimlessBinaryPipe
) {}
ngOnInit() {
this.createForm();
}
createForm() {
const controlsConfig: Record<string, FormControl> = {};
this.fields.forEach((field) => {
controlsConfig[field.name] = this.createFormControl(field);
});
this.formGroup = this.formBuilder.group(controlsConfig);
}
private createFormControl(field: CdFormModalFieldConfig): FormControl {
let validators: ValidatorFn[] = [];
if (_.isBoolean(field.required) && field.required) {
validators.push(Validators.required);
}
if (field.validators) {
validators = validators.concat(field.validators);
}
return new FormControl(
_.defaultTo(
field.type === 'binary' ? this.dimlessBinaryPipe.transform(field.value) : field.value,
null
),
{ validators }
);
}
getError(field: CdFormModalFieldConfig): string {
const formErrors = this.formGroup.get(field.name).errors;
const errors = Object.keys(formErrors).map((key) => {
return this.getErrorMessage(key, formErrors[key], field.errors);
});
return errors.join('<br>');
}
private getErrorMessage(
error: string,
errorContext: any,
fieldErrors: { [error: string]: string }
): string {
if (fieldErrors) {
const customError = fieldErrors[error];
if (customError) {
return customError;
}
}
if (['binaryMin', 'binaryMax'].includes(error)) {
// binaryMin and binaryMax return a function that take I18n to
// provide a translated error message.
return errorContext();
}
if (error === 'required') {
return $localize`This field is required.`;
}
return $localize`An error occurred.`;
}
onSubmitForm(values: any) {
const binaries = this.fields
.filter((field) => field.type === 'binary')
.map((field) => field.name);
binaries.forEach((key) => {
const value = values[key];
if (value) {
values[key] = this.formatter.toBytes(value);
}
});
this.activeModal.close();
if (_.isFunction(this.onSubmit)) {
this.onSubmit(values);
}
}
}
| 3,248
| 28.27027
| 94
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/grafana/grafana.component.html
|
<!-- Embed dashboard -->
<cd-loading-panel *ngIf="loading && grafanaExist"
i18n>Loading panel data...</cd-loading-panel>
<cd-alert-panel type="info"
*ngIf="!grafanaExist"
i18n>Please consult the <cd-doc section="grafana"></cd-doc> on
how to configure and enable the monitoring functionality.</cd-alert-panel>
<cd-alert-panel type="info"
*ngIf="!dashboardExist"
i18n>Grafana Dashboard doesn't exist. Please refer to
<cd-doc section="grafana"></cd-doc> on how to add dashboards to Grafana.</cd-alert-panel>
<ng-container *ngIf="grafanaExist && dashboardExist">
<div class="row mb-3">
<div class="col-lg-5 d-flex">
<div class="col-md-3 timepicker">
<label for="timepicker"
class="mt-2"
i18n>Grafana Time Picker</label>
</div>
<div class="col-sm-4">
<select id="timepicker"
name="timepicker"
class="form-select"
[(ngModel)]="time"
(ngModelChange)="onTimepickerChange($event)">
<option *ngFor="let key of grafanaTimes"
[ngValue]="key.value">{{ key.name }}
</option>
</select>
</div>
<div class="col-sm-1">
<button class="btn btn-light ms-3"
i18n-title
title="Reset Settings"
(click)="reset()">
<i [ngClass]="[icons.undo]"></i>
</button>
</div>
<div class="col-sm-1">
<button class="btn btn-light ms-3"
i18n-title
title="Show hidden information"
(click)="showMessage = !showMessage">
<i [ngClass]="[icons.infoCircle, icons.large]"></i>
</button>
</div>
</div>
</div>
<div class="row">
<div class="col my-2"
*ngIf="showMessage">
<cd-alert-panel type="info"
class="mb-3"
*ngIf="showMessage"
dismissible="true"
(dismissed)="showMessage = false"
i18n>If no embedded Grafana Dashboard appeared below, please follow <a [href]="grafanaSrc"
target="_blank"
noopener
noreferrer>this link </a> to check if Grafana is reachable and there are no HTTPS certificate issues. You may need to reload this page after accepting any Browser certificate exceptions</cd-alert-panel>
</div>
</div>
<div class="row">
<div class="col">
<div class="grafana-container">
<iframe #iframe
id="iframe"
[src]="grafanaSrc"
class="grafana"
[ngClass]="panelStyle"
frameborder="0"
scrolling="no"
[title]="title"
i18n-title>
</iframe>
</div>
</div>
</div>
</ng-container>
| 2,955
| 33.776471
| 224
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/grafana/grafana.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap';
import { of } from 'rxjs';
import { SettingsService } from '~/app/shared/api/settings.service';
import { CephReleaseNamePipe } from '~/app/shared/pipes/ceph-release-name.pipe';
import { SummaryService } from '~/app/shared/services/summary.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { AlertPanelComponent } from '../alert-panel/alert-panel.component';
import { DocComponent } from '../doc/doc.component';
import { LoadingPanelComponent } from '../loading-panel/loading-panel.component';
import { GrafanaComponent } from './grafana.component';
describe('GrafanaComponent', () => {
let component: GrafanaComponent;
let fixture: ComponentFixture<GrafanaComponent>;
const expected_url =
'http:localhost:3000/d/foo/somePath&refresh=2s&var-datasource=Dashboard1&kiosk&from=now-1h&to=now';
const expected_logs_url =
'http:localhost:3000/explore?orgId=1&left={"datasource": "Loki", "queries": [{"refId": "A"}], "range": {"from": "now-1h", "to": "now"}}&kiosk';
configureTestBed({
declarations: [GrafanaComponent, AlertPanelComponent, LoadingPanelComponent, DocComponent],
imports: [NgbAlertModule, HttpClientTestingModule, RouterTestingModule, FormsModule],
providers: [CephReleaseNamePipe, SettingsService, SummaryService]
});
beforeEach(() => {
fixture = TestBed.createComponent(GrafanaComponent);
component = fixture.componentInstance;
component.grafanaPath = 'somePath';
component.type = 'metrics';
component.uid = 'foo';
component.title = 'panel title';
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should have found out that grafana does not exist', () => {
fixture.detectChanges();
expect(component.grafanaExist).toBe(false);
expect(component.baseUrl).toBe(undefined);
expect(component.loading).toBe(true);
expect(component.url).toBe(undefined);
expect(component.grafanaSrc).toEqual(undefined);
});
describe('with grafana initialized', () => {
beforeEach(() => {
TestBed.inject(SettingsService)['settings'] = { 'api/grafana/url': 'http:localhost:3000' };
component.type = 'metrics';
fixture.detectChanges();
});
it('should have found out that grafana exists and dashboard exists', () => {
expect(component.time).toBe('from=now-1h&to=now');
expect(component.grafanaExist).toBe(true);
expect(component.baseUrl).toBe('http:localhost:3000/d/');
expect(component.loading).toBe(false);
expect(component.url).toBe(expected_url);
expect(component.grafanaSrc).toEqual({
changingThisBreaksApplicationSecurity: expected_url
});
});
it('should reset the values', () => {
component.reset();
expect(component.time).toBe('from=now-1h&to=now');
expect(component.url).toBe(expected_url);
expect(component.grafanaSrc).toEqual({
changingThisBreaksApplicationSecurity: expected_url
});
});
it('should have Dashboard', () => {
TestBed.inject(SettingsService).validateGrafanaDashboardUrl = () => of({ uid: 200 });
expect(component.dashboardExist).toBe(true);
});
});
describe('with loki datasource', () => {
beforeEach(() => {
TestBed.inject(SettingsService)['settings'] = { 'api/grafana/url': 'http:localhost:3000' };
component.type = 'logs';
component.grafanaPath = 'explore?';
fixture.detectChanges();
});
it('should have found out that Loki Log Search exists', () => {
expect(component.grafanaExist).toBe(true);
expect(component.baseUrl).toBe('http:localhost:3000/d/');
expect(component.loading).toBe(false);
expect(component.url).toBe(expected_logs_url);
expect(component.grafanaSrc).toEqual({
changingThisBreaksApplicationSecurity: expected_logs_url
});
});
});
});
| 4,172
| 38.367925
| 147
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/grafana/grafana.component.ts
|
import { Component, Input, OnChanges, OnInit } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { SettingsService } from '~/app/shared/api/settings.service';
import { Icons } from '~/app/shared/enum/icons.enum';
@Component({
selector: 'cd-grafana',
templateUrl: './grafana.component.html',
styleUrls: ['./grafana.component.scss']
})
export class GrafanaComponent implements OnInit, OnChanges {
grafanaSrc: SafeUrl;
url: string;
protocol: string;
host: string;
port: number;
baseUrl: any;
panelStyle: any;
grafanaExist = false;
mode = '&kiosk';
datasource: string;
loading = true;
styles: Record<string, string> = {};
dashboardExist = true;
showMessage = false;
time: string;
grafanaTimes: any;
icons = Icons;
readonly DEFAULT_TIME: string = 'from=now-1h&to=now';
@Input()
type: string;
@Input()
grafanaPath: string;
@Input()
grafanaStyle: string;
@Input()
uid: string;
@Input()
title: string;
constructor(private sanitizer: DomSanitizer, private settingsService: SettingsService) {
this.grafanaTimes = [
{
name: $localize`Last 5 minutes`,
value: 'from=now-5m&to=now'
},
{
name: $localize`Last 15 minutes`,
value: 'from=now-15m&to=now'
},
{
name: $localize`Last 30 minutes`,
value: 'from=now-30m&to=now'
},
{
name: $localize`Last 1 hour (Default)`,
value: 'from=now-1h&to=now'
},
{
name: $localize`Last 3 hours`,
value: 'from=now-3h&to=now'
},
{
name: $localize`Last 6 hours`,
value: 'from=now-6h&to=now'
},
{
name: $localize`Last 12 hours`,
value: 'from=now-12h&to=now'
},
{
name: $localize`Last 24 hours`,
value: 'from=now-24h&to=now'
},
{
name: $localize`Yesterday`,
value: 'from=now-1d%2Fd&to=now-1d%2Fd'
},
{
name: $localize`Today so far`,
value: 'from=now%2Fd&to=now'
},
{
name: $localize`Day before yesterday`,
value: 'from=now-2d%2Fd&to=now-2d%2Fd'
},
{
name: $localize`Last 2 days`,
value: 'from=now-2d&to=now'
},
{
name: $localize`This day last week`,
value: 'from=now-7d%2Fd&to=now-7d%2Fd'
},
{
name: $localize`Previous week`,
value: 'from=now-1w%2Fw&to=now-1w%2Fw'
},
{
name: $localize`This week so far`,
value: 'from=now%2Fw&to=now'
},
{
name: $localize`Last 7 days`,
value: 'from=now-7d&to=now'
},
{
name: $localize`Previous month`,
value: 'from=now-1M%2FM&to=now-1M%2FM'
},
{
name: $localize`This month so far`,
value: 'from=now%2FM&to=now'
},
{
name: $localize`Last 30 days`,
value: 'from=now-30d&to=now'
},
{
name: $localize`Last 90 days`,
value: 'from=now-90d&to=now'
},
{
name: $localize`Last 6 months`,
value: 'from=now-6M&to=now'
},
{
name: $localize`Last 1 year`,
value: 'from=now-1y&to=now'
},
{
name: $localize`Previous year`,
value: 'from=now-1y%2Fy&to=now-1y%2Fy'
},
{
name: $localize`This year so far`,
value: 'from=now%2Fy&to=now'
},
{
name: $localize`Last 2 years`,
value: 'from=now-2y&to=now'
},
{
name: $localize`Last 5 years`,
value: 'from=now-5y&to=now'
}
];
}
ngOnInit() {
this.time = this.DEFAULT_TIME;
this.styles = {
one: 'grafana_one',
two: 'grafana_two',
three: 'grafana_three',
four: 'grafana_four'
};
this.datasource = this.type === 'metrics' ? 'Dashboard1' : 'Loki';
this.settingsService.ifSettingConfigured('api/grafana/url', (url) => {
this.grafanaExist = true;
this.loading = false;
this.baseUrl = url + '/d/';
this.getFrame();
});
this.panelStyle = this.styles[this.grafanaStyle];
}
getFrame() {
this.settingsService
.validateGrafanaDashboardUrl(this.uid)
.subscribe((data: any) => (this.dashboardExist = data === 200));
if (this.type === 'metrics') {
this.url = `${this.baseUrl}${this.uid}/${this.grafanaPath}&refresh=2s&var-datasource=${this.datasource}${this.mode}&${this.time}`;
} else {
this.url = `${this.baseUrl.slice(0, -2)}${this.grafanaPath}orgId=1&left={"datasource": "${
this.datasource
}", "queries": [{"refId": "A"}], "range": {"from": "now-1h", "to": "now"}}${this.mode}`;
}
this.grafanaSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
onTimepickerChange() {
if (this.grafanaExist) {
this.getFrame();
}
}
reset() {
this.time = this.DEFAULT_TIME;
if (this.grafanaExist) {
this.getFrame();
}
}
ngOnChanges() {
if (this.grafanaExist) {
this.getFrame();
}
}
}
| 5,092
| 23.843902
| 136
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/helper/helper.component.html
|
<ng-template #popoverTpl>
<div [class]="class"
[innerHtml]="html">
</div>
<ng-content></ng-content>
</ng-template>
<i [ngClass]="iconClass ? iconClass : [icons.questionCircle]"
aria-hidden="true"
[ngbPopover]="popoverTpl"
(click)="$event.preventDefault();">
</i>
| 285
| 22.833333
| 61
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/helper/helper.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap';
import { configureTestBed } from '~/testing/unit-test-helper';
import { HelperComponent } from './helper.component';
describe('HelperComponent', () => {
let component: HelperComponent;
let fixture: ComponentFixture<HelperComponent>;
configureTestBed({
imports: [NgbPopoverModule],
declarations: [HelperComponent]
});
beforeEach(() => {
fixture = TestBed.createComponent(HelperComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 700
| 24.962963
| 66
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/helper/helper.component.ts
|
import { Component, Input } from '@angular/core';
import { Icons } from '~/app/shared/enum/icons.enum';
@Component({
selector: 'cd-helper',
templateUrl: './helper.component.html',
styleUrls: ['./helper.component.scss']
})
export class HelperComponent {
@Input()
class: string;
@Input()
iconClass = '';
@Input()
html: any;
icons = Icons;
}
| 364
| 15.590909
| 53
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/language-selector/language-selector.component.html
|
<div ngbDropdown
display="dynamic"
placement="bottom-right">
<a ngbDropdownToggle
i18n-title
id="toggle-language-button"
title="Select a Language"
role="button">
{{ allLanguages[selectedLanguage] }}
</a>
<div ngbDropdownMenu
role="listbox"
aria-labelledby="toggle-language-button">
<ng-container *ngFor="let lang of supportedLanguages | keyvalue">
<button ngbDropdownItem
role="option"
(click)="changeLanguage(lang.key)">
{{ lang.value }}
</button>
</ng-container>
</div>
</div>
| 591
| 24.73913
| 69
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/language-selector/language-selector.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { configureTestBed } from '~/testing/unit-test-helper';
import { LanguageSelectorComponent } from './language-selector.component';
describe('LanguageSelectorComponent', () => {
let component: LanguageSelectorComponent;
let fixture: ComponentFixture<LanguageSelectorComponent>;
configureTestBed({
declarations: [LanguageSelectorComponent],
imports: [FormsModule, HttpClientTestingModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(LanguageSelectorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
spyOn(component, 'reloadWindow').and.callFake(() => component.ngOnInit());
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should read current language', () => {
expect(component.selectedLanguage).toBe('en-US');
});
const expectLanguageChange = (lang: string) => {
component.changeLanguage(lang);
const cookie = document.cookie.split(';').filter((item) => item.includes(`cd-lang=${lang}`));
expect(cookie.length).toBe(1);
};
it('should change to cs', () => {
expectLanguageChange('cs');
});
it('should change to de', () => {
expectLanguageChange('de');
});
it('should change to es', () => {
expectLanguageChange('es');
});
it('should change to fr', () => {
expectLanguageChange('fr');
});
it('should change to id', () => {
expectLanguageChange('id');
});
it('should change to it', () => {
expectLanguageChange('it');
});
it('should change to ja', () => {
expectLanguageChange('ja');
});
it('should change to ko', () => {
expectLanguageChange('ko');
});
it('should change to pl', () => {
expectLanguageChange('pl');
});
it('should change to pt', () => {
expectLanguageChange('pt');
});
it('should change to zh-Hans', () => {
expectLanguageChange('zh-Hans');
});
it('should change to zh-Hant', () => {
expectLanguageChange('zh-Hant');
});
});
| 2,176
| 24.313953
| 97
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/language-selector/language-selector.component.ts
|
import { Component, OnInit } from '@angular/core';
import _ from 'lodash';
import { LanguageService } from '~/app/shared/services/language.service';
import { SupportedLanguages } from './supported-languages.enum';
@Component({
selector: 'cd-language-selector',
templateUrl: './language-selector.component.html',
styleUrls: ['./language-selector.component.scss']
})
export class LanguageSelectorComponent implements OnInit {
allLanguages = SupportedLanguages;
supportedLanguages: Record<string, any> = {};
selectedLanguage: string;
constructor(private languageService: LanguageService) {}
ngOnInit() {
this.selectedLanguage = this.languageService.getLocale();
this.languageService.getLanguages().subscribe((langs) => {
this.supportedLanguages = _.pick(SupportedLanguages, langs) as Object;
});
}
/**
* Jest is being more restricted regarding spying on the reload method.
* This will allow us to spyOn this method instead.
*/
reloadWindow() {
window.location.reload();
}
changeLanguage(lang: string) {
this.languageService.setLocale(lang);
this.reloadWindow();
}
}
| 1,138
| 26.780488
| 76
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/language-selector/supported-languages.enum.ts
|
// When adding a new supported language make sure to add a test for it in:
// language-selector.component.spec.ts
export enum SupportedLanguages {
'cs' = 'Čeština',
'de' = 'Deutsch',
'en-US' = 'English',
'es' = 'Español',
'fr' = 'Français',
'id' = 'Bahasa Indonesia',
'it' = 'Italiano',
'ja' = '日本語',
'ko' = '한국어',
'pl' = 'Polski',
'pt' = 'Português (brasileiro)',
'zh-Hans' = '中文 (简体)',
'zh-Hant' = '中文 (繁體)'
}
| 438
| 23.388889
| 74
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/loading-panel/loading-panel.component.html
|
<ngb-alert type="info"
[dismissible]="false">
<strong>
<i [ngClass]="[icons.spinner, icons.spin]"
aria-hidden="true"
class="me-2"></i>
</strong>
<ng-content></ng-content>
</ngb-alert>
| 219
| 21
| 46
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/loading-panel/loading-panel.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap';
import { configureTestBed } from '~/testing/unit-test-helper';
import { LoadingPanelComponent } from './loading-panel.component';
describe('LoadingPanelComponent', () => {
let component: LoadingPanelComponent;
let fixture: ComponentFixture<LoadingPanelComponent>;
configureTestBed({
declarations: [LoadingPanelComponent],
imports: [NgbAlertModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(LoadingPanelComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 739
| 26.407407
| 66
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/loading-panel/loading-panel.component.ts
|
import { Component } from '@angular/core';
import { Icons } from '~/app/shared/enum/icons.enum';
@Component({
selector: 'cd-loading-panel',
templateUrl: './loading-panel.component.html',
styleUrls: ['./loading-panel.component.scss']
})
export class LoadingPanelComponent {
icons = Icons;
}
| 300
| 22.153846
| 53
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/modal/modal.component.html
|
<div [ngClass]="pageURL ? 'modal' : ''">
<div [ngClass]="pageURL ? 'modal-dialog' : ''">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title float-start">
<ng-content select=".modal-title"></ng-content>
</h4>
<button type="button"
class="btn-close float-end"
aria-label="Close"
(click)="close()">
</button>
</div>
<ng-content select=".modal-content"></ng-content>
</div>
</div>
</div>
| 532
| 27.052632
| 57
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/modal/modal.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { configureTestBed } from '~/testing/unit-test-helper';
import { ModalComponent } from './modal.component';
describe('ModalComponent', () => {
let component: ModalComponent;
let fixture: ComponentFixture<ModalComponent>;
let routerNavigateSpy: jasmine.Spy;
configureTestBed({
declarations: [ModalComponent],
imports: [RouterTestingModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(ModalComponent);
component = fixture.componentInstance;
routerNavigateSpy = spyOn(TestBed.inject(Router), 'navigate');
routerNavigateSpy.and.returnValue(true);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call the hide callback function', () => {
spyOn(component.hide, 'emit');
const nativeElement = fixture.nativeElement;
const button = nativeElement.querySelector('button');
button.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(component.hide.emit).toHaveBeenCalled();
});
it('should hide the modal', () => {
component.modalRef = new NgbActiveModal();
spyOn(component.modalRef, 'close');
component.close();
expect(component.modalRef.close).toHaveBeenCalled();
});
it('should hide the routed modal', () => {
component.pageURL = 'hosts';
component.close();
expect(routerNavigateSpy).toHaveBeenCalledTimes(1);
expect(routerNavigateSpy).toHaveBeenCalledWith(['hosts', { outlets: { modal: null } }]);
});
});
| 1,749
| 30.818182
| 92
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/modal/modal.component.ts
|
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Router } from '@angular/router';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'cd-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.scss']
})
export class ModalComponent {
@Input()
modalRef: NgbActiveModal;
@Input()
pageURL: string;
/**
* Should be a function that is triggered when the modal is hidden.
*/
@Output()
hide = new EventEmitter();
constructor(private router: Router) {}
close() {
this.pageURL
? this.router.navigate([this.pageURL, { outlets: { modal: null } }])
: this.modalRef?.close();
this.hide.emit();
}
}
| 728
| 21.78125
| 74
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/motd/motd.component.html
|
<cd-alert-panel *ngIf="motd"
size="slim"
[showTitle]="false"
[type]="motd.severity"
[dismissible]="motd.severity !== 'danger'"
(dismissed)="onDismissed()">
<span [innerHTML]="motd.message | sanitizeHtml"></span>
</cd-alert-panel>
| 312
| 33.777778
| 58
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/motd/motd.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DashboardModule } from '~/app/ceph/dashboard/dashboard.module';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { MotdComponent } from './motd.component';
describe('MotdComponent', () => {
let component: MotdComponent;
let fixture: ComponentFixture<MotdComponent>;
configureTestBed({
imports: [DashboardModule, HttpClientTestingModule, SharedModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(MotdComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 829
| 29.740741
| 72
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/motd/motd.component.ts
|
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { Motd } from '~/app/shared/api/motd.service';
import { MotdNotificationService } from '~/app/shared/services/motd-notification.service';
@Component({
selector: 'cd-motd',
templateUrl: './motd.component.html',
styleUrls: ['./motd.component.scss']
})
export class MotdComponent implements OnInit, OnDestroy {
motd: Motd | undefined = undefined;
private subscription: Subscription;
constructor(private motdNotificationService: MotdNotificationService) {}
ngOnInit(): void {
this.subscription = this.motdNotificationService.motd$.subscribe((motd: Motd | undefined) => {
this.motd = motd;
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
onDismissed(): void {
this.motdNotificationService.hide();
}
}
| 871
| 24.647059
| 98
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/notifications-sidebar/notifications-sidebar.component.html
|
<ng-template #tasksTpl>
<!-- Executing -->
<div *ngFor="let executingTask of executingTasks; trackBy:trackByFn">
<div class="card tc_task border-0">
<div class="row no-gutters">
<div class="col-md-2 text-center">
<span [ngClass]="[icons.stack, icons.large2x]"
class="text-info">
<i [ngClass]="[icons.stack2x, icons.circle]"></i>
<i [ngClass]="[icons.stack1x, icons.spinner, icons.spin, icons.inverse]"></i>
</span>
</div>
<div class="col-md-9">
<div class="card-body p-1">
<h6 class="card-title bold">{{ executingTask.description }}</h6>
<div class="mb-1">
<ngb-progressbar type="info"
[value]="executingTask?.progress"
[striped]="true"
[animated]="true"></ngb-progressbar>
</div>
<p class="card-text text-muted">
<small class="date float-start">
{{ executingTask.begin_time | cdDate }}
</small>
<span class="float-end">
{{ executingTask.progress || 0 }} %
</span>
</p>
</div>
</div>
</div>
</div>
<hr>
</div>
</ng-template>
<ng-template #notificationsTpl>
<ng-container *ngIf="notifications.length > 0">
<button type="button"
class="btn btn-light btn-block"
(click)="removeAll(); $event.stopPropagation()">
<i [ngClass]="[icons.trash]"
aria-hidden="true"></i>
<ng-container i18n>Clear notifications</ng-container>
</button>
<hr>
<div *ngFor="let notification of notifications; let i = index"
[ngClass]="notification.borderClass">
<div class="card tc_notification border-0">
<div class="row no-gutters">
<div class="col-md-2 text-center">
<span [ngClass]="[icons.stack, icons.large2x, notification.textClass]">
<i [ngClass]="[icons.circle, icons.stack2x]"></i>
<i [ngClass]="[icons.stack1x, icons.inverse, notification.iconClass]"></i>
</span>
</div>
<div class="col-md-10">
<div class="card-body p-1">
<button class="btn btn-link float-end mt-0 pt-0"
title="Remove notification"
i18n-title
(click)="remove(i); $event.stopPropagation()">
<i [ngClass]="[icons.trash]"></i>
</button>
<button *ngIf="notification.application === 'Prometheus' && notification.type !== 2 && !notification.alertSilenced"
class="btn btn-link float-end text-muted mute m-0 p-0"
title="Silence Alert"
i18n-title
(click)="silence(notification)">
<i [ngClass]="[icons.mute]"></i>
</button>
<button *ngIf="notification.application === 'Prometheus' && notification.type !== 2 && notification.alertSilenced"
class="btn btn-link float-end text-muted mute m-0 p-0"
title="Expire Silence"
i18n-title
(click)="expire(notification)">
<i [ngClass]="[icons.bell]"></i>
</button>
<h6 class="card-title bold">{{ notification.title }}</h6>
<p class="card-text"
[innerHtml]="notification.message"></p>
<p class="card-text text-muted">
<ng-container *ngIf="notification.duration">
<small>
<ng-container i18n>Duration:</ng-container> {{ notification.duration | duration }}
</small>
<br>
</ng-container>
<small class="date"
[title]="notification.timestamp | cdDate">{{ notification.timestamp | relativeDate }}</small>
<i class="float-end custom-icon"
[ngClass]="[notification.applicationClass]"
[title]="notification.application"></i>
</p>
</div>
</div>
</div>
</div>
<hr>
</div>
</ng-container>
</ng-template>
<ng-template #emptyTpl>
<div *ngIf="notifications.length === 0 && executingTasks.length === 0">
<div class="message text-center"
i18n>There are no notifications.</div>
</div>
</ng-template>
<div class="card"
(clickOutside)="closeSidebar()"
[clickOutsideEnabled]="isSidebarOpened">
<div class="card-header">
<ng-container i18n>Tasks and Notifications</ng-container>
<button class="btn-close float-end"
tabindex="-1"
type="button"
title="close"
(click)="closeSidebar()">
</button>
</div>
<ngx-simplebar [options]="simplebar">
<div class="card-body">
<ng-container *ngTemplateOutlet="tasksTpl"></ng-container>
<ng-container *ngTemplateOutlet="notificationsTpl"></ng-container>
<ng-container *ngTemplateOutlet="emptyTpl"></ng-container>
</div>
</ngx-simplebar>
</div>
| 5,251
| 35.22069
| 129
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/notifications-sidebar/notifications-sidebar.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import {
ComponentFixture,
discardPeriodicTasks,
fakeAsync,
TestBed,
tick
} from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbProgressbarModule } from '@ng-bootstrap/ng-bootstrap';
import { ClickOutsideModule } from 'ng-click-outside';
import { ToastrModule } from 'ngx-toastr';
import { SimplebarAngularModule } from 'simplebar-angular';
import { PrometheusService } from '~/app/shared/api/prometheus.service';
import { RbdService } from '~/app/shared/api/rbd.service';
import { SettingsService } from '~/app/shared/api/settings.service';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { ExecutingTask } from '~/app/shared/models/executing-task';
import { Permissions } from '~/app/shared/models/permissions';
import { PipesModule } from '~/app/shared/pipes/pipes.module';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { NotificationService } from '~/app/shared/services/notification.service';
import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service';
import { PrometheusNotificationService } from '~/app/shared/services/prometheus-notification.service';
import { SummaryService } from '~/app/shared/services/summary.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { NotificationsSidebarComponent } from './notifications-sidebar.component';
describe('NotificationsSidebarComponent', () => {
let component: NotificationsSidebarComponent;
let fixture: ComponentFixture<NotificationsSidebarComponent>;
let prometheusUpdatePermission: string;
let prometheusReadPermission: string;
let prometheusCreatePermission: string;
let configOptReadPermission: string;
configureTestBed({
imports: [
HttpClientTestingModule,
PipesModule,
NgbProgressbarModule,
RouterTestingModule,
ToastrModule.forRoot(),
NoopAnimationsModule,
SimplebarAngularModule,
ClickOutsideModule
],
declarations: [NotificationsSidebarComponent],
providers: [PrometheusService, SettingsService, SummaryService, NotificationService, RbdService]
});
beforeEach(() => {
prometheusReadPermission = 'read';
prometheusUpdatePermission = 'update';
prometheusCreatePermission = 'create';
configOptReadPermission = 'read';
spyOn(TestBed.inject(AuthStorageService), 'getPermissions').and.callFake(
() =>
new Permissions({
prometheus: [
prometheusReadPermission,
prometheusUpdatePermission,
prometheusCreatePermission
],
'config-opt': [configOptReadPermission]
})
);
fixture = TestBed.createComponent(NotificationsSidebarComponent);
component = fixture.componentInstance;
});
it('should create', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
describe('prometheus alert handling', () => {
let prometheusAlertService: PrometheusAlertService;
let prometheusNotificationService: PrometheusNotificationService;
const expectPrometheusServicesToBeCalledTimes = (n: number) => {
expect(prometheusNotificationService.refresh).toHaveBeenCalledTimes(n);
expect(prometheusAlertService.refresh).toHaveBeenCalledTimes(n);
};
beforeEach(() => {
spyOn(TestBed.inject(PrometheusService), 'ifAlertmanagerConfigured').and.callFake((fn) =>
fn()
);
prometheusAlertService = TestBed.inject(PrometheusAlertService);
spyOn(prometheusAlertService, 'refresh').and.stub();
prometheusNotificationService = TestBed.inject(PrometheusNotificationService);
spyOn(prometheusNotificationService, 'refresh').and.stub();
});
it('should not refresh prometheus services if not allowed', () => {
prometheusReadPermission = '';
configOptReadPermission = 'read';
fixture.detectChanges();
expectPrometheusServicesToBeCalledTimes(0);
prometheusReadPermission = 'read';
configOptReadPermission = '';
fixture.detectChanges();
expectPrometheusServicesToBeCalledTimes(0);
});
it('should first refresh prometheus notifications and alerts during init', () => {
fixture.detectChanges();
expect(prometheusAlertService.refresh).toHaveBeenCalledTimes(1);
expectPrometheusServicesToBeCalledTimes(1);
});
it('should refresh prometheus services every 5s', fakeAsync(() => {
fixture.detectChanges();
expectPrometheusServicesToBeCalledTimes(1);
tick(5000);
expectPrometheusServicesToBeCalledTimes(2);
tick(15000);
expectPrometheusServicesToBeCalledTimes(5);
component.ngOnDestroy();
}));
});
describe('Running Tasks', () => {
let summaryService: SummaryService;
beforeEach(() => {
fixture.detectChanges();
summaryService = TestBed.inject(SummaryService);
spyOn(component, '_handleTasks').and.callThrough();
});
it('should handle executing tasks', () => {
const running_tasks = new ExecutingTask('rbd/delete', {
image_spec: 'somePool/someImage'
});
summaryService['summaryDataSource'].next({ executing_tasks: [running_tasks] });
expect(component._handleTasks).toHaveBeenCalled();
expect(component.executingTasks.length).toBe(1);
expect(component.executingTasks[0].description).toBe(`Deleting RBD 'somePool/someImage'`);
});
});
describe('Notifications', () => {
it('should fetch latest notifications', fakeAsync(() => {
const notificationService: NotificationService = TestBed.inject(NotificationService);
fixture.detectChanges();
expect(component.notifications.length).toBe(0);
notificationService.show(NotificationType.success, 'Sample title', 'Sample message');
tick(6000);
expect(component.notifications.length).toBe(1);
expect(component.notifications[0].title).toBe('Sample title');
discardPeriodicTasks();
}));
});
describe('Sidebar', () => {
let notificationService: NotificationService;
beforeEach(() => {
notificationService = TestBed.inject(NotificationService);
fixture.detectChanges();
});
it('should always close if sidebarSubject value is true', fakeAsync(() => {
// Closed before next value
expect(component.isSidebarOpened).toBeFalsy();
notificationService.sidebarSubject.next(true);
tick();
expect(component.isSidebarOpened).toBeFalsy();
// Opened before next value
component.isSidebarOpened = true;
expect(component.isSidebarOpened).toBeTruthy();
notificationService.sidebarSubject.next(true);
tick();
expect(component.isSidebarOpened).toBeFalsy();
}));
it('should toggle sidebar visibility if sidebarSubject value is false', () => {
// Closed before next value
expect(component.isSidebarOpened).toBeFalsy();
notificationService.sidebarSubject.next(false);
expect(component.isSidebarOpened).toBeTruthy();
// Opened before next value
component.isSidebarOpened = true;
expect(component.isSidebarOpened).toBeTruthy();
notificationService.sidebarSubject.next(false);
expect(component.isSidebarOpened).toBeFalsy();
});
});
});
| 7,483
| 34.808612
| 102
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/notifications-sidebar/notifications-sidebar.component.ts
|
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
HostBinding,
NgZone,
OnDestroy,
OnInit
} from '@angular/core';
import { Mutex } from 'async-mutex';
import _ from 'lodash';
import moment from 'moment';
import { Subscription } from 'rxjs';
import { PrometheusService } from '~/app/shared/api/prometheus.service';
import { SucceededActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { Icons } from '~/app/shared/enum/icons.enum';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import {
AlertmanagerSilence,
AlertmanagerSilenceMatcher
} from '~/app/shared/models/alertmanager-silence';
import { CdNotification } from '~/app/shared/models/cd-notification';
import { ExecutingTask } from '~/app/shared/models/executing-task';
import { FinishedTask } from '~/app/shared/models/finished-task';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { NotificationService } from '~/app/shared/services/notification.service';
import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service';
import { PrometheusNotificationService } from '~/app/shared/services/prometheus-notification.service';
import { SummaryService } from '~/app/shared/services/summary.service';
import { TaskMessageService } from '~/app/shared/services/task-message.service';
@Component({
selector: 'cd-notifications-sidebar',
templateUrl: './notifications-sidebar.component.html',
styleUrls: ['./notifications-sidebar.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class NotificationsSidebarComponent implements OnInit, OnDestroy {
@HostBinding('class.active') isSidebarOpened = false;
notifications: CdNotification[];
private interval: number;
private timeout: number;
executingTasks: ExecutingTask[] = [];
private subs = new Subscription();
icons = Icons;
// Tasks
last_task = '';
mutex = new Mutex();
simplebar = {
autoHide: false
};
constructor(
public notificationService: NotificationService,
private summaryService: SummaryService,
private taskMessageService: TaskMessageService,
private prometheusNotificationService: PrometheusNotificationService,
private succeededLabels: SucceededActionLabelsI18n,
private authStorageService: AuthStorageService,
private prometheusAlertService: PrometheusAlertService,
private prometheusService: PrometheusService,
private ngZone: NgZone,
private cdRef: ChangeDetectorRef
) {
this.notifications = [];
}
ngOnDestroy() {
window.clearInterval(this.interval);
window.clearTimeout(this.timeout);
this.subs.unsubscribe();
}
ngOnInit() {
this.last_task = window.localStorage.getItem('last_task');
const permissions = this.authStorageService.getPermissions();
if (permissions.prometheus.read && permissions.configOpt.read) {
this.triggerPrometheusAlerts();
this.ngZone.runOutsideAngular(() => {
this.interval = window.setInterval(() => {
this.ngZone.run(() => {
this.triggerPrometheusAlerts();
});
}, 5000);
});
}
this.subs.add(
this.notificationService.data$.subscribe((notifications: CdNotification[]) => {
this.notifications = _.orderBy(notifications, ['timestamp'], ['desc']);
this.cdRef.detectChanges();
})
);
this.subs.add(
this.notificationService.sidebarSubject.subscribe((forceClose) => {
if (forceClose) {
this.isSidebarOpened = false;
} else {
this.isSidebarOpened = !this.isSidebarOpened;
}
window.clearTimeout(this.timeout);
this.timeout = window.setTimeout(() => {
this.cdRef.detectChanges();
}, 0);
})
);
this.subs.add(
this.summaryService.subscribe((summary) => {
this._handleTasks(summary.executing_tasks);
this.mutex.acquire().then((release) => {
_.filter(
summary.finished_tasks,
(task: FinishedTask) => !this.last_task || moment(task.end_time).isAfter(this.last_task)
).forEach((task) => {
const config = this.notificationService.finishedTaskToNotification(task, task.success);
const notification = new CdNotification(config);
notification.timestamp = task.end_time;
notification.duration = task.duration;
if (!this.last_task || moment(task.end_time).isAfter(this.last_task)) {
this.last_task = task.end_time;
window.localStorage.setItem('last_task', this.last_task);
}
this.notificationService.save(notification);
});
this.cdRef.detectChanges();
release();
});
})
);
}
_handleTasks(executingTasks: ExecutingTask[]) {
for (const excutingTask of executingTasks) {
excutingTask.description = this.taskMessageService.getRunningTitle(excutingTask);
}
this.executingTasks = executingTasks;
}
private triggerPrometheusAlerts() {
this.prometheusAlertService.refresh();
this.prometheusNotificationService.refresh();
}
removeAll() {
this.notificationService.removeAll();
}
remove(index: number) {
this.notificationService.remove(index);
}
closeSidebar() {
this.isSidebarOpened = false;
}
trackByFn(index: number) {
return index;
}
silence(data: CdNotification) {
const datetimeFormat = 'YYYY-MM-DD HH:mm';
const resource = $localize`silence`;
const matcher: AlertmanagerSilenceMatcher = {
name: 'alertname',
value: data['title'].split(' ')[0],
isRegex: false
};
const silencePayload: AlertmanagerSilence = {
matchers: [matcher],
startsAt: moment(moment().format(datetimeFormat)).toISOString(),
endsAt: moment(moment().add(2, 'hours').format(datetimeFormat)).toISOString(),
createdBy: this.authStorageService.getUsername(),
comment: 'Silence created from the alert notification'
};
let msg = '';
data.alertSilenced = true;
msg = msg.concat(` ${matcher.name} - ${matcher.value},`);
const title = `${this.succeededLabels.CREATED} ${resource} for ${msg.slice(0, -1)}`;
this.prometheusService.setSilence(silencePayload).subscribe((resp) => {
if (data) {
data.silenceId = resp.body['silenceId'];
}
this.notificationService.show(
NotificationType.success,
title,
undefined,
undefined,
'Prometheus'
);
});
}
expire(data: CdNotification) {
data.alertSilenced = false;
this.prometheusService.expireSilence(data.silenceId).subscribe(
() => {
this.notificationService.show(
NotificationType.success,
`${this.succeededLabels.EXPIRED} ${data.silenceId}`,
undefined,
undefined,
'Prometheus'
);
},
(resp) => {
resp['application'] = 'Prometheus';
}
);
}
}
| 7,053
| 29.803493
| 102
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/orchestrator-doc-panel/orchestrator-doc-panel.component.html
|
<cd-alert-panel *ngIf="missingFeatures; else elseBlock"
type="info"
i18n>The feature is not supported in the current Orchestrator.</cd-alert-panel>
<ng-template #elseBlock>
<cd-alert-panel type="info"
i18n>Orchestrator is not available.
Please consult the <cd-doc section="orch"></cd-doc> on how to configure and
enable the functionality.</cd-alert-panel>
</ng-template>
| 432
| 38.363636
| 95
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/orchestrator-doc-panel/orchestrator-doc-panel.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { CephReleaseNamePipe } from '~/app/shared/pipes/ceph-release-name.pipe';
import { SummaryService } from '~/app/shared/services/summary.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { ComponentsModule } from '../components.module';
import { OrchestratorDocPanelComponent } from './orchestrator-doc-panel.component';
describe('OrchestratorDocPanelComponent', () => {
let component: OrchestratorDocPanelComponent;
let fixture: ComponentFixture<OrchestratorDocPanelComponent>;
configureTestBed({
imports: [ComponentsModule, HttpClientTestingModule, RouterTestingModule],
providers: [CephReleaseNamePipe, SummaryService]
});
beforeEach(() => {
fixture = TestBed.createComponent(OrchestratorDocPanelComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,130
| 36.7
| 83
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/orchestrator-doc-panel/orchestrator-doc-panel.component.ts
|
import { Component, Input } from '@angular/core';
import { OrchestratorFeature } from '~/app/shared/models/orchestrator.enum';
@Component({
selector: 'cd-orchestrator-doc-panel',
templateUrl: './orchestrator-doc-panel.component.html',
styleUrls: ['./orchestrator-doc-panel.component.scss']
})
export class OrchestratorDocPanelComponent {
@Input()
missingFeatures: OrchestratorFeature[];
}
| 401
| 27.714286
| 76
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/pwd-expiration-notification/pwd-expiration-notification.component.html
|
<cd-alert-panel class="no-margin-bottom"
[type]="alertType"
*ngIf="displayNotification"
[showTitle]="false"
size="slim"
[dismissible]="alertType !== 'danger'"
(dismissed)="onDismissed()">
<div *ngIf="expirationDays === 0"
i18n>Your password will expire in <strong>less than 1</strong> day. Click
<a routerLink="/user-profile/edit"
class="alert-link">here</a> to change it now.</div>
<div *ngIf="expirationDays > 0"
i18n>Your password will expire in <strong>{{ expirationDays }}</strong> day(s). Click
<a routerLink="/user-profile/edit"
class="alert-link">here</a> to change it now.</div>
</cd-alert-panel>
| 738
| 42.470588
| 92
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/pwd-expiration-notification/pwd-expiration-notification.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Routes } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap';
import { of as observableOf } from 'rxjs';
import { SettingsService } from '~/app/shared/api/settings.service';
import { AlertPanelComponent } from '~/app/shared/components/alert-panel/alert-panel.component';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { PwdExpirationNotificationComponent } from './pwd-expiration-notification.component';
describe('PwdExpirationNotificationComponent', () => {
let component: PwdExpirationNotificationComponent;
let fixture: ComponentFixture<PwdExpirationNotificationComponent>;
let settingsService: SettingsService;
let authStorageService: AuthStorageService;
@Component({ selector: 'cd-fake', template: '' })
class FakeComponent {}
const routes: Routes = [{ path: 'login', component: FakeComponent }];
const spyOnDate = (fakeDate: string) => {
const dateValue = Date;
spyOn(global, 'Date').and.callFake((date) => new dateValue(date ? date : fakeDate));
};
configureTestBed({
declarations: [PwdExpirationNotificationComponent, FakeComponent, AlertPanelComponent],
imports: [NgbAlertModule, HttpClientTestingModule, RouterTestingModule.withRoutes(routes)],
providers: [SettingsService, AuthStorageService]
});
describe('password expiration date has been set', () => {
beforeEach(() => {
authStorageService = TestBed.inject(AuthStorageService);
settingsService = TestBed.inject(SettingsService);
spyOn(authStorageService, 'getPwdExpirationDate').and.returnValue(1645488000);
spyOn(settingsService, 'getStandardSettings').and.returnValue(
observableOf({
user_pwd_expiration_warning_1: 10,
user_pwd_expiration_warning_2: 5,
user_pwd_expiration_span: 90
})
);
fixture = TestBed.createComponent(PwdExpirationNotificationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
component.ngOnInit();
expect(component).toBeTruthy();
});
it('should set warning levels', () => {
component.ngOnInit();
expect(component.pwdExpirationSettings.pwdExpirationWarning1).toBe(10);
expect(component.pwdExpirationSettings.pwdExpirationWarning2).toBe(5);
});
it('should calculate password expiration in days', () => {
spyOnDate('2022-02-18T00:00:00.000Z');
component.ngOnInit();
expect(component['expirationDays']).toBe(4);
});
it('should set alert type warning correctly', () => {
spyOnDate('2022-02-14T00:00:00.000Z');
component.ngOnInit();
expect(component['alertType']).toBe('warning');
expect(component.displayNotification).toBeTruthy();
});
it('should set alert type danger correctly', () => {
spyOnDate('2022-02-18T00:00:00.000Z');
component.ngOnInit();
expect(component['alertType']).toBe('danger');
expect(component.displayNotification).toBeTruthy();
});
it('should not display if date is far', () => {
spyOnDate('2022-01-01T00:00:00.000Z');
component.ngOnInit();
expect(component.displayNotification).toBeFalsy();
});
});
describe('password expiration date has not been set', () => {
beforeEach(() => {
authStorageService = TestBed.inject(AuthStorageService);
spyOn(authStorageService, 'getPwdExpirationDate').and.returnValue(null);
fixture = TestBed.createComponent(PwdExpirationNotificationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should calculate no expirationDays', () => {
component.ngOnInit();
expect(component['expirationDays']).toBeUndefined();
});
});
});
| 4,126
| 37.212963
| 96
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/pwd-expiration-notification/pwd-expiration-notification.component.ts
|
import { Component, OnDestroy, OnInit } from '@angular/core';
import { SettingsService } from '~/app/shared/api/settings.service';
import { CdPwdExpirationSettings } from '~/app/shared/models/cd-pwd-expiration-settings';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
@Component({
selector: 'cd-pwd-expiration-notification',
templateUrl: './pwd-expiration-notification.component.html',
styleUrls: ['./pwd-expiration-notification.component.scss']
})
export class PwdExpirationNotificationComponent implements OnInit, OnDestroy {
alertType: string;
expirationDays: number;
pwdExpirationSettings: CdPwdExpirationSettings;
displayNotification = false;
constructor(
private settingsService: SettingsService,
private authStorageService: AuthStorageService
) {}
ngOnInit() {
this.settingsService.getStandardSettings().subscribe((pwdExpirationSettings) => {
this.pwdExpirationSettings = new CdPwdExpirationSettings(pwdExpirationSettings);
const pwdExpirationDate = this.authStorageService.getPwdExpirationDate();
if (pwdExpirationDate) {
this.expirationDays = this.getExpirationDays(pwdExpirationDate);
if (this.expirationDays <= this.pwdExpirationSettings.pwdExpirationWarning2) {
this.alertType = 'danger';
} else {
this.alertType = 'warning';
}
this.displayNotification =
this.expirationDays <= this.pwdExpirationSettings.pwdExpirationWarning1;
this.authStorageService.isPwdDisplayedSource.next(this.displayNotification);
}
});
}
ngOnDestroy() {
this.authStorageService.isPwdDisplayedSource.next(false);
}
private getExpirationDays(pwdExpirationDate: number): number {
const current = new Date();
const expiration = new Date(pwdExpirationDate * 1000);
return Math.floor((expiration.valueOf() - current.valueOf()) / (1000 * 3600 * 24));
}
onDismissed(): void {
this.authStorageService.isPwdDisplayedSource.next(false);
this.displayNotification = false;
}
}
| 2,068
| 35.946429
| 89
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/refresh-selector/refresh-selector.component.html
|
<div class="container-fluid">
<div class="row">
<form>
<div class="col-sm-1 d-flex float-end">
<label for="refreshInterval"
class="col-form-label my-0 mx-2 float-end"
i18n>Refresh</label>
<select id="refreshInterval"
name="refreshInterval"
class="form-select float-end"
(change)="changeRefreshInterval($event.target.value)"
[(ngModel)]="selectedInterval">
<option *ngFor="let key of intervalKeys"
[value]="intervalList[key]">{{ key }}</option>
</select>
</div>
</form>
</div>
</div>
| 653
| 31.7
| 69
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/refresh-selector/refresh-selector.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RefreshIntervalService } from '~/app/shared/services/refresh-interval.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RefreshSelectorComponent } from './refresh-selector.component';
describe('RefreshSelectorComponent', () => {
let component: RefreshSelectorComponent;
let fixture: ComponentFixture<RefreshSelectorComponent>;
configureTestBed({
imports: [FormsModule],
declarations: [RefreshSelectorComponent],
providers: [RefreshIntervalService]
});
beforeEach(() => {
fixture = TestBed.createComponent(RefreshSelectorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 871
| 30.142857
| 88
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/refresh-selector/refresh-selector.component.ts
|
import { Component, OnInit } from '@angular/core';
import { RefreshIntervalService } from '~/app/shared/services/refresh-interval.service';
@Component({
selector: 'cd-refresh-selector',
templateUrl: './refresh-selector.component.html',
styleUrls: ['./refresh-selector.component.scss']
})
export class RefreshSelectorComponent implements OnInit {
selectedInterval: number;
intervalList: { [key: string]: number } = {
'5 s': 5000,
'10 s': 10000,
'15 s': 15000,
'30 s': 30000,
'1 min': 60000,
'3 min': 180000,
'5 min': 300000
};
intervalKeys = Object.keys(this.intervalList);
constructor(private refreshIntervalService: RefreshIntervalService) {}
ngOnInit() {
this.selectedInterval = this.refreshIntervalService.getRefreshInterval() || 5000;
}
changeRefreshInterval(interval: number) {
this.refreshIntervalService.setRefreshInterval(interval);
}
}
| 910
| 26.606061
| 88
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/select-badges/select-badges.component.html
|
<cd-select #cdSelect
[data]="data"
[options]="options"
[messages]="messages"
[selectionLimit]="selectionLimit"
[customBadges]="customBadges"
[customBadgeValidators]="customBadgeValidators"
elemClass="me-2 select-menu-edit"
(selection)="selection.emit($event)">
<i [ngClass]="[icons.edit]"></i>
</cd-select>
<span *ngFor="let dataItem of data">
<span class="badge badge-dark me-2">
<span class="me-2">{{ dataItem }}</span>
<a class="badge-remove"
(click)="cdSelect.removeItem(dataItem)">
<i [ngClass]="[icons.destroy]"
aria-hidden="true"></i>
</a>
</span>
</span>
| 692
| 29.130435
| 58
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/select-badges/select-badges.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { NgbPopoverModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { configureTestBed } from '~/testing/unit-test-helper';
import { SelectMessages } from '../select/select-messages.model';
import { SelectComponent } from '../select/select.component';
import { SelectBadgesComponent } from './select-badges.component';
describe('SelectBadgesComponent', () => {
let component: SelectBadgesComponent;
let fixture: ComponentFixture<SelectBadgesComponent>;
configureTestBed({
declarations: [SelectBadgesComponent, SelectComponent],
imports: [NgbPopoverModule, NgbTooltipModule, ReactiveFormsModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(SelectBadgesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should reflect the attributes into CdSelect', () => {
const data = ['a', 'b'];
const options = [
{ name: 'option1', description: '', selected: false, enabled: true },
{ name: 'option2', description: '', selected: false, enabled: true }
];
const messages = new SelectMessages({ empty: 'foo bar' });
const selectionLimit = 2;
const customBadges = true;
const customBadgeValidators = [Validators.required];
component.data = data;
component.options = options;
component.messages = messages;
component.selectionLimit = selectionLimit;
component.customBadges = customBadges;
component.customBadgeValidators = customBadgeValidators;
fixture.detectChanges();
expect(component.cdSelect.data).toEqual(data);
expect(component.cdSelect.options).toEqual(options);
expect(component.cdSelect.messages).toEqual(messages);
expect(component.cdSelect.selectionLimit).toEqual(selectionLimit);
expect(component.cdSelect.customBadges).toEqual(customBadges);
expect(component.cdSelect.customBadgeValidators).toEqual(customBadgeValidators);
});
});
| 2,136
| 35.844828
| 84
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/select-badges/select-badges.component.ts
|
import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ValidatorFn } from '@angular/forms';
import { Icons } from '~/app/shared/enum/icons.enum';
import { SelectMessages } from '../select/select-messages.model';
import { SelectOption } from '../select/select-option.model';
import { SelectComponent } from '../select/select.component';
@Component({
selector: 'cd-select-badges',
templateUrl: './select-badges.component.html',
styleUrls: ['./select-badges.component.scss']
})
export class SelectBadgesComponent {
@Input()
data: Array<string> = [];
@Input()
options: Array<SelectOption> = [];
@Input()
messages = new SelectMessages({});
@Input()
selectionLimit: number;
@Input()
customBadges = false;
@Input()
customBadgeValidators: ValidatorFn[] = [];
@Output()
selection = new EventEmitter();
@ViewChild('cdSelect', { static: true })
cdSelect: SelectComponent;
icons = Icons;
}
| 960
| 25.694444
| 82
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/select/select-messages.model.ts
|
import _ from 'lodash';
export class SelectMessages {
empty: string;
selectionLimit: any;
customValidations = {};
filter: string;
add: string;
noOptions: string;
constructor(messages: {}) {
this.empty = $localize`No items selected.`;
this.selectionLimit = {
tooltip: $localize`Deselect item to select again`,
text: $localize`Selection limit reached`
};
this.filter = $localize`Filter tags`;
this.add = $localize`Add badge`; // followed by " '{{filter.value}}'"
this.noOptions = $localize`There are no items available.`;
_.merge(this, messages);
}
}
| 608
| 24.375
| 73
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/select/select-option.model.ts
|
export class SelectOption {
selected: boolean;
name: string;
description: string;
enabled: boolean;
constructor(selected: boolean, name: string, description: string, enabled = true) {
this.selected = selected;
this.name = name;
this.description = description;
this.enabled = enabled;
}
}
| 317
| 21.714286
| 85
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/select/select.component.html
|
<ng-template #popTemplate>
<form name="form"
#formDir="ngForm"
[formGroup]="form"
novalidate>
<div>
<input type="text"
formControlName="filter"
i18n-placeholder
[placeholder]="messages.filter"
(keyup)="$event.keyCode === 13 ? selectOption() : updateFilter()"
class="form-control text-center" />
<ng-container *ngFor="let error of Object.keys(messages.customValidations)">
<span class="invalid-feedback text-center d-block"
*ngIf="form.showError('filter', formDir) && filter.hasError(error)">
{{ messages.customValidations[error] }}
</span>
</ng-container>
</div>
</form>
<div *ngFor="let option of filteredOptions"
class="select-menu-item"
[ngClass]="{'help-block disabled': (data.length === selectionLimit || !option.enabled) && !option.selected}"
(click)="triggerSelection(option)">
<div class="select-menu-item-icon">
<i [ngClass]="[icons.check]"
aria-hidden="true"
*ngIf="option.selected"></i>
</div>
<div class="select-menu-item-content">
{{ option.name }}
<ng-container *ngIf="option.description">
<br>
<small class="form-text text-muted">
{{ option.description }}
</small>
</ng-container>
</div>
</div>
<div *ngIf="isCreatable()"
class="select-menu-item"
(click)="addCustomOption()">
<div class="select-menu-item-icon">
<i [ngClass]="[icons.tag]"
aria-hidden="true"></i>
</div>
<div class="select-menu-item-content">
{{ messages.add }} '{{ filter.value }}'
</div>
</div>
<div class="is-invalid"
*ngIf="data.length === selectionLimit">
<span class="form-text text-muted text-center text-warning"
[ngbTooltip]="messages.selectionLimit.tooltip"
*ngIf="data.length === selectionLimit">
{{ messages.selectionLimit.text }}
</span>
</div>
</ng-template>
<a class="select-menu-edit float-start"
[ngClass]="elemClass"
[ngbPopover]="popTemplate"
data-testid="select-menu-edit"
*ngIf="customBadges || options.length > 0">
<ng-content></ng-content>
</a>
<span class="form-text text-muted float-start"
*ngIf="data.length === 0 && !(!customBadges && options.length === 0)">
{{ messages.empty }}
</span>
<span class="form-text text-muted float-start"
*ngIf="!customBadges && options.length === 0">
{{ messages.noOptions }}
</span>
| 2,565
| 31.075
| 115
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/select/select.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { NgbPopoverModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { configureTestBed } from '~/testing/unit-test-helper';
import { SelectOption } from './select-option.model';
import { SelectComponent } from './select.component';
describe('SelectComponent', () => {
let component: SelectComponent;
let fixture: ComponentFixture<SelectComponent>;
const selectOption = (filter: string) => {
component.filter.setValue(filter);
component.updateFilter();
component.selectOption();
};
configureTestBed({
declarations: [SelectComponent],
imports: [NgbPopoverModule, NgbTooltipModule, ReactiveFormsModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(SelectComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.options = [
{ name: 'option1', description: '', selected: false, enabled: true },
{ name: 'option2', description: '', selected: false, enabled: true },
{ name: 'option3', description: '', selected: false, enabled: true }
];
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should add item', () => {
component.data = [];
component.triggerSelection(component.options[1]);
expect(component.data).toEqual(['option2']);
});
it('should update selected', () => {
component.data = ['option2'];
component.ngOnChanges();
expect(component.options[0].selected).toBe(false);
expect(component.options[1].selected).toBe(true);
});
it('should remove item', () => {
component.options.map((option) => {
option.selected = true;
return option;
});
component.data = ['option1', 'option2', 'option3'];
component.removeItem('option1');
expect(component.data).toEqual(['option2', 'option3']);
});
it('should not remove item that is not selected', () => {
component.options[0].selected = true;
component.data = ['option1'];
component.removeItem('option2');
expect(component.data).toEqual(['option1']);
});
describe('filter values', () => {
beforeEach(() => {
component.ngOnInit();
});
it('shows all options with no value set', () => {
expect(component.filteredOptions).toEqual(component.options);
});
it('shows one option that it filtered for', () => {
component.filter.setValue('2');
component.updateFilter();
expect(component.filteredOptions).toEqual([component.options[1]]);
});
it('shows all options after selecting something', () => {
component.filter.setValue('2');
component.updateFilter();
component.selectOption();
expect(component.filteredOptions).toEqual(component.options);
});
it('is not able to create by default with no value set', () => {
component.updateFilter();
expect(component.isCreatable()).toBeFalsy();
});
it('is not able to create by default with a value set', () => {
component.filter.setValue('2');
component.updateFilter();
expect(component.isCreatable()).toBeFalsy();
});
});
describe('automatically add selected options if not in options array', () => {
beforeEach(() => {
component.data = ['option1', 'option4'];
expect(component.options.length).toBe(3);
});
const expectedResult = () => {
expect(component.options.length).toBe(4);
expect(component.options[3]).toEqual(new SelectOption(true, 'option4', ''));
};
it('with no extra settings', () => {
component.ngOnInit();
expectedResult();
});
it('with custom badges', () => {
component.customBadges = true;
component.ngOnInit();
expectedResult();
});
it('with limit higher than selected', () => {
component.selectionLimit = 3;
component.ngOnInit();
expectedResult();
});
it('with limit equal to selected', () => {
component.selectionLimit = 2;
component.ngOnInit();
expectedResult();
});
it('with limit lower than selected', () => {
component.selectionLimit = 1;
component.ngOnInit();
expectedResult();
});
});
describe('sorted array and options', () => {
beforeEach(() => {
component.customBadges = true;
component.customBadgeValidators = [Validators.pattern('[A-Za-z0-9_]+')];
component.data = ['c', 'b'];
component.options = [new SelectOption(true, 'd', ''), new SelectOption(true, 'a', '')];
component.ngOnInit();
});
it('has a sorted selection', () => {
expect(component.data).toEqual(['a', 'b', 'c', 'd']);
});
it('has a sorted options', () => {
const sortedOptions = [
new SelectOption(true, 'a', ''),
new SelectOption(true, 'b', ''),
new SelectOption(true, 'c', ''),
new SelectOption(true, 'd', '')
];
expect(component.options).toEqual(sortedOptions);
});
it('has a sorted selection after adding an item', () => {
selectOption('block');
expect(component.data).toEqual(['a', 'b', 'block', 'c', 'd']);
});
it('has a sorted options after adding an item', () => {
selectOption('block');
const sortedOptions = [
new SelectOption(true, 'a', ''),
new SelectOption(true, 'b', ''),
new SelectOption(true, 'block', ''),
new SelectOption(true, 'c', ''),
new SelectOption(true, 'd', '')
];
expect(component.options).toEqual(sortedOptions);
});
});
describe('with custom options', () => {
beforeEach(() => {
component.customBadges = true;
component.customBadgeValidators = [Validators.pattern('[A-Za-z0-9_]+')];
component.ngOnInit();
});
it('is not able to create with no value set', () => {
component.updateFilter();
expect(component.isCreatable()).toBeFalsy();
});
it('is able to create with a valid value set', () => {
component.filter.setValue('2');
component.updateFilter();
expect(component.isCreatable()).toBeTruthy();
});
it('is not able to create with a value set that already exist', () => {
component.filter.setValue('option2');
component.updateFilter();
expect(component.isCreatable()).toBeFalsy();
});
it('adds custom option', () => {
selectOption('customOption');
expect(component.options[0]).toEqual({
name: 'customOption',
description: '',
selected: true,
enabled: true
});
expect(component.options.length).toBe(4);
expect(component.data).toEqual(['customOption']);
});
it('will not add an option that did not pass the validation', () => {
selectOption(' this does not pass ');
expect(component.options.length).toBe(3);
expect(component.data).toEqual([]);
expect(component.filter.invalid).toBeTruthy();
});
it('removes custom item selection by name', () => {
selectOption('customOption');
component.removeItem('customOption');
expect(component.data).toEqual([]);
expect(component.options.length).toBe(4);
expect(component.options[0]).toEqual({
name: 'customOption',
description: '',
selected: false,
enabled: true
});
});
it('will not add an option that is already there', () => {
selectOption('option2');
expect(component.options.length).toBe(3);
expect(component.data).toEqual(['option2']);
});
it('will not add an option twice after each other', () => {
selectOption('onlyOnce');
expect(component.data).toEqual(['onlyOnce']);
selectOption('onlyOnce');
expect(component.data).toEqual([]);
selectOption('onlyOnce');
expect(component.data).toEqual(['onlyOnce']);
expect(component.options.length).toBe(4);
});
});
describe('if the selection limit is reached', function () {
beforeEach(() => {
component.selectionLimit = 2;
component.triggerSelection(component.options[0]);
component.triggerSelection(component.options[1]);
});
it('will not select more options', () => {
component.triggerSelection(component.options[2]);
expect(component.data).toEqual(['option1', 'option2']);
});
it('will unselect options that are selected', () => {
component.triggerSelection(component.options[1]);
expect(component.data).toEqual(['option1']);
});
});
});
| 8,583
| 29.98917
| 93
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/select/select.component.ts
|
import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
import { FormControl, ValidatorFn } from '@angular/forms';
import _ from 'lodash';
import { Icons } from '~/app/shared/enum/icons.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { SelectMessages } from './select-messages.model';
import { SelectOption } from './select-option.model';
@Component({
selector: 'cd-select',
templateUrl: './select.component.html',
styleUrls: ['./select.component.scss']
})
export class SelectComponent implements OnInit, OnChanges {
@Input()
elemClass: string;
@Input()
data: Array<string> = [];
@Input()
options: Array<SelectOption> = [];
@Input()
messages = new SelectMessages({});
@Input()
selectionLimit: number;
@Input()
customBadges = false;
@Input()
customBadgeValidators: ValidatorFn[] = [];
@Output()
selection = new EventEmitter();
form: CdFormGroup;
filter: FormControl;
Object = Object;
filteredOptions: Array<SelectOption> = [];
icons = Icons;
ngOnInit() {
this.initFilter();
if (this.data.length > 0) {
this.initMissingOptions();
}
this.options = _.sortBy(this.options, ['name']);
this.updateOptions();
}
private initFilter() {
this.filter = new FormControl('', { validators: this.customBadgeValidators });
this.form = new CdFormGroup({ filter: this.filter });
this.filteredOptions = [...(this.options || [])];
}
private initMissingOptions() {
const options = this.options.map((option) => option.name);
const needToCreate = this.data.filter((option) => options.indexOf(option) === -1);
needToCreate.forEach((option) => this.addOption(option));
this.forceOptionsToReflectData();
}
private addOption(name: string) {
this.options.push(new SelectOption(false, name, ''));
this.options = _.sortBy(this.options, ['name']);
this.triggerSelection(this.options.find((option) => option.name === name));
}
triggerSelection(option: SelectOption) {
if (
!option ||
(this.selectionLimit && !option.selected && this.data.length >= this.selectionLimit)
) {
return;
}
option.selected = !option.selected;
this.updateOptions();
this.selection.emit({ option: option });
}
private updateOptions() {
this.data.splice(0, this.data.length);
this.options.forEach((option: SelectOption) => {
if (option.selected) {
this.data.push(option.name);
}
});
this.updateFilter();
}
updateFilter() {
this.filteredOptions = this.options.filter((option) => option.name.includes(this.filter.value));
}
private forceOptionsToReflectData() {
this.options.forEach((option) => {
if (this.data.indexOf(option.name) !== -1) {
option.selected = true;
}
});
}
ngOnChanges() {
if (this.filter) {
this.updateFilter();
}
if (!this.options || !this.data || this.data.length === 0) {
return;
}
this.forceOptionsToReflectData();
}
selectOption() {
if (this.filteredOptions.length === 0) {
this.addCustomOption();
} else {
this.triggerSelection(this.filteredOptions[0]);
this.resetFilter();
}
}
addCustomOption() {
if (!this.isCreatable()) {
return;
}
this.addOption(this.filter.value);
this.resetFilter();
}
isCreatable() {
return (
this.customBadges &&
this.filter.valid &&
this.filter.value.length > 0 &&
this.filteredOptions.every((option) => option.name !== this.filter.value)
);
}
private resetFilter() {
this.filter.setValue('');
this.updateFilter();
}
removeItem(item: string) {
this.triggerSelection(
this.options.find((option: SelectOption) => option.name === item && option.selected)
);
}
}
| 3,848
| 24.66
| 100
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/sparkline/sparkline.component.html
|
<div class="chart-container"
[ngStyle]="style">
<canvas baseChart
#sparkCanvas
[labels]="labels"
[datasets]="datasets"
[options]="options"
[colors]="colors"
[chartType]="'line'">
</canvas>
<div class="chartjs-tooltip"
#sparkTooltip>
<table></table>
</div>
</div>
| 347
| 20.75
| 31
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/sparkline/sparkline.component.spec.ts
|
import { NO_ERRORS_SCHEMA, SimpleChange } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe';
import { FormatterService } from '~/app/shared/services/formatter.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { SparklineComponent } from './sparkline.component';
describe('SparklineComponent', () => {
let component: SparklineComponent;
let fixture: ComponentFixture<SparklineComponent>;
configureTestBed({
declarations: [SparklineComponent],
schemas: [NO_ERRORS_SCHEMA],
providers: [DimlessBinaryPipe, FormatterService]
});
beforeEach(() => {
fixture = TestBed.createComponent(SparklineComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
expect(component.options.tooltips.custom).toBeDefined();
});
it('should update', () => {
expect(component.datasets).toEqual([{ data: [] }]);
expect(component.labels.length).toBe(0);
component.data = [11, 22, 33];
component.ngOnChanges({ data: new SimpleChange(null, component.data, false) });
expect(component.datasets).toEqual([{ data: [11, 22, 33] }]);
expect(component.labels.length).toBe(3);
});
it('should not transform the label, if not isBinary', () => {
component.isBinary = false;
const result = component.options.tooltips.callbacks.label({ yLabel: 1024 });
expect(result).toBe(1024);
});
it('should transform the label, if isBinary', () => {
component.isBinary = true;
const result = component.options.tooltips.callbacks.label({ yLabel: 1024 });
expect(result).toBe('1 KiB');
});
});
| 1,782
| 32.641509
| 83
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/sparkline/sparkline.component.ts
|
import {
Component,
ElementRef,
Input,
OnChanges,
OnInit,
SimpleChanges,
ViewChild
} from '@angular/core';
import { ChartTooltip } from '~/app/shared/models/chart-tooltip';
import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe';
@Component({
selector: 'cd-sparkline',
templateUrl: './sparkline.component.html',
styleUrls: ['./sparkline.component.scss']
})
export class SparklineComponent implements OnInit, OnChanges {
@ViewChild('sparkCanvas', { static: true })
chartCanvasRef: ElementRef;
@ViewChild('sparkTooltip', { static: true })
chartTooltipRef: ElementRef;
@Input()
data: any;
@Input()
style = {
height: '30px',
width: '100px'
};
@Input()
isBinary: boolean;
public colors: Array<any> = [
{
backgroundColor: 'rgba(40,140,234,0.2)',
borderColor: 'rgba(40,140,234,1)',
pointBackgroundColor: 'rgba(40,140,234,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(40,140,234,0.8)'
}
];
options: Record<string, any> = {
animation: {
duration: 0
},
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
elements: {
line: {
borderWidth: 1
}
},
tooltips: {
enabled: false,
mode: 'index',
intersect: false,
custom: undefined,
callbacks: {
label: (tooltipItem: any) => {
if (this.isBinary) {
return this.dimlessBinaryPipe.transform(tooltipItem.yLabel);
} else {
return tooltipItem.yLabel;
}
},
title: () => ''
}
},
scales: {
yAxes: [
{
display: false
}
],
xAxes: [
{
display: false
}
]
}
};
public datasets: Array<any> = [
{
data: []
}
];
public labels: Array<any> = [];
constructor(private dimlessBinaryPipe: DimlessBinaryPipe) {}
ngOnInit() {
const getStyleTop = (tooltip: any) => {
return tooltip.caretY - tooltip.height - tooltip.yPadding - 5 + 'px';
};
const getStyleLeft = (tooltip: any, positionX: number) => {
return positionX + tooltip.caretX + 'px';
};
const chartTooltip = new ChartTooltip(
this.chartCanvasRef,
this.chartTooltipRef,
getStyleLeft,
getStyleTop
);
chartTooltip.customColors = {
backgroundColor: this.colors[0].pointBackgroundColor,
borderColor: this.colors[0].pointBorderColor
};
this.options.tooltips.custom = (tooltip: any) => {
chartTooltip.customTooltips(tooltip);
};
}
ngOnChanges(changes: SimpleChanges) {
this.datasets[0].data = changes['data'].currentValue;
this.labels = [...Array(changes['data'].currentValue.length)];
}
}
| 2,855
| 20.801527
| 75
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/submit-button/submit-button.component.html
|
<button [type]="type"
class="btn btn-accent tc_submitButton"
[ngClass]="btnClass"
[disabled]="loading || disabled"
(click)="submit($event)"
[attr.aria-label]="ariaLabel">
<ng-content></ng-content>
<span *ngIf="loading">
<i [ngClass]="[icons.spinner, icons.spin]"></i>
</span>
</button>
| 336
| 27.083333
| 51
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/submit-button/submit-button.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormGroup } from '@angular/forms';
import { configureTestBed } from '~/testing/unit-test-helper';
import { SubmitButtonComponent } from './submit-button.component';
describe('SubmitButtonComponent', () => {
let component: SubmitButtonComponent;
let fixture: ComponentFixture<SubmitButtonComponent>;
configureTestBed({
declarations: [SubmitButtonComponent]
});
beforeEach(() => {
fixture = TestBed.createComponent(SubmitButtonComponent);
component = fixture.componentInstance;
component.form = new FormGroup({}, {});
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 736
| 25.321429
| 66
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/submit-button/submit-button.component.ts
|
import { Component, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, FormGroup, FormGroupDirective, NgForm } from '@angular/forms';
import _ from 'lodash';
import { Icons } from '~/app/shared/enum/icons.enum';
/**
* This component will render a submit button with the given label.
*
* The button will disabled itself and show a loading icon when the user clicks
* it, usually initiating a request to the server, and it will stay in that
* state until the request is finished.
*
* To indicate that the request failed, returning the button to the enable
* state, you need to insert an error in the form with the 'cdSubmitButton' key.
* p.e.: this.rbdForm.setErrors({'cdSubmitButton': true});
*
* It will also check if the form is valid, when clicking the button, and will
* focus on the first invalid input.
*
* @export
* @class SubmitButtonComponent
* @implements {OnInit}
*/
@Component({
selector: 'cd-submit-button',
templateUrl: './submit-button.component.html',
styleUrls: ['./submit-button.component.scss']
})
export class SubmitButtonComponent implements OnInit {
@Input()
form: FormGroup | NgForm;
@Input()
type = 'submit';
@Input()
disabled = false;
// A CSS class string to apply to the button's main element.
@Input()
btnClass: string;
@Input()
ariaLabel: string;
@Output()
submitAction = new EventEmitter();
loading = false;
icons = Icons;
constructor(private elRef: ElementRef) {}
ngOnInit() {
this.form?.statusChanges.subscribe(() => {
if (_.has(this.form.errors, 'cdSubmitButton')) {
this.loading = false;
_.unset(this.form.errors, 'cdSubmitButton');
// Handle Reactive forms.
if (this.form instanceof AbstractControl) {
(<AbstractControl>this.form).updateValueAndValidity();
}
}
});
}
submit($event: any) {
this.focusButton();
// Special handling for Template driven forms.
if (this.form instanceof FormGroupDirective) {
(<FormGroupDirective>this.form).onSubmit($event);
}
if (this.form?.invalid) {
this.focusInvalid();
return;
}
this.loading = true;
this.submitAction.emit();
}
focusButton() {
this.elRef.nativeElement.offsetParent.querySelector(`button[type="${this.type}"]`).focus();
}
focusInvalid() {
const target = this.elRef.nativeElement.offsetParent.querySelector(
'input.ng-invalid, select.ng-invalid'
);
if (target) {
target.focus();
}
}
}
| 2,555
| 24.56
| 95
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/telemetry-notification/telemetry-notification.component.html
|
<cd-alert-panel *ngIf="displayNotification"
class="no-margin-bottom"
[showTitle]="false"
size="slim"
[type]="notificationSeverity"
[dismissible]="notificationSeverity !== 'danger'"
(dismissed)="onDismissed()">
<div i18n>The Ceph community needs your help to continue improving: please
<a routerLink="/telemetry"
class="btn activate-button alert-link activate-text">Activate</a> the
<a href="https://docs.ceph.com/en/latest/mgr/telemetry/">Telemetry</a> module.</div>
</cd-alert-panel>
| 596
| 44.923077
| 86
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/telemetry-notification/telemetry-notification.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { of } from 'rxjs';
import { MgrModuleService } from '~/app/shared/api/mgr-module.service';
import { UserService } from '~/app/shared/api/user.service';
import { AlertPanelComponent } from '~/app/shared/components/alert-panel/alert-panel.component';
import { Permissions } from '~/app/shared/models/permissions';
import { PipesModule } from '~/app/shared/pipes/pipes.module';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { NotificationService } from '~/app/shared/services/notification.service';
import { TelemetryNotificationService } from '~/app/shared/services/telemetry-notification.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { TelemetryNotificationComponent } from './telemetry-notification.component';
describe('TelemetryActivationNotificationComponent', () => {
let component: TelemetryNotificationComponent;
let fixture: ComponentFixture<TelemetryNotificationComponent>;
let authStorageService: AuthStorageService;
let mgrModuleService: MgrModuleService;
let notificationService: NotificationService;
let isNotificationHiddenSpy: jasmine.Spy;
let getPermissionsSpy: jasmine.Spy;
let getConfigSpy: jasmine.Spy;
const configOptPermissions: Permissions = new Permissions({
'config-opt': ['read', 'create', 'update', 'delete']
});
const noConfigOptPermissions: Permissions = new Permissions({});
const telemetryEnabledConfig = {
enabled: true
};
const telemetryDisabledConfig = {
enabled: false
};
configureTestBed({
declarations: [TelemetryNotificationComponent, AlertPanelComponent],
imports: [NgbAlertModule, HttpClientTestingModule, ToastrModule.forRoot(), PipesModule],
providers: [MgrModuleService, UserService]
});
beforeEach(() => {
fixture = TestBed.createComponent(TelemetryNotificationComponent);
component = fixture.componentInstance;
authStorageService = TestBed.inject(AuthStorageService);
mgrModuleService = TestBed.inject(MgrModuleService);
notificationService = TestBed.inject(NotificationService);
isNotificationHiddenSpy = spyOn(component, 'isNotificationHidden').and.returnValue(false);
getPermissionsSpy = spyOn(authStorageService, 'getPermissions').and.returnValue(
configOptPermissions
);
getConfigSpy = spyOn(mgrModuleService, 'getConfig').and.returnValue(
of(telemetryDisabledConfig)
);
});
it('should create', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should not show notification again if the user closed it before', () => {
isNotificationHiddenSpy.and.returnValue(true);
fixture.detectChanges();
expect(component.displayNotification).toBe(false);
});
it('should not show notification for a user without configOpt permissions', () => {
getPermissionsSpy.and.returnValue(noConfigOptPermissions);
fixture.detectChanges();
expect(component.displayNotification).toBe(false);
});
it('should not show notification if the module is enabled already', () => {
getConfigSpy.and.returnValue(of(telemetryEnabledConfig));
fixture.detectChanges();
expect(component.displayNotification).toBe(false);
});
it('should show the notification if all pre-conditions set accordingly', () => {
fixture.detectChanges();
expect(component.displayNotification).toBe(true);
});
it('should hide the notification if the user closes it', () => {
spyOn(notificationService, 'show');
fixture.detectChanges();
component.onDismissed();
expect(notificationService.show).toHaveBeenCalled();
expect(localStorage.getItem('telemetry_notification_hidden')).toBe('true');
});
it('should hide the notification if the user logs out', () => {
const telemetryNotificationService = TestBed.inject(TelemetryNotificationService);
spyOn(telemetryNotificationService, 'setVisibility');
fixture.detectChanges();
component.ngOnDestroy();
expect(telemetryNotificationService.setVisibility).toHaveBeenCalledWith(false);
});
});
| 4,314
| 38.953704
| 100
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/telemetry-notification/telemetry-notification.component.ts
|
import { Component, OnDestroy, OnInit } from '@angular/core';
import _ from 'lodash';
import { MgrModuleService } from '~/app/shared/api/mgr-module.service';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { NotificationService } from '~/app/shared/services/notification.service';
import { TelemetryNotificationService } from '~/app/shared/services/telemetry-notification.service';
@Component({
selector: 'cd-telemetry-notification',
templateUrl: './telemetry-notification.component.html',
styleUrls: ['./telemetry-notification.component.scss']
})
export class TelemetryNotificationComponent implements OnInit, OnDestroy {
displayNotification = false;
notificationSeverity = 'warning';
constructor(
private mgrModuleService: MgrModuleService,
private authStorageService: AuthStorageService,
private notificationService: NotificationService,
private telemetryNotificationService: TelemetryNotificationService
) {}
ngOnInit() {
this.telemetryNotificationService.update.subscribe((visible: boolean) => {
this.displayNotification = visible;
});
if (!this.isNotificationHidden()) {
const configOptPermissions = this.authStorageService.getPermissions().configOpt;
if (_.every(Object.values(configOptPermissions))) {
this.mgrModuleService.getConfig('telemetry').subscribe((options) => {
if (!options['enabled']) {
this.telemetryNotificationService.setVisibility(true);
}
});
}
}
}
ngOnDestroy() {
this.telemetryNotificationService.setVisibility(false);
}
isNotificationHidden(): boolean {
return localStorage.getItem('telemetry_notification_hidden') === 'true';
}
onDismissed(): void {
this.telemetryNotificationService.setVisibility(false);
localStorage.setItem('telemetry_notification_hidden', 'true');
this.notificationService.show(
NotificationType.success,
$localize`Telemetry activation reminder muted`,
$localize`You can activate the module on the Telemetry configuration \
page (<b>Dashboard Settings</b> -> <b>Telemetry configuration</b>) at any time.`
);
}
}
| 2,264
| 34.952381
| 100
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/usage-bar/usage-bar.component.html
|
<ng-template #usageTooltipTpl>
<table>
<tr>
<td class="text-left">Used: </td>
<td class="text-right"><strong> {{ isBinary ? (used | dimlessBinary) : (used | dimless) }}</strong></td>
</tr>
<tr *ngIf="calculatePerc">
<td class="text-left">Free: </td>
<td class="'text-right"><strong>{{ isBinary ? (total - used | dimlessBinary) : (total - used | dimless) }}</strong></td>
</tr>
</table>
</ng-template>
<div class="progress"
data-placement="left"
[ngbTooltip]="usageTooltipTpl">
<div class="progress-bar bg-info"
[ngClass]="{'bg-warning': usedPercentage/100 >= warningThreshold, 'bg-danger': usedPercentage/100 >= errorThreshold}"
role="progressbar"
[attr.aria-label]="{ title }"
i18n-aria-label="The title of this usage bar is { title }"
[style.width]="usedPercentage + '%'">
<span>{{ usedPercentage | number: '1.0-' + decimals }}%</span>
</div>
<div class="progress-bar bg-freespace"
role="progressbar"
[attr.aria-label]="{ title }"
i18n-aria-label="The title of this usage bar is { title }"
[style.width]="freePercentage + '%'">
</div>
</div>
| 1,184
| 36.03125
| 126
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/usage-bar/usage-bar.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { PipesModule } from '~/app/shared/pipes/pipes.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { UsageBarComponent } from './usage-bar.component';
describe('UsageBarComponent', () => {
let component: UsageBarComponent;
let fixture: ComponentFixture<UsageBarComponent>;
configureTestBed({
imports: [PipesModule, NgbTooltipModule],
declarations: [UsageBarComponent]
});
beforeEach(() => {
fixture = TestBed.createComponent(UsageBarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 791
| 27.285714
| 66
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/usage-bar/usage-bar.component.ts
|
import { Component, Input, OnChanges } from '@angular/core';
import _ from 'lodash';
@Component({
selector: 'cd-usage-bar',
templateUrl: './usage-bar.component.html',
styleUrls: ['./usage-bar.component.scss']
})
export class UsageBarComponent implements OnChanges {
@Input()
total: number;
@Input()
used: any;
@Input()
warningThreshold: number;
@Input()
errorThreshold: number;
@Input()
isBinary = true;
@Input()
decimals = 0;
@Input()
calculatePerc = true;
@Input()
title = $localize`usage`;
usedPercentage: number;
freePercentage: number;
ngOnChanges() {
if (this.calculatePerc) {
this.usedPercentage = this.total > 0 ? (this.used / this.total) * 100 : 0;
this.freePercentage = 100 - this.usedPercentage;
} else {
if (this.used) {
this.used = this.used.slice(0, -1);
this.usedPercentage = Number(this.used);
this.freePercentage = 100 - this.usedPercentage;
} else {
this.usedPercentage = 0;
}
}
}
}
| 1,025
| 21.304348
| 80
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/wizard/wizard.component.html
|
<div class="card-body">
<div class="row m-7">
<nav class="col">
<ul class="nav nav-pills flex-column"
*ngFor="let step of steps | async; let i = index;">
<li class="nav-item">
<a class="nav-link"
(click)="onStepClick(step)"
[ngClass]="{active: currentStep.stepIndex === step.stepIndex}">
<span class="circle-step"
[ngClass]="{active: currentStep.stepIndex === step.stepIndex}"
i18n>{{ step.stepIndex }}</span>
<span i18n>{{ stepsTitle[i] }}</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
| 642
| 31.15
| 80
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/wizard/wizard.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { WizardComponent } from './wizard.component';
describe('WizardComponent', () => {
let component: WizardComponent;
let fixture: ComponentFixture<WizardComponent>;
configureTestBed({
imports: [SharedModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(WizardComponent);
component = fixture.componentInstance;
component.stepsTitle = ['Add Hosts', 'Review'];
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 706
| 26.192308
| 66
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/wizard/wizard.component.ts
|
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import * as _ from 'lodash';
import { Observable, Subscription } from 'rxjs';
import { WizardStepModel } from '~/app/shared/models/wizard-steps';
import { WizardStepsService } from '~/app/shared/services/wizard-steps.service';
@Component({
selector: 'cd-wizard',
templateUrl: './wizard.component.html',
styleUrls: ['./wizard.component.scss']
})
export class WizardComponent implements OnInit, OnDestroy {
@Input()
stepsTitle: string[];
steps: Observable<WizardStepModel[]>;
currentStep: WizardStepModel;
currentStepSub: Subscription;
constructor(private stepsService: WizardStepsService) {}
ngOnInit(): void {
this.stepsService.setTotalSteps(this.stepsTitle.length);
this.steps = this.stepsService.getSteps();
this.currentStepSub = this.stepsService.getCurrentStep().subscribe((step: WizardStepModel) => {
this.currentStep = step;
});
}
onStepClick(step: WizardStepModel) {
this.stepsService.setCurrentStep(step);
}
ngOnDestroy(): void {
this.currentStepSub.unsubscribe();
}
}
| 1,114
| 26.875
| 99
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/constants/app.constants.ts
|
import { Injectable } from '@angular/core';
import { environment } from '~/environments/environment';
export class AppConstants {
public static readonly organization = 'ceph';
public static readonly projectName = 'Ceph Dashboard';
public static readonly license = 'Free software (LGPL 2.1).';
public static readonly copyright = 'Copyright(c) ' + environment.year + ' Ceph contributors.';
public static readonly cephLogo = 'assets/Ceph_Logo.svg';
}
export enum URLVerbs {
/* Create a new item */
CREATE = 'create',
/* Make changes to an existing item */
EDIT = 'edit',
/* Make changes to an existing item */
UPDATE = 'update',
/* Remove an item from a container WITHOUT deleting it */
REMOVE = 'remove',
/* Destroy an existing item */
DELETE = 'delete',
/* Add an existing item to a container */
ADD = 'add',
/* Non-standard verbs */
COPY = 'copy',
CLONE = 'clone',
/* Prometheus wording */
RECREATE = 'recreate',
EXPIRE = 'expire',
/* Daemons */
RESTART = 'Restart'
}
export enum ActionLabels {
/* Create a new item */
CREATE = 'Create',
/* Destroy an existing item */
DELETE = 'Delete',
/* Add an existing item to a container */
ADD = 'Add',
/* Remove an item from a container WITHOUT deleting it */
REMOVE = 'Remove',
/* Make changes to an existing item */
EDIT = 'Edit',
/* */
CANCEL = 'Cancel',
/* Non-standard actions */
COPY = 'Copy',
CLONE = 'Clone',
UPDATE = 'Update',
EVICT = 'Evict',
/* Read-only */
SHOW = 'Show',
/* Prometheus wording */
RECREATE = 'Recreate',
EXPIRE = 'Expire',
/* Daemons */
START = 'Start',
STOP = 'Stop',
REDEPLOY = 'Redeploy',
RESTART = 'Restart'
}
@Injectable({
providedIn: 'root'
})
export class ActionLabelsI18n {
/* This service is required as the i18n polyfill does not provide static
translation
*/
CREATE: string;
DELETE: string;
ADD: string;
REMOVE: string;
EDIT: string;
CANCEL: string;
PREVIEW: string;
MOVE: string;
NEXT: string;
BACK: string;
CHANGE: string;
COPY: string;
CLONE: string;
DEEP_SCRUB: string;
DESTROY: string;
EVICT: string;
EXPIRE: string;
FLATTEN: string;
MARK_DOWN: string;
MARK_IN: string;
MARK_LOST: string;
MARK_OUT: string;
PROTECT: string;
PURGE: string;
RECREATE: string;
RENAME: string;
RESTORE: string;
REWEIGHT: string;
ROLLBACK: string;
SCRUB: string;
SET: string;
SUBMIT: string;
SHOW: string;
TRASH: string;
UNPROTECT: string;
UNSET: string;
UPDATE: string;
FLAGS: string;
ENTER_MAINTENANCE: string;
EXIT_MAINTENANCE: string;
REMOVE_SCHEDULING: string;
PROMOTE: string;
DEMOTE: string;
START_DRAIN: string;
STOP_DRAIN: string;
START: string;
STOP: string;
REDEPLOY: string;
RESTART: string;
RESYNC: string;
EXPORT: string;
IMPORT: any;
MIGRATE: string;
constructor() {
/* Create a new item */
this.CREATE = $localize`Create`;
this.EXPORT = $localize`Export`;
this.IMPORT = $localize`Import`;
this.MIGRATE = $localize`Migrate to Multi-Site`;
/* Destroy an existing item */
this.DELETE = $localize`Delete`;
/* Add an existing item to a container */
this.ADD = $localize`Add`;
this.SET = $localize`Set`;
this.SUBMIT = $localize`Submit`;
/* Remove an item from a container WITHOUT deleting it */
this.REMOVE = $localize`Remove`;
this.UNSET = $localize`Unset`;
/* Make changes to an existing item */
this.EDIT = $localize`Edit`;
this.UPDATE = $localize`Update`;
this.CANCEL = $localize`Cancel`;
this.PREVIEW = $localize`Preview`;
this.MOVE = $localize`Move`;
/* Wizard wording */
this.NEXT = $localize`Next`;
this.BACK = $localize`Back`;
/* Non-standard actions */
this.CLONE = $localize`Clone`;
this.COPY = $localize`Copy`;
this.DEEP_SCRUB = $localize`Deep Scrub`;
this.DESTROY = $localize`Destroy`;
this.EVICT = $localize`Evict`;
this.FLATTEN = $localize`Flatten`;
this.MARK_DOWN = $localize`Mark Down`;
this.MARK_IN = $localize`Mark In`;
this.MARK_LOST = $localize`Mark Lost`;
this.MARK_OUT = $localize`Mark Out`;
this.PROTECT = $localize`Protect`;
this.PURGE = $localize`Purge`;
this.RENAME = $localize`Rename`;
this.RESTORE = $localize`Restore`;
this.REWEIGHT = $localize`Reweight`;
this.ROLLBACK = $localize`Rollback`;
this.SCRUB = $localize`Scrub`;
this.SHOW = $localize`Show`;
this.TRASH = $localize`Move to Trash`;
this.UNPROTECT = $localize`Unprotect`;
this.CHANGE = $localize`Change`;
this.FLAGS = $localize`Flags`;
this.ENTER_MAINTENANCE = $localize`Enter Maintenance`;
this.EXIT_MAINTENANCE = $localize`Exit Maintenance`;
this.START_DRAIN = $localize`Start Drain`;
this.STOP_DRAIN = $localize`Stop Drain`;
this.RESYNC = $localize`Resync`;
/* Prometheus wording */
this.RECREATE = $localize`Recreate`;
this.EXPIRE = $localize`Expire`;
this.START = $localize`Start`;
this.STOP = $localize`Stop`;
this.REDEPLOY = $localize`Redeploy`;
this.RESTART = $localize`Restart`;
this.REMOVE_SCHEDULING = $localize`Remove Scheduling`;
this.PROMOTE = $localize`Promote`;
this.DEMOTE = $localize`Demote`;
}
}
@Injectable({
providedIn: 'root'
})
export class SucceededActionLabelsI18n {
/* This service is required as the i18n polyfill does not provide static
translation
*/
CREATED: string;
DELETED: string;
ADDED: string;
REMOVED: string;
EDITED: string;
CANCELED: string;
PREVIEWED: string;
MOVED: string;
EXPORT: string;
IMPORT: string;
COPIED: string;
CLONED: string;
DEEP_SCRUBBED: string;
DESTROYED: string;
FLATTENED: string;
MARKED_DOWN: string;
MARKED_IN: string;
MARKED_LOST: string;
MARKED_OUT: string;
PROTECTED: string;
PURGED: string;
RENAMED: string;
RESTORED: string;
REWEIGHTED: string;
ROLLED_BACK: string;
SCRUBBED: string;
SHOWED: string;
TRASHED: string;
UNPROTECTED: string;
CHANGE: string;
RECREATED: string;
EXPIRED: string;
MOVE: string;
START: string;
STOP: string;
REDEPLOY: string;
RESTART: string;
constructor() {
/* Create a new item */
this.CREATED = $localize`Created`;
/* Destroy an existing item */
this.DELETED = $localize`Deleted`;
/* Add an existing item to a container */
this.ADDED = $localize`Added`;
/* Remove an item from a container WITHOUT deleting it */
this.REMOVED = $localize`Removed`;
/* Make changes to an existing item */
this.EDITED = $localize`Edited`;
this.CANCELED = $localize`Canceled`;
this.PREVIEWED = $localize`Previewed`;
this.MOVED = $localize`Moved`;
/* Non-standard actions */
this.CLONED = $localize`Cloned`;
this.COPIED = $localize`Copied`;
this.DEEP_SCRUBBED = $localize`Deep Scrubbed`;
this.DESTROYED = $localize`Destroyed`;
this.FLATTENED = $localize`Flattened`;
this.MARKED_DOWN = $localize`Marked Down`;
this.MARKED_IN = $localize`Marked In`;
this.MARKED_LOST = $localize`Marked Lost`;
this.MARKED_OUT = $localize`Marked Out`;
this.PROTECTED = $localize`Protected`;
this.PURGED = $localize`Purged`;
this.RENAMED = $localize`Renamed`;
this.RESTORED = $localize`Restored`;
this.REWEIGHTED = $localize`Reweighted`;
this.ROLLED_BACK = $localize`Rolled back`;
this.SCRUBBED = $localize`Scrubbed`;
this.SHOWED = $localize`Showed`;
this.TRASHED = $localize`Moved to Trash`;
this.UNPROTECTED = $localize`Unprotected`;
this.CHANGE = $localize`Change`;
/* Prometheus wording */
this.RECREATED = $localize`Recreated`;
this.EXPIRED = $localize`Expired`;
this.START = $localize`Start`;
this.STOP = $localize`Stop`;
this.REDEPLOY = $localize`Redeploy`;
this.RESTART = $localize`Restart`;
}
}
@Injectable({
providedIn: 'root'
})
export class TimerServiceInterval {
TIMER_SERVICE_PERIOD: number;
constructor() {
this.TIMER_SERVICE_PERIOD = 5000;
}
}
| 8,046
| 23.533537
| 96
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/datatable.module.ts
|
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { NgbDropdownModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormlyModule } from '@ngx-formly/core';
import { FormlyBootstrapModule } from '@ngx-formly/bootstrap';
import { ComponentsModule } from '../components/components.module';
import { PipesModule } from '../pipes/pipes.module';
import { CRUDTableComponent } from './crud-table/crud-table.component';
import { TableActionsComponent } from './table-actions/table-actions.component';
import { TableKeyValueComponent } from './table-key-value/table-key-value.component';
import { TablePaginationComponent } from './table-pagination/table-pagination.component';
import { TableComponent } from './table/table.component';
import { CrudFormComponent } from '../forms/crud-form/crud-form.component';
import { FormlyArrayTypeComponent } from '../forms/crud-form/formly-array-type/formly-array-type.component';
import { FormlyInputTypeComponent } from '../forms/crud-form/formly-input-type/formly-input-type.component';
import { FormlyObjectTypeComponent } from '../forms/crud-form/formly-object-type/formly-object-type.component';
import { FormlyTextareaTypeComponent } from '../forms/crud-form/formly-textarea-type/formly-textarea-type.component';
import { FormlyInputWrapperComponent } from '../forms/crud-form/formly-input-wrapper/formly-input-wrapper.component';
import { FormlyFileTypeComponent } from '../forms/crud-form/formly-file-type/formly-file-type.component';
import { FormlyFileValueAccessorDirective } from '../forms/crud-form/formly-file-type/formly-file-type-accessor';
@NgModule({
imports: [
CommonModule,
NgxDatatableModule,
NgxPipeFunctionModule,
FormsModule,
NgbDropdownModule,
NgbTooltipModule,
PipesModule,
ComponentsModule,
RouterModule,
ReactiveFormsModule,
FormlyModule.forRoot({
types: [
{ name: 'array', component: FormlyArrayTypeComponent },
{ name: 'object', component: FormlyObjectTypeComponent },
{ name: 'input', component: FormlyInputTypeComponent, wrappers: ['input-wrapper'] },
{ name: 'textarea', component: FormlyTextareaTypeComponent, wrappers: ['input-wrapper'] },
{ name: 'file', component: FormlyFileTypeComponent, wrappers: ['input-wrapper'] }
],
validationMessages: [
{ name: 'required', message: 'This field is required' },
{ name: 'json', message: 'This field is not a valid json document' },
{
name: 'rgwRoleName',
message:
'Role name must contain letters, numbers or the ' +
'following valid special characters "_+=,.@-]+" (pattern: [0-9a-zA-Z_+=,.@-]+)'
},
{
name: 'rgwRolePath',
message:
'Role path must start and finish with a slash "/".' +
' (pattern: (\u002F)|(\u002F[\u0021-\u007E]+\u002F))'
},
{ name: 'file_size', message: 'File size must not exceed 4KiB' }
],
wrappers: [{ name: 'input-wrapper', component: FormlyInputWrapperComponent }]
}),
FormlyBootstrapModule
],
declarations: [
TableComponent,
TableKeyValueComponent,
TableActionsComponent,
CRUDTableComponent,
TablePaginationComponent,
CrudFormComponent,
FormlyArrayTypeComponent,
FormlyInputTypeComponent,
FormlyObjectTypeComponent,
FormlyInputWrapperComponent,
FormlyFileTypeComponent,
FormlyFileValueAccessorDirective
],
exports: [
TableComponent,
NgxDatatableModule,
TableKeyValueComponent,
TableActionsComponent,
CRUDTableComponent,
TablePaginationComponent
]
})
export class DataTableModule {}
| 3,969
| 41.688172
| 117
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/crud-table/crud-table.component.html
|
<ul class="nav nav-tabs"
*ngIf="tabs">
<li class="nav-item"
*ngFor="let tab of tabs; keyvalue">
<a class="nav-link"
[routerLink]="tab.url"
routerLinkActive="active"
ariaCurrentWhenActive="page"
[routerLinkActiveOptions]="{exact: true}"
i18n>{{tab.name}}</a>
</li>
</ul>
<ng-container *ngIf="meta">
<cd-table
[data]="data$ | async"
[columns]="meta.table.columns"
[columnMode]="meta.table.columnMode"
(setExpandedRow)="setExpandedRow($event)"
[hasDetails]="meta.detail_columns.length > 0"
[selectionType]="meta.table.selectionType"
(updateSelection)="updateSelection($event)"
[toolHeader]="meta.table.toolHeader">
<div class="table-actions btn-toolbar">
<cd-table-actions [permission]="permission"
[selection]="selection"
class="btn-group"
id="crud-table-actions"
[tableActions]="meta.actions">
</cd-table-actions>
</div>
<ng-container *ngIf="expandedRow && meta.detail_columns.length > 0"
cdTableDetail>
<table class="table table-striped table-bordered">
<tbody>
<tr *ngFor="let column of meta.detail_columns">
<td i18n
class="bold">{{ column }}</td>
<td> {{ expandedRow[column] }} </td>
</tr>
</tbody>
</table>
</ng-container>
</cd-table>
</ng-container>
<ng-template #badgeDictTpl
let-value="value">
<span *ngFor="let instance of value | keyvalue; last as isLast">
<span class="badge badge-background-primary" >{{ instance.key }}: {{ instance.value }}</span>
<ng-container *ngIf="!isLast"> </ng-container>
</span>
</ng-template>
<ng-template #dateTpl
let-value="value">
<span>{{ value | cdDate }}</span>
</ng-template>
<ng-template #durationTpl
let-value="value">
<span>{{ value | duration }}</span>
</ng-template>
<ng-template #exportDataModalTpl>
<div class="d-flex flex-column align-items-center w-100 gap-3">
<textarea readonly
class="form-control w-100 bg-light height-400"
id="authExportArea">{{ modalState.authExportData }}</textarea>
<cd-copy-2-clipboard-button class="align-self-end"
source="authExportArea">
</cd-copy-2-clipboard-button>
</div>
</ng-template>
| 2,449
| 30.818182
| 97
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/crud-table/crud-table.component.spec.ts
|
/* tslint:disable:no-unused-variable */
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbDropdownModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { ToastrModule } from 'ngx-toastr';
import { ComponentsModule } from '~/app/shared/components/components.module';
import { PipesModule } from '~/app/shared/pipes/pipes.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { TableKeyValueComponent } from '../table-key-value/table-key-value.component';
import { TablePaginationComponent } from '../table-pagination/table-pagination.component';
import { TableComponent } from '../table/table.component';
import { CRUDTableComponent } from './crud-table.component';
describe('CRUDTableComponent', () => {
let component: CRUDTableComponent;
let fixture: ComponentFixture<CRUDTableComponent>;
configureTestBed({
declarations: [
CRUDTableComponent,
TableComponent,
TableKeyValueComponent,
TablePaginationComponent
],
imports: [
NgxDatatableModule,
FormsModule,
ComponentsModule,
NgbDropdownModule,
PipesModule,
NgbTooltipModule,
RouterTestingModule,
NgxPipeFunctionModule,
HttpClientTestingModule,
ToastrModule.forRoot()
]
});
beforeEach(() => {
fixture = TestBed.createComponent(CRUDTableComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,841
| 33.111111
| 90
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/crud-table/crud-table.component.ts
|
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { Observable } from 'rxjs';
import { CrudMetadata } from '~/app/shared/models/crud-table-metadata';
import { DataGatewayService } from '~/app/shared/services/data-gateway.service';
import { TimerService } from '~/app/shared/services/timer.service';
import { CephUserService } from '../../api/ceph-user.service';
import { ConfirmationModalComponent } from '../../components/confirmation-modal/confirmation-modal.component';
import { CdTableSelection } from '../../models/cd-table-selection';
import { FinishedTask } from '../../models/finished-task';
import { Permission, Permissions } from '../../models/permissions';
import { AuthStorageService } from '../../services/auth-storage.service';
import { TaskWrapperService } from '../../services/task-wrapper.service';
import { ModalService } from '../../services/modal.service';
import { CriticalConfirmationModalComponent } from '../../components/critical-confirmation-modal/critical-confirmation-modal.component';
@Component({
selector: 'cd-crud-table',
templateUrl: './crud-table.component.html',
styleUrls: ['./crud-table.component.scss']
})
export class CRUDTableComponent implements OnInit {
@ViewChild('badgeDictTpl')
public badgeDictTpl: TemplateRef<any>;
@ViewChild('dateTpl')
public dateTpl: TemplateRef<any>;
@ViewChild('durationTpl')
public durationTpl: TemplateRef<any>;
@ViewChild('exportDataModalTpl')
public authxEportTpl: TemplateRef<any>;
data$: Observable<any>;
meta$: Observable<CrudMetadata>;
meta: CrudMetadata;
permissions: Permissions;
permission: Permission;
selection = new CdTableSelection();
expandedRow: any = null;
modalRef: NgbModalRef;
tabs = {};
resource: string;
modalState = {};
constructor(
private authStorageService: AuthStorageService,
private timerService: TimerService,
private dataGatewayService: DataGatewayService,
private taskWrapper: TaskWrapperService,
private cephUserService: CephUserService,
private activatedRoute: ActivatedRoute,
private modalService: ModalService,
private router: Router
) {
this.permissions = this.authStorageService.getPermissions();
}
ngOnInit() {
/* The following should be simplified with a wrapper that
converts .data to @Input args. For example:
https://medium.com/@andrewcherepovskiy/passing-route-params-into-angular-components-input-properties-fc85c34c9aca
*/
this.activatedRoute.data.subscribe((data: any) => {
const resource: string = data.resource;
this.tabs = data.tabs;
this.dataGatewayService
.list(`ui-${resource}`)
.subscribe((response: CrudMetadata) => this.processMeta(response));
this.data$ = this.timerService.get(() => this.dataGatewayService.list(resource));
});
this.activatedRoute.data.subscribe((data: any) => {
this.resource = data.resource;
});
}
processMeta(meta: CrudMetadata) {
const toCamelCase = (test: string) =>
test
.split('-')
.reduce(
(res: string, word: string, i: number) =>
i === 0
? word.toLowerCase()
: `${res}${word.charAt(0).toUpperCase()}${word.substr(1).toLowerCase()}`,
''
);
this.permission = this.permissions[toCamelCase(meta.permissions[0])];
const templates = {
badgeDict: this.badgeDictTpl,
date: this.dateTpl,
duration: this.durationTpl
};
meta.table.columns.forEach((element, index) => {
if (element['cellTemplate'] !== undefined) {
meta.table.columns[index]['cellTemplate'] = templates[element['cellTemplate'] as string];
}
});
// isHidden flag does not work as expected somehow so the best ways to enforce isHidden is
// to filter the columns manually instead of letting isHidden flag inside table.component to
// work.
meta.table.columns = meta.table.columns.filter((col: any) => {
return !col['isHidden'];
});
this.meta = meta;
for (let i = 0; i < this.meta.actions.length; i++) {
let action = this.meta.actions[i];
if (action.disable) {
action.disable = (selection) => !selection.hasSelection;
}
if (action.click.toString() !== '') {
action.click = this[this.meta.actions[i].click.toString()].bind(this);
}
}
}
delete() {
const selectedKey = this.selection.first()[this.meta.columnKey];
this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, {
itemDescription: $localize`${this.meta.columnKey}`,
itemNames: [selectedKey],
submitAction: () => {
this.taskWrapper
.wrapTaskAroundCall({
task: new FinishedTask('crud-component/id', selectedKey),
call: this.dataGatewayService.delete(this.resource, selectedKey)
})
.subscribe({
error: () => {
this.modalRef.close();
},
complete: () => {
this.modalRef.close();
}
});
}
});
}
updateSelection(selection: CdTableSelection) {
this.selection = selection;
}
setExpandedRow(event: any) {
this.expandedRow = event;
}
edit() {
let key = '';
if (this.selection.hasSelection) {
key = this.selection.first()[this.meta.columnKey];
}
this.router.navigate(['/cluster/user/edit'], { queryParams: { key: key } });
}
authExport() {
let entities: string[] = [];
this.selection.selected.forEach((row) => entities.push(row.entity));
this.cephUserService.export(entities).subscribe((data: string) => {
const modalVariables = {
titleText: $localize`Ceph user export data`,
buttonText: $localize`Close`,
bodyTpl: this.authxEportTpl,
showSubmit: true,
showCancel: false,
onSubmit: () => {
this.modalRef.close();
}
};
this.modalState['authExportData'] = data.trim();
this.modalRef = this.modalService.show(ConfirmationModalComponent, modalVariables);
});
}
}
| 6,258
| 34.162921
| 136
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-actions/table-actions.component.html
|
<div class="btn-group">
<ng-container *ngIf="currentAction">
<button type="button"
title="{{ useDisableDesc(currentAction) }}"
class="btn btn-{{btnColor}}"
[ngClass]="{'disabled': disableSelectionAction(currentAction)}"
(click)="useClickAction(currentAction)"
[disabled]="disableSelectionAction(currentAction)"
[routerLink]="useRouterLink(currentAction)"
[attr.aria-label]="currentAction.name"
[preserveFragment]="currentAction.preserveFragment ? '' : null">
<i [ngClass]="[currentAction.icon]"></i>
<span class="action-label">{{ currentAction.name }}</span>
</button>
</ng-container>
<div class="btn-group"
ngbDropdown
role="group"
*ngIf="dropDownActions.length > 1"
aria-label="Button group with nested dropdown">
<button aria-label="dropdown-menu-toggle"
class="btn btn-{{btnColor}} dropdown-toggle-split"
ngbDropdownToggle>
<ng-container *ngIf="dropDownOnly">{{ dropDownOnly }} </ng-container>
<span *ngIf="!dropDownOnly"
class="sr-only"></span>
</button>
<div class="dropdown-menu"
ngbDropdownMenu>
<ng-container *ngFor="let action of dropDownActions">
<button ngbDropdownItem
class="{{ toClassName(action) }}"
title="{{ useDisableDesc(action) }}"
(click)="useClickAction(action)"
[routerLink]="useRouterLink(action)"
[preserveFragment]="action.preserveFragment ? '' : null"
[disabled]="disableSelectionAction(action)"
[attr.aria-label]="action.name">
<i [ngClass]="[action.icon, 'action-icon']"></i>
<span>{{ action.name }}</span>
</button>
</ng-container>
</div>
</div>
</div>
| 1,869
| 39.652174
| 76
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-actions/table-actions.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { ComponentsModule } from '~/app/shared/components/components.module';
import { CdTableAction } from '~/app/shared/models/cd-table-action';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { Permission } from '~/app/shared/models/permissions';
import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper';
import { TableActionsComponent } from './table-actions.component';
describe('TableActionsComponent', () => {
let component: TableActionsComponent;
let fixture: ComponentFixture<TableActionsComponent>;
let addAction: CdTableAction;
let editAction: CdTableAction;
let protectAction: CdTableAction;
let unprotectAction: CdTableAction;
let deleteAction: CdTableAction;
let copyAction: CdTableAction;
let permissionHelper: PermissionHelper;
configureTestBed({
declarations: [TableActionsComponent],
imports: [ComponentsModule, NgxPipeFunctionModule, RouterTestingModule]
});
beforeEach(() => {
addAction = {
permission: 'create',
icon: 'fa-plus',
canBePrimary: (selection: CdTableSelection) => !selection.hasSelection,
name: 'Add'
};
editAction = {
permission: 'update',
icon: 'fa-pencil',
name: 'Edit'
};
copyAction = {
permission: 'create',
icon: 'fa-copy',
canBePrimary: (selection: CdTableSelection) => selection.hasSingleSelection,
disable: (selection: CdTableSelection) =>
!selection.hasSingleSelection || selection.first().cdExecuting,
name: 'Copy'
};
deleteAction = {
permission: 'delete',
icon: 'fa-times',
canBePrimary: (selection: CdTableSelection) => selection.hasSelection,
disable: (selection: CdTableSelection) =>
!selection.hasSelection || selection.first().cdExecuting,
name: 'Delete'
};
protectAction = {
permission: 'update',
icon: 'fa-lock',
canBePrimary: () => false,
visible: (selection: CdTableSelection) => selection.hasSingleSelection,
name: 'Protect'
};
unprotectAction = {
permission: 'update',
icon: 'fa-unlock',
canBePrimary: () => false,
visible: (selection: CdTableSelection) => !selection.hasSingleSelection,
name: 'Unprotect'
};
fixture = TestBed.createComponent(TableActionsComponent);
component = fixture.componentInstance;
component.selection = new CdTableSelection();
component.permission = new Permission();
component.permission.read = true;
component.tableActions = [
addAction,
editAction,
protectAction,
unprotectAction,
copyAction,
deleteAction
];
permissionHelper = new PermissionHelper(component.permission);
permissionHelper.setPermissionsAndGetActions(component.tableActions);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call ngInit without permissions', () => {
component.permission = undefined;
component.ngOnInit();
expect(component.tableActions).toEqual([]);
expect(component.dropDownActions).toEqual([]);
});
describe('useRouterLink', () => {
const testLink = '/api/some/link';
it('should use a link generated from a function', () => {
addAction.routerLink = () => testLink;
expect(component.useRouterLink(addAction)).toBe(testLink);
});
it('should use the link as it is because it is a string', () => {
addAction.routerLink = testLink;
expect(component.useRouterLink(addAction)).toBe(testLink);
});
it('should not return anything because no link is defined', () => {
expect(component.useRouterLink(addAction)).toBe(undefined);
});
it('should not return anything because the action is disabled', () => {
editAction.routerLink = testLink;
expect(component.useRouterLink(editAction)).toBe(undefined);
});
});
it('should test all TableActions combinations', () => {
const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions(
component.tableActions
);
expect(tableActions).toEqual({
'create,update,delete': {
actions: ['Add', 'Edit', 'Protect', 'Unprotect', 'Copy', 'Delete'],
primary: { multiple: 'Delete', executing: 'Edit', single: 'Edit', no: 'Add' }
},
'create,update': {
actions: ['Add', 'Edit', 'Protect', 'Unprotect', 'Copy'],
primary: { multiple: 'Add', executing: 'Edit', single: 'Edit', no: 'Add' }
},
'create,delete': {
actions: ['Add', 'Copy', 'Delete'],
primary: { multiple: 'Delete', executing: 'Copy', single: 'Copy', no: 'Add' }
},
create: {
actions: ['Add', 'Copy'],
primary: { multiple: 'Add', executing: 'Copy', single: 'Copy', no: 'Add' }
},
'update,delete': {
actions: ['Edit', 'Protect', 'Unprotect', 'Delete'],
primary: { multiple: 'Delete', executing: 'Edit', single: 'Edit', no: 'Edit' }
},
update: {
actions: ['Edit', 'Protect', 'Unprotect'],
primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' }
},
delete: {
actions: ['Delete'],
primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
},
'no-permissions': {
actions: [],
primary: { multiple: '', executing: '', single: '', no: '' }
}
});
});
it('should convert any name to a proper CSS class', () => {
expect(component.toClassName({ name: 'Create' } as CdTableAction)).toBe('create');
expect(component.toClassName({ name: 'Mark x down' } as CdTableAction)).toBe('mark-x-down');
expect(component.toClassName({ name: '?Su*per!' } as CdTableAction)).toBe('super');
});
describe('useDisableDesc', () => {
it('should return a description if disable method returns a string', () => {
const deleteWithDescAction: CdTableAction = {
permission: 'delete',
icon: 'fa-times',
canBePrimary: (selection: CdTableSelection) => selection.hasSelection,
disable: () => {
return 'Delete action disabled description';
},
name: 'DeleteDesc'
};
expect(component.useDisableDesc(deleteWithDescAction)).toBe(
'Delete action disabled description'
);
});
it('should return no description if disable does not return string', () => {
expect(component.useDisableDesc(deleteAction)).toBeUndefined();
});
});
describe('useClickAction', () => {
const editClickAction: CdTableAction = {
permission: 'update',
icon: 'fa-pencil',
name: 'Edit',
click: () => {
return 'Edit action click';
}
};
it('should call click action if action is not disabled', () => {
editClickAction.disable = () => {
return false;
};
expect(component.useClickAction(editClickAction)).toBe('Edit action click');
});
it('should not call click action if action is disabled', () => {
editClickAction.disable = () => {
return true;
};
expect(component.useClickAction(editClickAction)).toBeFalsy();
});
});
});
| 7,396
| 33.565421
| 96
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-actions/table-actions.component.ts
|
import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import _ from 'lodash';
import { Icons } from '~/app/shared/enum/icons.enum';
import { CdTableAction } from '~/app/shared/models/cd-table-action';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { Permission } from '~/app/shared/models/permissions';
@Component({
selector: 'cd-table-actions',
templateUrl: './table-actions.component.html',
styleUrls: ['./table-actions.component.scss']
})
export class TableActionsComponent implements OnChanges, OnInit {
@Input()
permission: Permission;
@Input()
selection: CdTableSelection;
@Input()
tableActions: CdTableAction[];
@Input()
btnColor = 'accent';
// Use this if you just want to display a drop down button,
// labeled with the given text, with all actions in it.
// This disables the main action button.
@Input()
dropDownOnly?: string;
currentAction?: CdTableAction;
// Array with all visible actions
dropDownActions: CdTableAction[] = [];
icons = Icons;
ngOnInit() {
this.removeActionsWithNoPermissions();
this.onSelectionChange();
}
ngOnChanges(changes: SimpleChanges) {
if (changes.selection) {
this.onSelectionChange();
}
}
onSelectionChange(): void {
this.updateDropDownActions();
this.updateCurrentAction();
}
toClassName(action: CdTableAction): string {
return action.name
.replace(/ /g, '-')
.replace(/[^a-z-]/gi, '')
.toLowerCase();
}
/**
* Removes all actions from 'tableActions' that need a permission the user doesn't have.
*/
private removeActionsWithNoPermissions() {
if (!this.permission) {
this.tableActions = [];
return;
}
const permissions = Object.keys(this.permission).filter((key) => this.permission[key]);
this.tableActions = this.tableActions.filter((action) =>
permissions.includes(action.permission)
);
}
private updateDropDownActions(): void {
this.dropDownActions = this.tableActions.filter((action) =>
action.visible ? action.visible(this.selection) : action
);
}
/**
* Finds the next action that is used as main action for the button
*
* The order of the list is crucial to get the right main action.
*
* Default button conditions of actions:
* - 'create' actions can be used with no or multiple selections
* - 'update' and 'delete' actions can be used with one selection
*/
private updateCurrentAction(): void {
if (this.dropDownOnly) {
this.currentAction = undefined;
return;
}
let buttonAction = this.dropDownActions.find((tableAction) => this.showableAction(tableAction));
if (!buttonAction && this.dropDownActions.length > 0) {
buttonAction = this.dropDownActions[0];
}
this.currentAction = buttonAction;
}
/**
* Determines if action can be used for the button
*
* @param {CdTableAction} action
* @returns {boolean}
*/
private showableAction(action: CdTableAction): boolean {
const condition = action.canBePrimary;
const singleSelection = this.selection.hasSingleSelection;
const defaultCase = action.permission === 'create' ? !singleSelection : singleSelection;
return (condition && condition(this.selection)) || (!condition && defaultCase);
}
useRouterLink(action: CdTableAction): string {
if (!action.routerLink || this.disableSelectionAction(action)) {
return undefined;
}
return _.isString(action.routerLink) ? action.routerLink : action.routerLink();
}
/**
* Determines if an action should be disabled
*
* Default disable conditions of 'update' and 'delete' actions:
* - If no or multiple selections are made
* - If one selection is made, but a task is executed on that item
*
* @param {CdTableAction} action
* @returns {Boolean}
*/
disableSelectionAction(action: CdTableAction): Boolean {
const disable = action.disable;
if (disable) {
return Boolean(disable(this.selection));
}
const permission = action.permission;
const selected = this.selection.hasSingleSelection && this.selection.first();
return Boolean(
['update', 'delete'].includes(permission) && (!selected || selected.cdExecuting)
);
}
useClickAction(action: CdTableAction) {
/**
* In order to show tooltips for deactivated menu items, the class
* 'pointer-events: auto;' has been added to the .scss file which also
* re-activates the click-event.
* To prevent calling the click-event on deactivated elements we also have
* to check here if it's disabled.
*/
return !this.disableSelectionAction(action) && action.click && action.click();
}
useDisableDesc(action: CdTableAction) {
if (action.disable) {
const result = action.disable(this.selection);
return _.isString(result) ? result : undefined;
}
return undefined;
}
}
| 4,958
| 29.611111
| 100
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-key-value/table-key-value.component.html
|
<div class="table-scroller">
<cd-table #table
[data]="tableData"
[columns]="columns"
columnMode="flex"
[toolHeader]="false"
[autoReload]="autoReload"
[customCss]="customCss"
[autoSave]="false"
[header]="false"
[footer]="false"
[limit]="0">
</cd-table>
</div>
| 383
| 24.6
| 37
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-key-value/table-key-value.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbDropdownModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { ComponentsModule } from '~/app/shared/components/components.module';
import { CellTemplate } from '~/app/shared/enum/cell-template.enum';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdDatePipe } from '~/app/shared/pipes/cd-date.pipe';
import { PipesModule } from '~/app/shared/pipes/pipes.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { TablePaginationComponent } from '../table-pagination/table-pagination.component';
import { TableComponent } from '../table/table.component';
import { TableKeyValueComponent } from './table-key-value.component';
describe('TableKeyValueComponent', () => {
let component: TableKeyValueComponent;
let fixture: ComponentFixture<TableKeyValueComponent>;
configureTestBed({
declarations: [TableComponent, TableKeyValueComponent, TablePaginationComponent],
imports: [
FormsModule,
NgxDatatableModule,
ComponentsModule,
RouterTestingModule,
NgbDropdownModule,
PipesModule,
NgbTooltipModule,
NgxPipeFunctionModule
]
});
beforeEach(() => {
fixture = TestBed.createComponent(TableKeyValueComponent);
component = fixture.componentInstance;
});
it('should create', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should make key value object pairs out of arrays with length two', () => {
component.data = [
['someKey', 0],
['arrayKey', [1, 2, 3]],
[3, 'something']
];
component.ngOnInit();
const expected: any = [
{ key: 'arrayKey', value: '1, 2, 3' },
{ key: 'someKey', value: 0 },
{ key: 3, value: 'something' }
];
expect(component.tableData).toEqual(expected);
});
it('should not show data supposed to be have hidden by key', () => {
component.data = [
['a', 1],
['b', 2]
];
component.hideKeys = ['a'];
component.ngOnInit();
expect(component.tableData).toEqual([{ key: 'b', value: 2 }]);
});
it('should remove items with objects as values', () => {
component.data = [
[3, 'something'],
['will be removed', { a: 3, b: 4, c: 5 }]
];
component.ngOnInit();
expect(component.tableData).toEqual(<any>[{ key: 3, value: 'something' }]);
});
it('makes key value object pairs out of an object', () => {
component.data = { 3: 'something', someKey: 0 };
component.ngOnInit();
expect(component.tableData).toEqual([
{ key: '3', value: 'something' },
{ key: 'someKey', value: 0 }
]);
});
it('does nothing if data does not need to be converted', () => {
component.data = [
{ key: 3, value: 'something' },
{ key: 'someKey', value: 0 }
];
component.ngOnInit();
expect(component.tableData).toEqual(component.data);
});
it('throws errors if data cannot be converted', () => {
component.data = 38;
expect(() => component.ngOnInit()).toThrowError('Wrong data format');
component.data = [['someKey', 0, 3]];
expect(() => component.ngOnInit()).toThrowError(
'Array contains too many elements (3). Needs to be of type [string, any][]'
);
});
it('tests makePairs()', () => {
const makePairs = (data: any) => component['makePairs'](data);
expect(makePairs([['dash', 'board']])).toEqual([{ key: 'dash', value: 'board' }]);
const pair = [
{ key: 'dash', value: 'board' },
{ key: 'ceph', value: 'mimic' }
];
const pairInverse = [
{ key: 'ceph', value: 'mimic' },
{ key: 'dash', value: 'board' }
];
expect(makePairs(pair)).toEqual(pairInverse);
expect(makePairs({ dash: 'board' })).toEqual([{ key: 'dash', value: 'board' }]);
expect(makePairs({ dash: 'board', ceph: 'mimic' })).toEqual(pairInverse);
});
it('tests makePairsFromArray()', () => {
const makePairsFromArray = (data: any[]) => component['makePairsFromArray'](data);
expect(makePairsFromArray([['dash', 'board']])).toEqual([{ key: 'dash', value: 'board' }]);
const pair = [
{ key: 'dash', value: 'board' },
{ key: 'ceph', value: 'mimic' }
];
expect(makePairsFromArray(pair)).toEqual(pair);
});
it('tests makePairsFromObject()', () => {
const makePairsFromObject = (data: object) => component['makePairsFromObject'](data);
expect(makePairsFromObject({ dash: 'board' })).toEqual([{ key: 'dash', value: 'board' }]);
expect(makePairsFromObject({ dash: 'board', ceph: 'mimic' })).toEqual([
{ key: 'dash', value: 'board' },
{ key: 'ceph', value: 'mimic' }
]);
});
describe('tests convertValue()', () => {
const convertValue = (data: any) => component['convertValue'](data);
const expectConvertValue = (value: any, expectation: any) =>
expect(convertValue(value)).toBe(expectation);
it('should not convert strings', () => {
expectConvertValue('something', 'something');
});
it('should not convert integers', () => {
expectConvertValue(29, 29);
});
it('should convert arrays with any type to strings', () => {
expectConvertValue([1, 2, 3], '1, 2, 3');
expectConvertValue([{ sth: 'something' }], '{"sth":"something"}');
expectConvertValue([1, 'two', { 3: 'three' }], '1, two, {"3":"three"}');
});
it('should only convert objects if renderObjects is set to true', () => {
expect(convertValue({ sth: 'something' })).toBe(null);
component.renderObjects = true;
expect(convertValue({ sth: 'something' })).toEqual({ sth: 'something' });
});
});
describe('automatically pipe UTC dates through cdDate', () => {
let datePipe: CdDatePipe;
beforeEach(() => {
datePipe = TestBed.inject(CdDatePipe);
spyOn(datePipe, 'transform').and.callThrough();
});
const expectTimeConversion = (date: string) => {
component.data = { dateKey: date };
component.ngOnInit();
expect(datePipe.transform).toHaveBeenCalledWith(date);
expect(component.tableData[0].key).not.toBe(date);
};
it('converts some date', () => {
expectTimeConversion('2019-04-15 12:26:52.305285');
});
it('converts UTC date', () => {
expectTimeConversion('2019-04-16T12:35:46.646300974Z');
});
});
describe('render objects', () => {
beforeEach(() => {
component.data = {
options: {
numberKey: 38,
stringKey: 'somethingElse',
objectKey: {
sub1: 12,
sub2: 34,
sub3: 56
}
},
otherOptions: {
sub1: {
x: 42
},
sub2: {
y: 555
}
},
additionalKeyContainingObject: { type: 'none' },
keyWithEmptyObject: {}
};
component.renderObjects = true;
});
it('with parent key', () => {
component.ngOnInit();
expect(component.tableData).toEqual([
{ key: 'additionalKeyContainingObject type', value: 'none' },
{ key: 'keyWithEmptyObject', value: '' },
{ key: 'options numberKey', value: 38 },
{ key: 'options objectKey sub1', value: 12 },
{ key: 'options objectKey sub2', value: 34 },
{ key: 'options objectKey sub3', value: 56 },
{ key: 'options stringKey', value: 'somethingElse' },
{ key: 'otherOptions sub1 x', value: 42 },
{ key: 'otherOptions sub2 y', value: 555 }
]);
});
it('without parent key', () => {
component.appendParentKey = false;
component.ngOnInit();
expect(component.tableData).toEqual([
{ key: 'keyWithEmptyObject', value: '' },
{ key: 'numberKey', value: 38 },
{ key: 'stringKey', value: 'somethingElse' },
{ key: 'sub1', value: 12 },
{ key: 'sub2', value: 34 },
{ key: 'sub3', value: 56 },
{ key: 'type', value: 'none' },
{ key: 'x', value: 42 },
{ key: 'y', value: 555 }
]);
});
});
describe('subscribe fetchData', () => {
it('should not subscribe fetchData of table', () => {
component.ngOnInit();
expect(component.table.fetchData.observers.length).toBe(0);
});
it('should call fetchData', () => {
let called = false;
component.fetchData.subscribe(() => {
called = true;
});
component.ngOnInit();
expect(component.table.fetchData.observers.length).toBe(1);
component.table.fetchData.emit();
expect(called).toBeTruthy();
});
});
describe('hide empty items', () => {
beforeEach(() => {
component.data = {
booleanFalse: false,
booleanTrue: true,
string: '',
array: [],
object: {},
emptyObject: {
string: '',
array: [],
object: {}
},
someNumber: 0,
someDifferentNumber: 1,
someArray: [0, 1],
someString: '0',
someObject: {
empty: {},
something: 0.1
}
};
component.renderObjects = true;
});
it('should show all items as default', () => {
expect(component.hideEmpty).toBe(false);
component.ngOnInit();
expect(component.tableData).toEqual([
{ key: 'array', value: '' },
{ key: 'booleanFalse', value: false },
{ key: 'booleanTrue', value: true },
{ key: 'emptyObject array', value: '' },
{ key: 'emptyObject object', value: '' },
{ key: 'emptyObject string', value: '' },
{ key: 'object', value: '' },
{ key: 'someArray', value: '0, 1' },
{ key: 'someDifferentNumber', value: 1 },
{ key: 'someNumber', value: 0 },
{ key: 'someObject empty', value: '' },
{ key: 'someObject something', value: 0.1 },
{ key: 'someString', value: '0' },
{ key: 'string', value: '' }
]);
});
it('should hide all empty items', () => {
component.hideEmpty = true;
component.ngOnInit();
expect(component.tableData).toEqual([
{ key: 'booleanFalse', value: false },
{ key: 'booleanTrue', value: true },
{ key: 'someArray', value: '0, 1' },
{ key: 'someDifferentNumber', value: 1 },
{ key: 'someNumber', value: 0 },
{ key: 'someObject something', value: 0.1 },
{ key: 'someString', value: '0' }
]);
});
});
describe('columns set up', () => {
let columns: CdTableColumn[];
beforeEach(() => {
columns = [
{ prop: 'key', flexGrow: 1, cellTransformation: CellTemplate.bold },
{ prop: 'value', flexGrow: 3 }
];
});
it('should have the following default column set up', () => {
component.ngOnInit();
expect(component.columns).toEqual(columns);
});
it('should have the following column set up if customCss is defined', () => {
component.customCss = { 'class-name': 42 };
component.ngOnInit();
columns[1].cellTransformation = CellTemplate.classAdding;
expect(component.columns).toEqual(columns);
});
});
});
| 11,424
| 31.365439
| 95
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-key-value/table-key-value.component.ts
|
import {
Component,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
ViewChild
} from '@angular/core';
import _ from 'lodash';
import { CellTemplate } from '~/app/shared/enum/cell-template.enum';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdDatePipe } from '~/app/shared/pipes/cd-date.pipe';
import { TableComponent } from '../table/table.component';
interface KeyValueItem {
key: string;
value: any;
}
/**
* Display the given data in a 2 column data table. The left column
* shows the 'key' attribute, the right column the 'value' attribute.
* The data table has the following characteristics:
* - No header and footer is displayed
* - The relation of the width for the columns 'key' and 'value' is 1:3
* - The 'key' column is displayed in bold text
*/
@Component({
selector: 'cd-table-key-value',
templateUrl: './table-key-value.component.html',
styleUrls: ['./table-key-value.component.scss']
})
export class TableKeyValueComponent implements OnInit, OnChanges {
@ViewChild(TableComponent, { static: true })
table: TableComponent;
@Input()
data: any;
@Input()
autoReload: any = 5000;
@Input()
renderObjects = false;
// Only used if objects are rendered
@Input()
appendParentKey = true;
@Input()
hideEmpty = false;
@Input()
hideKeys: string[] = []; // Keys of pairs not to be displayed
// If set, the classAddingTpl is used to enable different css for different values
@Input()
customCss?: { [css: string]: number | string | ((any: any) => boolean) };
columns: Array<CdTableColumn> = [];
tableData: KeyValueItem[];
/**
* The function that will be called to update the input data.
*/
@Output()
fetchData = new EventEmitter();
constructor(private datePipe: CdDatePipe) {}
ngOnInit() {
this.columns = [
{
prop: 'key',
flexGrow: 1,
cellTransformation: CellTemplate.bold
},
{
prop: 'value',
flexGrow: 3
}
];
if (this.customCss) {
this.columns[1].cellTransformation = CellTemplate.classAdding;
}
// We need to subscribe the 'fetchData' event here and not in the
// HTML template, otherwise the data table will display the loading
// indicator infinitely if data is only bound via '[data]="xyz"'.
// See for 'loadingIndicator' in 'TableComponent::ngOnInit()'.
if (this.fetchData.observers.length > 0) {
this.table.fetchData.subscribe(() => {
// Forward event triggered by the 'cd-table' data table.
this.fetchData.emit();
});
}
this.useData();
}
ngOnChanges() {
this.useData();
}
useData() {
if (!this.data) {
return; // Wait for data
}
let pairs = this.makePairs(this.data);
if (this.hideKeys) {
pairs = pairs.filter((pair) => !this.hideKeys.includes(pair.key));
}
this.tableData = pairs;
}
private makePairs(data: any): KeyValueItem[] {
let result: KeyValueItem[] = [];
if (!data) {
return undefined; // Wait for data
} else if (_.isArray(data)) {
result = this.makePairsFromArray(data);
} else if (_.isObject(data)) {
result = this.makePairsFromObject(data);
} else {
throw new Error('Wrong data format');
}
result = result
.map((item) => {
item.value = this.convertValue(item.value);
return item;
})
.filter((i) => i.value !== null);
return _.sortBy(this.renderObjects ? this.insertFlattenObjects(result) : result, 'key');
}
private makePairsFromArray(data: any[]): KeyValueItem[] {
let temp: any[] = [];
const first = data[0];
if (_.isArray(first)) {
if (first.length === 2) {
temp = data.map((a) => ({
key: a[0],
value: a[1]
}));
} else {
throw new Error(
`Array contains too many elements (${first.length}). ` +
`Needs to be of type [string, any][]`
);
}
} else if (_.isObject(first)) {
if (_.has(first, 'key') && _.has(first, 'value')) {
temp = [...data];
} else {
temp = data.reduce(
(previous: any[], item) => previous.concat(this.makePairsFromObject(item)),
temp
);
}
}
return temp;
}
private makePairsFromObject(data: any): KeyValueItem[] {
return Object.keys(data).map((k) => ({
key: k,
value: data[k]
}));
}
private insertFlattenObjects(data: KeyValueItem[]): any[] {
return _.flattenDeep(
data.map((item) => {
const value = item.value;
const isObject = _.isObject(value);
if (!isObject || _.isEmpty(value)) {
if (isObject) {
item.value = '';
}
return item;
}
return this.splitItemIntoItems(item);
})
);
}
/**
* Split item into items will call _makePairs inside _makePairs (recursion), in oder to split
* the object item up into items as planned.
*/
private splitItemIntoItems(data: { key: string; value: object }): KeyValueItem[] {
return this.makePairs(data.value).map((item) => {
if (this.appendParentKey) {
item.key = data.key + ' ' + item.key;
}
return item;
});
}
private convertValue(value: any): KeyValueItem {
if (_.isArray(value)) {
if (_.isEmpty(value) && this.hideEmpty) {
return null;
}
value = value.map((item) => (_.isObject(item) ? JSON.stringify(item) : item)).join(', ');
} else if (_.isObject(value)) {
if ((this.hideEmpty && _.isEmpty(value)) || !this.renderObjects) {
return null;
}
} else if (_.isString(value)) {
if (value === '' && this.hideEmpty) {
return null;
}
if (this.isDate(value)) {
value = this.datePipe.transform(value) || value;
}
}
return value;
}
private isDate(s: string) {
const sep = '[ -:.TZ]';
const n = '\\d{2}' + sep;
// year - m - d - h : m : s . someRest Z (if UTC)
return s.match(new RegExp('^\\d{4}' + sep + n + n + n + n + n + '\\d*' + 'Z?$'));
}
}
| 6,160
| 26.382222
| 95
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-pagination/table-pagination.component.html
|
<nav class="pagination"
aria-label="Pagination"
i18n-aria-label>
<button
class="pagination__btn pagination__btn_first"
aria-label="Go to first page"
i18n-aria-label
[disabled]="!canPrevious()"
(click)="selectPage(1)"
>
<i class="fa fa-angle-double-left"
aria-hidden="true"></i>
</button>
<button
class="pagination__btn pagination__btn_prev"
aria-label="Go to previous page"
i18n-aria-label
[disabled]="!canPrevious()"
(click)="prevPage()"
>
<i class="fa fa-angle-left"
aria-hidden="true"></i>
</button>
<div class="pagination__pages">
<input
#pageNumber
class="pagination__page_input"
aria-label="Current page"
i18n-aria-label
type="number"
min="1"
[max]="totalPages"
[value]="page"
(input)="selectPage(pageNumber.valueAsNumber)"
/>
<span aria-hidden="true"> of {{ totalPages }} </span>
</div>
<button
class="pagination__btn pagination__btn_next"
aria-label="Go to next page"
i18n-aria-label
(click)="nextPage()"
[disabled]="!canNext()"
>
<i class="fa fa-angle-right"
aria-hidden="true"></i>
</button>
<button
class="pagination__btn pagination__btn_last"
aria-label="Go to last page"
i18n-aria-label
[disabled]="!canNext()"
(click)="selectPage(totalPages)"
>
<i class="fa fa-angle-double-right"
aria-hidden="true"></i>
</button>
</nav>
| 1,464
| 23.830508
| 57
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-pagination/table-pagination.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TablePaginationComponent } from './table-pagination.component';
describe('TablePaginationComponent', () => {
let component: TablePaginationComponent;
let fixture: ComponentFixture<TablePaginationComponent>;
let element: HTMLElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [TablePaginationComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TablePaginationComponent);
component = fixture.componentInstance;
element = fixture.debugElement.nativeElement;
component.page = 1;
component.size = 10;
component.count = 100;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should contain valid inputs', () => {
expect(component.page).toEqual(1);
expect(component.size).toEqual(10);
expect(component.count).toEqual(100);
});
it('should change page', () => {
const input = element.querySelector('input');
input.value = '5';
input.dispatchEvent(new Event('input'));
expect(component.page).toEqual(5);
});
it('should disable prev button', () => {
const prev: HTMLButtonElement = element.querySelector('.pagination__btn_prev');
expect(prev.disabled).toBeTruthy();
});
it('should disable next button', () => {
const next: HTMLButtonElement = element.querySelector('.pagination__btn_next');
component.size = 100;
fixture.detectChanges();
expect(next.disabled).toBeTruthy();
});
});
| 1,611
| 28.309091
| 83
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table-pagination/table-pagination.component.ts
|
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'cd-table-pagination',
templateUrl: './table-pagination.component.html',
styleUrls: ['./table-pagination.component.scss']
})
export class TablePaginationComponent {
private _size = 0;
private _count = 0;
private _page = 1;
pages: any;
@Input()
set size(value: number) {
this._size = value;
this.pages = this.calcPages();
}
get size(): number {
return this._size;
}
@Input()
set page(value: number) {
this._page = value;
}
get page(): number {
return this._page;
}
@Input()
set count(value: number) {
this._count = value;
}
get count(): number {
return this._count;
}
get totalPages(): number {
const count = this.size < 1 ? 1 : Math.ceil(this._count / this._size);
return Math.max(count || 0, 1);
}
@Output() pageChange: EventEmitter<any> = new EventEmitter();
canPrevious(): boolean {
return this._page > 1;
}
canNext(): boolean {
return this._page < this.totalPages;
}
prevPage(): void {
this.selectPage(this._page - 1);
}
nextPage(): void {
this.selectPage(this._page + 1);
}
selectPage(page: number): void {
if (page > 0 && page <= this.totalPages && page !== this.page) {
this._page = page;
this.pageChange.emit({
page
});
} else if (page > 0 && page >= this.totalPages) {
this._page = this.totalPages;
this.pageChange.emit({
page: this.totalPages
});
}
}
calcPages(page?: number): any[] {
const pages = [];
let startPage = 1;
let endPage = this.totalPages;
const maxSize = 5;
const isMaxSized = maxSize < this.totalPages;
page = page || this.page;
if (isMaxSized) {
startPage = page - Math.floor(maxSize / 2);
endPage = page + Math.floor(maxSize / 2);
if (startPage < 1) {
startPage = 1;
endPage = Math.min(startPage + maxSize - 1, this.totalPages);
} else if (endPage > this.totalPages) {
startPage = Math.max(this.totalPages - maxSize + 1, 1);
endPage = this.totalPages;
}
}
for (let num = startPage; num <= endPage; num++) {
pages.push({
number: num,
text: <string>(<any>num)
});
}
return pages;
}
}
| 2,348
| 20.162162
| 74
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table/table.component.html
|
<div class="dataTables_wrapper">
<div *ngIf="onlyActionHeader"
class="dataTables_header clearfix">
<div class="cd-datatable-actions">
<ng-content select=".only-table-actions"></ng-content>
</div>
</div>
<div class="dataTables_header clearfix"
*ngIf="toolHeader">
<!-- actions -->
<div class="cd-datatable-actions">
<ng-content select=".table-actions"></ng-content>
</div>
<!-- end actions -->
<!-- column filters -->
<div *ngIf="columnFilters.length !== 0"
class="btn-group widget-toolbar">
<div ngbDropdown
placement="bottom-right"
class="tc_filter_name">
<button ngbDropdownToggle
class="btn btn-light"
title="Filter">
<i [ngClass]="[icons.large, icons.filter]"></i>
{{ selectedFilter.column.name }}
</button>
<div ngbDropdownMenu>
<ng-container *ngFor="let filter of columnFilters">
<button ngbDropdownItem
(click)="onSelectFilter(filter); false">{{ filter.column.name }}</button>
</ng-container>
</div>
</div>
<div ngbDropdown
placement="bottom-right"
class="tc_filter_option">
<button ngbDropdownToggle
class="btn btn-light"
[class.disabled]="selectedFilter.options.length === 0">
{{ selectedFilter.value ? selectedFilter.value.formatted: 'Any' }}
</button>
<div ngbDropdownMenu>
<ng-container *ngFor="let option of selectedFilter.options">
<button ngbDropdownItem
(click)="onChangeFilter(selectedFilter, option); false">
{{ option.formatted }}
<i *ngIf="selectedFilter.value !== undefined && (selectedFilter.value.raw === option.raw)"
[ngClass]="[icons.check]"></i>
</button>
</ng-container>
</div>
</div>
</div>
<!-- end column filters -->
<!-- search -->
<div class="input-group search"
*ngIf="searchField">
<span class="input-group-text">
<i [ngClass]="[icons.search]"></i>
</span>
<input aria-label="search"
class="form-control"
type="text"
[(ngModel)]="search"
(keyup)="updateFilter()">
<button type="button"
class="btn btn-light"
title="Clear"
(click)="onClearSearch()">
<i class="icon-prepend {{ icons.destroy }}"></i>
</button>
</div>
<!-- end search -->
<!-- pagination limit -->
<div class="input-group dataTables_paginate"
*ngIf="limit">
<input aria-label="table pagination"
class="form-control"
type="number"
min="1"
max="9999"
[value]="userConfig.limit"
(click)="setLimit($event)"
(keyup)="setLimit($event)"
(blur)="setLimit($event)">
</div>
<!-- end pagination limit-->
<!-- show hide columns -->
<div class="widget-toolbar">
<div ngbDropdown
autoClose="outside"
class="tc_menuitem">
<button ngbDropdownToggle
class="btn btn-light tc_columnBtn"
title="toggle columns">
<i [ngClass]="[icons.large, icons.table]"></i>
</button>
<div ngbDropdownMenu>
<ng-container *ngFor="let column of columns">
<button ngbDropdownItem
*ngIf="column.name !== ''"
(click)="toggleColumn(column); false;">
<div class="custom-control custom-checkbox py-0">
<input class="custom-control-input"
type="checkbox"
[name]="column.prop"
id="{{ column.prop }}{{ tableName }}"
[checked]="!column.isHidden">
<label class="custom-control-label"
for="{{ column.prop }}{{ tableName }}">{{ column.name }}</label>
</div>
</button>
</ng-container>
</div>
</div>
</div>
<!-- end show hide columns -->
<!-- refresh button -->
<div class="widget-toolbar tc_refreshBtn"
*ngIf="fetchData.observers.length > 0">
<button type="button"
[class]="'btn btn-' + status.type"
[ngbTooltip]="status.msg"
(click)="refreshBtn()"
title="Refresh">
<i [ngClass]="[icons.large, icons.refresh]"
[class.fa-spin]="updating || loadingIndicator"></i>
</button>
</div>
<!-- end refresh button -->
</div>
<div class="dataTables_header clearfix"
*ngIf="toolHeader && columnFiltered">
<!-- filter chips for column filters -->
<div class="filter-chips">
<span *ngFor="let filter of columnFilters">
<span *ngIf="filter.value"
class="badge badge-info me-2">
<span class="me-2">{{ filter.column.name }}: {{ filter.value.formatted }}</span>
<a class="badge-remove"
(click)="onChangeFilter(filter); false">
<i [ngClass]="[icons.destroy]"
aria-hidden="true"></i>
</a>
</span>
</span>
<a class="tc_clearSelections"
href=""
(click)="onClearFilters(); false">
<ng-container i18n>Clear filters</ng-container>
</a>
</div>
<!-- end filter chips for column filters -->
</div>
<ngx-datatable #table
class="bootstrap cd-datatable"
[cssClasses]="paginationClasses"
[selectionType]="selectionType"
[selected]="selection.selected"
(select)="onSelect($event)"
[sorts]="userConfig.sorts"
(sort)="changeSorting($event)"
[columns]="tableColumns"
[columnMode]="columnMode"
[rows]="rows"
[rowClass]="getRowClass()"
[headerHeight]="header ? 'auto' : 0"
[footerHeight]="footer ? 'auto' : 0"
[count]="count"
[externalPaging]="serverSide"
[externalSorting]="serverSide"
[limit]="userConfig.limit > 0 ? userConfig.limit : undefined"
[offset]="userConfig.offset >= 0 ? userConfig.offset : 0"
(page)="changePage($event)"
[loadingIndicator]="loadingIndicator"
[rowIdentity]="rowIdentity()"
[rowHeight]="'auto'">
<!-- Row Selection Template-->
<ng-template #rowSelectionTpl
let-value="value"
let-isSelected="isSelected"
ngx-datatable-cell-template>
<input type="checkbox"
[attr.aria-label]="isSelected ? 'selected' : 'select'"
[checked]="isSelected"
class="cd-datatable-checkbox" />
</ng-template>
<!-- Row Detail Template -->
<ngx-datatable-row-detail rowHeight="auto"
#detailRow>
<ng-template let-row="row"
let-expanded="expanded"
ngx-datatable-row-detail-template>
<!-- Table Details -->
<ng-content select="[cdTableDetail]"></ng-content>
</ng-template>
</ngx-datatable-row-detail>
<ngx-datatable-footer>
<ng-template ngx-datatable-footer-template
let-rowCount="rowCount"
let-pageSize="pageSize"
let-selectedCount="selectedCount"
let-curPage="curPage"
let-offset="offset"
let-isVisible="isVisible">
<div class="page-count">
<span *ngIf="selectionType">
{{ selectedCount }} <ng-container i18n="X selected">selected</ng-container> /
</span>
<!-- rowCount might have different semantics with or without serverSide.
We treat serverSide (backend-driven tables) as a specific case.
-->
<span *ngIf="!serverSide else serverSideTpl">
<span *ngIf="rowCount != data?.length">
{{ rowCount }} <ng-container i18n="X found">found</ng-container> /
</span>
{{ data?.length || 0 }} <ng-container i18n="X total">total</ng-container>
</span>
<ng-template #serverSideTpl>
{{ data?.length || 0 }} <ng-container i18n="X found">found</ng-container> /
{{ rowCount }} <ng-container i18n="X total">total</ng-container>
</ng-template>
</div>
<cd-table-pagination [page]="curPage"
[size]="pageSize"
[count]="rowCount"
[hidden]="!((rowCount / pageSize) > 1)"
(pageChange)="table.onFooterPage($event)"></cd-table-pagination>
</ng-template>
</ngx-datatable-footer>
</ngx-datatable>
</div>
<!-- cell templates that can be accessed from outside -->
<ng-template #tableCellBoldTpl
let-value="value">
<strong>{{ value }}</strong>
</ng-template>
<ng-template #sparklineTpl
let-row="row"
let-value="value">
<cd-sparkline [data]="value"
[isBinary]="row.cdIsBinary"></cd-sparkline>
</ng-template>
<ng-template #routerLinkTpl
let-row="row"
let-value="value">
<a [routerLink]="[row.cdLink]"
[queryParams]="row.cdParams">{{ value }}</a>
</ng-template>
<ng-template #checkIconTpl
let-value="value">
<i [ngClass]="[icons.check]"
[hidden]="!(value | boolean)"></i>
</ng-template>
<ng-template #perSecondTpl
let-row="row"
let-value="value">
{{ value | dimless }} /s
</ng-template>
<ng-template #executingTpl
let-column="column"
let-row="row"
let-value="value">
<i [ngClass]="[icons.spinner, icons.spin]"
*ngIf="row.cdExecuting"></i>
<span [ngClass]="column?.customTemplateConfig?.valueClass">
{{ value }}
</span>
<span *ngIf="row.cdExecuting"
[ngClass]="column?.customTemplateConfig?.executingClass ? column.customTemplateConfig.executingClass : 'text-muted italic'">({{ row.cdExecuting }})</span>
</ng-template>
<ng-template #classAddingTpl
let-value="value">
<span class="{{ value | pipeFunction:useCustomClass:this }}">{{ value }}</span>
</ng-template>
<ng-template #badgeTpl
let-column="column"
let-value="value">
<span *ngFor="let item of (value | array); last as last">
<span class="badge"
[ngClass]="(column?.customTemplateConfig?.map && column?.customTemplateConfig?.map[item]?.class) ? column.customTemplateConfig.map[item].class : (column?.customTemplateConfig?.class ? column.customTemplateConfig.class : 'badge-primary')"
*ngIf="(column?.customTemplateConfig?.map && column?.customTemplateConfig?.map[item]?.value) ? column.customTemplateConfig.map[item].value : column?.customTemplateConfig?.prefix ? column.customTemplateConfig.prefix + item : item">
{{ (column?.customTemplateConfig?.map && column?.customTemplateConfig?.map[item]?.value) ? column.customTemplateConfig.map[item].value : column?.customTemplateConfig?.prefix ? column.customTemplateConfig.prefix + item : item }}
</span>
<span *ngIf="!last"> </span>
</span>
</ng-template>
<ng-template #mapTpl
let-column="column"
let-value="value">
<span>{{ value | map:column?.customTemplateConfig }}</span>
</ng-template>
<ng-template #truncateTpl
let-column="column"
let-value="value">
<span data-toggle="tooltip"
[title]="value">{{ value | truncate:column?.customTemplateConfig?.length:column?.customTemplateConfig?.omission }}</span>
</ng-template>
<ng-template #rowDetailsTpl
let-row="row"
let-isExpanded="expanded"
ngx-datatable-cell-template>
<a href="javascript:void(0)"
[class.expand-collapse-icon-right]="!isExpanded"
[class.expand-collapse-icon-down]="isExpanded"
class="expand-collapse-icon tc_expand-collapse"
title="Expand/Collapse Row"
i18n-title
(click)="toggleExpandRow(row, isExpanded, $event)">
</a>
</ng-template>
<ng-template #timeAgoTpl
let-value="value">
<span data-toggle="tooltip"
[title]="value | cdDate">{{ value | relativeDate }}</span>
</ng-template>
| 12,585
| 35.80117
| 247
|
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table/table.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbDropdownModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import _ from 'lodash';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { ComponentsModule } from '~/app/shared/components/components.module';
import { CellTemplate } from '~/app/shared/enum/cell-template.enum';
import { CdTableColumnFilter } from '~/app/shared/models/cd-table-column-filter';
import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { PipesModule } from '~/app/shared/pipes/pipes.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { TablePaginationComponent } from '../table-pagination/table-pagination.component';
import { TableComponent } from './table.component';
describe('TableComponent', () => {
let component: TableComponent;
let fixture: ComponentFixture<TableComponent>;
const createFakeData = (n: number) => {
const data = [];
for (let i = 0; i < n; i++) {
data.push({
a: i,
b: i * 10,
c: !!(i % 2)
});
}
return data;
};
const clearLocalStorage = () => {
component.localStorage.clear();
};
configureTestBed({
declarations: [TableComponent, TablePaginationComponent],
imports: [
BrowserAnimationsModule,
NgxDatatableModule,
NgxPipeFunctionModule,
FormsModule,
ComponentsModule,
RouterTestingModule,
NgbDropdownModule,
PipesModule,
NgbTooltipModule
]
});
beforeEach(() => {
fixture = TestBed.createComponent(TableComponent);
component = fixture.componentInstance;
component.data = createFakeData(10);
component.localColumns = component.columns = [
{ prop: 'a', name: 'Index', filterable: true },
{ prop: 'b', name: 'Index times ten' },
{ prop: 'c', name: 'Odd?', filterable: true }
];
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should force an identifier', () => {
component.identifier = 'x';
component.forceIdentifier = true;
component.ngOnInit();
expect(component.identifier).toBe('x');
expect(component.sorts[0].prop).toBe('a');
expect(component.sorts).toEqual(component.createSortingDefinition('a'));
});
it('should have rows', () => {
component.useData();
expect(component.data.length).toBe(10);
expect(component.rows.length).toBe(component.data.length);
});
it('should have an int in setLimit parsing a string', () => {
expect(component.limit).toBe(10);
expect(component.limit).toEqual(jasmine.any(Number));
const e = { target: { value: '1' } };
component.setLimit(e);
expect(component.userConfig.limit).toBe(1);
expect(component.userConfig.limit).toEqual(jasmine.any(Number));
e.target.value = '-20';
component.setLimit(e);
expect(component.userConfig.limit).toBe(1);
});
it('should prevent propagation of mouseenter event', (done) => {
let wasCalled = false;
const mouseEvent = new MouseEvent('mouseenter');
mouseEvent.stopPropagation = () => {
wasCalled = true;
};
spyOn(component.table.element, 'addEventListener').and.callFake((eventName, fn) => {
fn(mouseEvent);
expect(eventName).toBe('mouseenter');
expect(wasCalled).toBe(true);
done();
});
component.ngOnInit();
});
it('should call updateSelection on init', () => {
component.updateSelection.subscribe((selection: CdTableSelection) => {
expect(selection.hasSelection).toBeFalsy();
expect(selection.hasSingleSelection).toBeFalsy();
expect(selection.hasMultiSelection).toBeFalsy();
expect(selection.selected.length).toBe(0);
});
component.ngOnInit();
});
describe('test column filtering', () => {
let filterIndex: CdTableColumnFilter;
let filterOdd: CdTableColumnFilter;
let filterCustom: CdTableColumnFilter;
const expectColumnFilterCreated = (
filter: CdTableColumnFilter,
prop: string,
options: string[],
value?: { raw: string; formatted: string }
) => {
expect(filter.column.prop).toBe(prop);
expect(_.map(filter.options, 'raw')).toEqual(options);
expect(filter.value).toEqual(value);
};
const expectColumnFiltered = (
changes: { filter: CdTableColumnFilter; value?: string }[],
results: any[],
search: string = ''
) => {
component.search = search;
_.forEach(changes, (change) => {
component.onChangeFilter(
change.filter,
change.value ? { raw: change.value, formatted: change.value } : undefined
);
});
expect(component.rows).toEqual(results);
component.onClearSearch();
component.onClearFilters();
};
describe('with visible columns', () => {
beforeEach(() => {
component.initColumnFilters();
component.updateColumnFilterOptions();
filterIndex = component.columnFilters[0];
filterOdd = component.columnFilters[1];
});
it('should have filters initialized', () => {
expect(component.columnFilters.length).toBe(2);
expectColumnFilterCreated(
filterIndex,
'a',
_.map(component.data, (row) => _.toString(row.a))
);
expectColumnFilterCreated(filterOdd, 'c', ['false', 'true']);
});
it('should add filters', () => {
// single
expectColumnFiltered([{ filter: filterIndex, value: '1' }], [{ a: 1, b: 10, c: true }]);
// multiple
expectColumnFiltered(
[
{ filter: filterOdd, value: 'false' },
{ filter: filterIndex, value: '2' }
],
[{ a: 2, b: 20, c: false }]
);
// Clear should work
expect(component.rows).toEqual(component.data);
});
it('should remove filters', () => {
// single
expectColumnFiltered(
[
{ filter: filterOdd, value: 'true' },
{ filter: filterIndex, value: '1' },
{ filter: filterIndex, value: undefined }
],
[
{ a: 1, b: 10, c: true },
{ a: 3, b: 30, c: true },
{ a: 5, b: 50, c: true },
{ a: 7, b: 70, c: true },
{ a: 9, b: 90, c: true }
]
);
// multiple
expectColumnFiltered(
[
{ filter: filterOdd, value: 'true' },
{ filter: filterIndex, value: '1' },
{ filter: filterIndex, value: undefined },
{ filter: filterOdd, value: undefined }
],
component.data
);
// a selected filter should be removed if it's selected again
expectColumnFiltered(
[
{ filter: filterOdd, value: 'true' },
{ filter: filterIndex, value: '1' },
{ filter: filterIndex, value: '1' }
],
[
{ a: 1, b: 10, c: true },
{ a: 3, b: 30, c: true },
{ a: 5, b: 50, c: true },
{ a: 7, b: 70, c: true },
{ a: 9, b: 90, c: true }
]
);
});
it('should search from filtered rows', () => {
expectColumnFiltered(
[{ filter: filterOdd, value: 'true' }],
[{ a: 9, b: 90, c: true }],
'9'
);
// Clear should work
expect(component.rows).toEqual(component.data);
});
});
describe('with custom columns', () => {
beforeEach(() => {
// create a new additional column in data
for (let i = 0; i < component.data.length; i++) {
const row = component.data[i];
row['d'] = row.a;
}
// create a custom column filter
component.extraFilterableColumns = [
{
name: 'd less than 5',
prop: 'd',
filterOptions: ['yes', 'no'],
filterInitValue: 'yes',
filterPredicate: (row, value) => {
if (value === 'yes') {
return row.d < 5;
} else {
return row.d >= 5;
}
}
}
];
component.initColumnFilters();
component.updateColumnFilterOptions();
filterIndex = component.columnFilters[0];
filterOdd = component.columnFilters[1];
filterCustom = component.columnFilters[2];
});
it('should have filters initialized', () => {
expect(component.columnFilters.length).toBe(3);
expectColumnFilterCreated(filterCustom, 'd', ['yes', 'no'], {
raw: 'yes',
formatted: 'yes'
});
component.useData();
expect(component.rows).toEqual(_.slice(component.data, 0, 5));
});
it('should remove filters', () => {
expectColumnFiltered([{ filter: filterCustom, value: 'no' }], _.slice(component.data, 5));
});
});
});
describe('test search', () => {
const expectSearch = (keyword: string, expectedResult: object[]) => {
component.search = keyword;
component.updateFilter();
expect(component.rows).toEqual(expectedResult);
component.onClearSearch();
};
describe('searchableObjects', () => {
const testObject = {
obj: {
min: 8,
max: 123
}
};
beforeEach(() => {
component.data = [testObject];
component.localColumns = [{ prop: 'obj', name: 'Object' }];
});
it('should not search through objects as default case', () => {
expect(component.searchableObjects).toBe(false);
expectSearch('8', []);
});
it('should search through objects if searchableObjects is set to true', () => {
component.searchableObjects = true;
expectSearch('28', []);
expectSearch('8', [testObject]);
expectSearch('123', [testObject]);
expectSearch('max', [testObject]);
});
});
it('should find a particular number', () => {
expectSearch('5', [{ a: 5, b: 50, c: true }]);
expectSearch('9', [{ a: 9, b: 90, c: true }]);
});
it('should find boolean values', () => {
expectSearch('true', [
{ a: 1, b: 10, c: true },
{ a: 3, b: 30, c: true },
{ a: 5, b: 50, c: true },
{ a: 7, b: 70, c: true },
{ a: 9, b: 90, c: true }
]);
expectSearch('false', [
{ a: 0, b: 0, c: false },
{ a: 2, b: 20, c: false },
{ a: 4, b: 40, c: false },
{ a: 6, b: 60, c: false },
{ a: 8, b: 80, c: false }
]);
});
it('should test search keyword preparation', () => {
const prepare = TableComponent.prepareSearch;
const expected = ['a', 'b', 'c'];
expect(prepare('a b c')).toEqual(expected);
expect(prepare('a,, b,, c')).toEqual(expected);
expect(prepare('a,,,, b,,, c')).toEqual(expected);
expect(prepare('a+b c')).toEqual(['a+b', 'c']);
expect(prepare('a,,,+++b,,, c')).toEqual(['a+++b', 'c']);
expect(prepare('"a b c" "d e f", "g, h i"')).toEqual(['a+b+c', 'd+e++f', 'g+h+i']);
});
it('should search for multiple values', () => {
expectSearch('2 20 false', [{ a: 2, b: 20, c: false }]);
expectSearch('false 2', [{ a: 2, b: 20, c: false }]);
});
it('should filter by column', () => {
expectSearch('index:5', [{ a: 5, b: 50, c: true }]);
expectSearch('times:50', [{ a: 5, b: 50, c: true }]);
expectSearch('times:50 index:5', [{ a: 5, b: 50, c: true }]);
expectSearch('Odd?:true', [
{ a: 1, b: 10, c: true },
{ a: 3, b: 30, c: true },
{ a: 5, b: 50, c: true },
{ a: 7, b: 70, c: true },
{ a: 9, b: 90, c: true }
]);
component.data = createFakeData(100);
expectSearch('index:1 odd:true times:110', [{ a: 11, b: 110, c: true }]);
});
it('should search through arrays', () => {
component.localColumns = [
{ prop: 'a', name: 'Index' },
{ prop: 'b', name: 'ArrayColumn' }
];
component.data = [
{ a: 1, b: ['foo', 'bar'] },
{ a: 2, b: ['baz', 'bazinga'] }
];
expectSearch('bar', [{ a: 1, b: ['foo', 'bar'] }]);
expectSearch('arraycolumn:bar arraycolumn:foo', [{ a: 1, b: ['foo', 'bar'] }]);
expectSearch('arraycolumn:baz arraycolumn:inga', [{ a: 2, b: ['baz', 'bazinga'] }]);
component.data = [
{ a: 1, b: [1, 2] },
{ a: 2, b: [3, 4] }
];
expectSearch('arraycolumn:1 arraycolumn:2', [{ a: 1, b: [1, 2] }]);
});
it('should search with spaces', () => {
const expectedResult = [{ a: 2, b: 20, c: false }];
expectSearch(`'Index times ten':20`, expectedResult);
expectSearch('index+times+ten:20', expectedResult);
});
it('should filter results although column name is incomplete', () => {
component.data = createFakeData(3);
expectSearch(`'Index times ten'`, []);
expectSearch(`'Ind'`, []);
expectSearch(`'Ind:'`, [
{ a: 0, b: 0, c: false },
{ a: 1, b: 10, c: true },
{ a: 2, b: 20, c: false }
]);
});
it('should search if column name is incomplete', () => {
const expectedData = [
{ a: 0, b: 0, c: false },
{ a: 1, b: 10, c: true },
{ a: 2, b: 20, c: false }
];
component.data = _.clone(expectedData);
expectSearch('inde', []);
expectSearch('index:', expectedData);
expectSearch('index times te', []);
});
it('should restore full table after search', () => {
component.useData();
expect(component.rows.length).toBe(10);
component.search = '3';
component.updateFilter();
expect(component.rows.length).toBe(1);
component.onClearSearch();
expect(component.rows.length).toBe(10);
});
it('should work with undefined data', () => {
component.data = undefined;
component.search = '3';
component.updateFilter();
expect(component.rows).toBeUndefined();
});
});
describe('after ngInit', () => {
const toggleColumn = (prop: string, checked: boolean) => {
component.toggleColumn({
prop: prop,
isHidden: checked
});
};
const equalStorageConfig = () => {
expect(JSON.stringify(component.userConfig)).toBe(
component.localStorage.getItem(component.tableName)
);
};
beforeEach(() => {
component.ngOnInit();
});
it('should have updated the column definitions', () => {
expect(component.localColumns[0].flexGrow).toBe(1);
expect(component.localColumns[1].flexGrow).toBe(2);
expect(component.localColumns[2].flexGrow).toBe(2);
expect(component.localColumns[2].resizeable).toBe(false);
});
it('should have table columns', () => {
expect(component.tableColumns.length).toBe(3);
expect(component.tableColumns).toEqual(component.localColumns);
});
it('should have a unique identifier which it searches for', () => {
expect(component.identifier).toBe('a');
expect(component.userConfig.sorts[0].prop).toBe('a');
expect(component.userConfig.sorts).toEqual(component.createSortingDefinition('a'));
equalStorageConfig();
});
it('should remove column "a"', () => {
expect(component.userConfig.sorts[0].prop).toBe('a');
toggleColumn('a', false);
expect(component.userConfig.sorts[0].prop).toBe('b');
expect(component.tableColumns.length).toBe(2);
equalStorageConfig();
});
it('should not be able to remove all columns', () => {
expect(component.userConfig.sorts[0].prop).toBe('a');
toggleColumn('a', false);
toggleColumn('b', false);
toggleColumn('c', false);
expect(component.userConfig.sorts[0].prop).toBe('c');
expect(component.tableColumns.length).toBe(1);
equalStorageConfig();
});
it('should enable column "a" again', () => {
expect(component.userConfig.sorts[0].prop).toBe('a');
toggleColumn('a', false);
toggleColumn('a', true);
expect(component.userConfig.sorts[0].prop).toBe('b');
expect(component.tableColumns.length).toBe(3);
equalStorageConfig();
});
it('should toggle on off columns', () => {
for (const column of component.columns) {
component.toggleColumn(column);
expect(column.isHidden).toBeTruthy();
component.toggleColumn(column);
expect(column.isHidden).toBeFalsy();
}
});
afterEach(() => {
clearLocalStorage();
});
});
describe('test cell transformations', () => {
interface ExecutingTemplateConfig {
valueClass?: string;
executingClass?: string;
}
const testExecutingTemplate = (templateConfig?: ExecutingTemplateConfig) => {
const state = 'updating';
const value = component.data[0].a;
component.autoReload = -1;
component.columns[0].cellTransformation = CellTemplate.executing;
if (templateConfig) {
component.columns[0].customTemplateConfig = templateConfig;
}
component.data[0].cdExecuting = state;
fixture.detectChanges();
const elements = fixture.debugElement
.query(By.css('datatable-body-row datatable-body-cell'))
.queryAll(By.css('span'));
expect(elements.length).toBe(2);
// Value
const valueElement = elements[0];
if (templateConfig?.valueClass) {
templateConfig.valueClass.split(' ').forEach((clz) => {
expect(valueElement.classes).toHaveProperty(clz);
});
}
expect(valueElement.nativeElement.textContent.trim()).toBe(`${value}`);
// Executing state
const executingElement = elements[1];
if (templateConfig?.executingClass) {
templateConfig.executingClass.split(' ').forEach((clz) => {
expect(executingElement.classes).toHaveProperty(clz);
});
}
expect(executingElement.nativeElement.textContent.trim()).toBe(`(${state})`);
};
it.only('should display executing template', () => {
testExecutingTemplate();
});
it.only('should display executing template with custom classes', () => {
testExecutingTemplate({ valueClass: 'a b', executingClass: 'c d' });
});
});
describe('reload data', () => {
beforeEach(() => {
component.ngOnInit();
component.data = [];
component['updating'] = false;
});
it('should call fetchData callback function', () => {
component.fetchData.subscribe((context: any) => {
expect(context instanceof CdTableFetchDataContext).toBeTruthy();
});
component.reloadData();
});
it('should call error function', () => {
component.data = createFakeData(5);
component.fetchData.subscribe((context: any) => {
context.error();
expect(component.status.type).toBe('danger');
expect(component.data.length).toBe(0);
expect(component.loadingIndicator).toBeFalsy();
expect(component['updating']).toBeFalsy();
});
component.reloadData();
});
it('should call error function with custom config', () => {
component.data = createFakeData(10);
component.fetchData.subscribe((context: any) => {
context.errorConfig.resetData = false;
context.errorConfig.displayError = false;
context.error();
expect(component.status.type).toBe('danger');
expect(component.data.length).toBe(10);
expect(component.loadingIndicator).toBeFalsy();
expect(component['updating']).toBeFalsy();
});
component.reloadData();
});
it('should update selection on refresh - "onChange"', () => {
spyOn(component, 'onSelect').and.callThrough();
component.data = createFakeData(10);
component.selection.selected = [_.clone(component.data[1])];
component.updateSelectionOnRefresh = 'onChange';
component.updateSelected();
expect(component.onSelect).toHaveBeenCalledTimes(0);
component.data[1].d = !component.data[1].d;
component.updateSelected();
expect(component.onSelect).toHaveBeenCalled();
});
it('should update selection on refresh - "always"', () => {
spyOn(component, 'onSelect').and.callThrough();
component.data = createFakeData(10);
component.selection.selected = [_.clone(component.data[1])];
component.updateSelectionOnRefresh = 'always';
component.updateSelected();
expect(component.onSelect).toHaveBeenCalled();
component.data[1].d = !component.data[1].d;
component.updateSelected();
expect(component.onSelect).toHaveBeenCalled();
});
it('should update selection on refresh - "never"', () => {
spyOn(component, 'onSelect').and.callThrough();
component.data = createFakeData(10);
component.selection.selected = [_.clone(component.data[1])];
component.updateSelectionOnRefresh = 'never';
component.updateSelected();
expect(component.onSelect).toHaveBeenCalledTimes(0);
component.data[1].d = !component.data[1].d;
component.updateSelected();
expect(component.onSelect).toHaveBeenCalledTimes(0);
});
afterEach(() => {
clearLocalStorage();
});
});
describe('useCustomClass', () => {
beforeEach(() => {
component.customCss = {
'badge badge-danger': 'active',
'secret secret-number': 123.456,
btn: (v) => _.isString(v) && v.startsWith('http'),
secure: (v) => _.isString(v) && v.startsWith('https')
};
});
it('should throw an error if custom classes are not set', () => {
component.customCss = undefined;
expect(() => component.useCustomClass('active')).toThrowError('Custom classes are not set!');
});
it('should not return any class', () => {
['', 'something', 123, { complex: 1 }, [1, 2, 3]].forEach((value) =>
expect(component.useCustomClass(value)).toBe(undefined)
);
});
it('should match a string and return the corresponding class', () => {
expect(component.useCustomClass('active')).toBe('badge badge-danger');
});
it('should match a number and return the corresponding class', () => {
expect(component.useCustomClass(123.456)).toBe('secret secret-number');
});
it('should match against a function and return the corresponding class', () => {
expect(component.useCustomClass('http://no.ssl')).toBe('btn');
});
it('should match against multiple functions and return the corresponding classes', () => {
expect(component.useCustomClass('https://secure.it')).toBe('btn secure');
});
});
describe('test expand and collapse feature', () => {
beforeEach(() => {
spyOn(component.setExpandedRow, 'emit');
component.table = {
rowDetail: { collapseAllRows: jest.fn(), toggleExpandRow: jest.fn() }
} as any;
// Setup table
component.identifier = 'a';
component.data = createFakeData(10);
// Select item
component.expanded = _.clone(component.data[1]);
});
describe('update expanded on refresh', () => {
const updateExpendedOnState = (state: 'always' | 'never' | 'onChange') => {
component.updateExpandedOnRefresh = state;
component.updateExpanded();
};
beforeEach(() => {
// Mock change
component.data[1].b = 'test';
});
it('refreshes "always"', () => {
updateExpendedOnState('always');
expect(component.expanded.b).toBe('test');
expect(component.setExpandedRow.emit).toHaveBeenCalled();
});
it('refreshes "onChange"', () => {
updateExpendedOnState('onChange');
expect(component.expanded.b).toBe('test');
expect(component.setExpandedRow.emit).toHaveBeenCalled();
});
it('does not refresh "onChange" if data is equal', () => {
component.data[1].b = 10; // Reverts change
updateExpendedOnState('onChange');
expect(component.expanded.b).toBe(10);
expect(component.setExpandedRow.emit).not.toHaveBeenCalled();
});
it('"never" refreshes', () => {
updateExpendedOnState('never');
expect(component.expanded.b).toBe(10);
expect(component.setExpandedRow.emit).not.toHaveBeenCalled();
});
});
it('should open the table details and close other expanded rows', () => {
component.toggleExpandRow(component.expanded, false, new Event('click'));
expect(component.expanded).toEqual({ a: 1, b: 10, c: true });
expect(component.table.rowDetail.collapseAllRows).toHaveBeenCalled();
expect(component.setExpandedRow.emit).toHaveBeenCalledWith(component.expanded);
expect(component.table.rowDetail.toggleExpandRow).toHaveBeenCalled();
});
it('should close the current table details expansion', () => {
component.toggleExpandRow(component.expanded, true, new Event('click'));
expect(component.expanded).toBeUndefined();
expect(component.setExpandedRow.emit).toHaveBeenCalledWith(undefined);
expect(component.table.rowDetail.toggleExpandRow).toHaveBeenCalled();
});
it('should not select the row when the row is expanded', () => {
expect(component.selection.selected).toEqual([]);
component.toggleExpandRow(component.data[1], false, new Event('click'));
expect(component.selection.selected).toEqual([]);
});
it('should not change selection when expanding different row', () => {
expect(component.selection.selected).toEqual([]);
expect(component.expanded).toEqual(component.data[1]);
component.selection.selected = [component.data[2]];
component.toggleExpandRow(component.data[3], false, new Event('click'));
expect(component.selection.selected).toEqual([component.data[2]]);
expect(component.expanded).toEqual(component.data[3]);
});
});
});
| 26,419
| 32.742018
| 99
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/datatable/table/table.component.ts
|
import {
AfterContentChecked,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
PipeTransform,
SimpleChanges,
TemplateRef,
ViewChild
} from '@angular/core';
import {
DatatableComponent,
getterForProp,
SortDirection,
SortPropDir,
TableColumnProp
} from '@swimlane/ngx-datatable';
import _ from 'lodash';
import { Observable, of, Subject, Subscription } from 'rxjs';
import { TableStatus } from '~/app/shared/classes/table-status';
import { CellTemplate } from '~/app/shared/enum/cell-template.enum';
import { Icons } from '~/app/shared/enum/icons.enum';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdTableColumnFilter } from '~/app/shared/models/cd-table-column-filter';
import { CdTableColumnFiltersChange } from '~/app/shared/models/cd-table-column-filters-change';
import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context';
import { PageInfo } from '~/app/shared/models/cd-table-paging';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { CdUserConfig } from '~/app/shared/models/cd-user-config';
import { TimerService } from '~/app/shared/services/timer.service';
@Component({
selector: 'cd-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TableComponent implements AfterContentChecked, OnInit, OnChanges, OnDestroy {
@ViewChild(DatatableComponent, { static: true })
table: DatatableComponent;
@ViewChild('tableCellBoldTpl', { static: true })
tableCellBoldTpl: TemplateRef<any>;
@ViewChild('sparklineTpl', { static: true })
sparklineTpl: TemplateRef<any>;
@ViewChild('routerLinkTpl', { static: true })
routerLinkTpl: TemplateRef<any>;
@ViewChild('checkIconTpl', { static: true })
checkIconTpl: TemplateRef<any>;
@ViewChild('perSecondTpl', { static: true })
perSecondTpl: TemplateRef<any>;
@ViewChild('executingTpl', { static: true })
executingTpl: TemplateRef<any>;
@ViewChild('classAddingTpl', { static: true })
classAddingTpl: TemplateRef<any>;
@ViewChild('badgeTpl', { static: true })
badgeTpl: TemplateRef<any>;
@ViewChild('mapTpl', { static: true })
mapTpl: TemplateRef<any>;
@ViewChild('truncateTpl', { static: true })
truncateTpl: TemplateRef<any>;
@ViewChild('timeAgoTpl', { static: true })
timeAgoTpl: TemplateRef<any>;
@ViewChild('rowDetailsTpl', { static: true })
rowDetailsTpl: TemplateRef<any>;
@ViewChild('rowSelectionTpl', { static: true })
rowSelectionTpl: TemplateRef<any>;
// This is the array with the items to be shown.
@Input()
data: any[];
// Each item -> { prop: 'attribute name', name: 'display name' }
@Input()
columns: CdTableColumn[];
// Each item -> { prop: 'attribute name', dir: 'asc'||'desc'}
@Input()
sorts?: SortPropDir[];
// Method used for setting column widths.
@Input()
columnMode? = 'flex';
// Display only actions in header (make sure to disable toolHeader) and use ".only-table-actions"
@Input()
onlyActionHeader? = false;
// Display the tool header, including reload button, pagination and search fields?
@Input()
toolHeader? = true;
// Display search field inside tool header?
@Input()
searchField? = true;
// Display the table header?
@Input()
header? = true;
// Display the table footer?
@Input()
footer? = true;
// Page size to show. Set to 0 to show unlimited number of rows.
@Input()
limit? = 10;
@Input()
maxLimit? = 9999;
// Has the row details?
@Input()
hasDetails = false;
/**
* Auto reload time in ms - per default every 5s
* You can set it to 0, undefined or false to disable the auto reload feature in order to
* trigger 'fetchData' if the reload button is clicked.
* You can set it to a negative number to, on top of disabling the auto reload,
* prevent triggering fetchData when initializing the table.
*/
@Input()
autoReload = 5000;
// Which row property is unique for a row. If the identifier is not specified in any
// column, then the property name of the first column is used. Defaults to 'id'.
@Input()
identifier = 'id';
// If 'true', then the specified identifier is used anyway, although it is not specified
// in any column. Defaults to 'false'.
@Input()
forceIdentifier = false;
// Allows other components to specify which type of selection they want,
// e.g. 'single' or 'multi'.
@Input()
selectionType: string = undefined;
// By default selected item details will be updated on table refresh, if data has changed
@Input()
updateSelectionOnRefresh: 'always' | 'never' | 'onChange' = 'onChange';
// By default expanded item details will be updated on table refresh, if data has changed
@Input()
updateExpandedOnRefresh: 'always' | 'never' | 'onChange' = 'onChange';
@Input()
autoSave = true;
// Enable this in order to search through the JSON of any used object.
@Input()
searchableObjects = false;
// Only needed to set if the classAddingTpl is used
@Input()
customCss?: { [css: string]: number | string | ((any: any) => boolean) };
// Columns that aren't displayed but can be used as filters
@Input()
extraFilterableColumns: CdTableColumn[] = [];
@Input()
status = new TableStatus();
// Support server-side pagination/sorting/etc.
@Input()
serverSide = false;
/*
Only required when serverSide is enabled.
It should be provided by the server via "X-Total-Count" HTTP Header
*/
@Input()
count = 0;
/**
* Should be a function to update the input data if undefined nothing will be triggered
*
* Sometimes it's useful to only define fetchData once.
* Example:
* Usage of multiple tables with data which is updated by the same function
* What happens:
* The function is triggered through one table and all tables will update
*/
@Output()
fetchData = new EventEmitter<CdTableFetchDataContext>();
/**
* This should be defined if you need access to the selection object.
*
* Each time the table selection changes, this will be triggered and
* the new selection object will be sent.
*
* @memberof TableComponent
*/
@Output()
updateSelection = new EventEmitter();
@Output()
setExpandedRow = new EventEmitter();
/**
* This should be defined if you need access to the applied column filters.
*
* Each time the column filters changes, this will be triggered and
* the column filters change event will be sent.
*
* @memberof TableComponent
*/
@Output() columnFiltersChanged = new EventEmitter<CdTableColumnFiltersChange>();
/**
* Use this variable to access the selected row(s).
*/
selection = new CdTableSelection();
/**
* Use this variable to access the expanded row
*/
expanded: any = undefined;
/**
* To prevent making changes to the original columns list, that might change
* how the table is renderer a second time, we now clone that list into a
* local variable and only use the clone.
*/
localColumns: CdTableColumn[];
tableColumns: CdTableColumn[];
icons = Icons;
cellTemplates: {
[key: string]: TemplateRef<any>;
} = {};
search = '';
rows: any[] = [];
loadingIndicator = true;
paginationClasses = {
pagerLeftArrow: Icons.leftArrowDouble,
pagerRightArrow: Icons.rightArrowDouble,
pagerPrevious: Icons.leftArrow,
pagerNext: Icons.rightArrow
};
userConfig: CdUserConfig = {};
tableName: string;
localStorage = window.localStorage;
private saveSubscriber: Subscription;
private reloadSubscriber: Subscription;
private updating = false;
// Internal variable to check if it is necessary to recalculate the
// table columns after the browser window has been resized.
private currentWidth: number;
columnFilters: CdTableColumnFilter[] = [];
selectedFilter: CdTableColumnFilter;
get columnFiltered(): boolean {
return _.some(this.columnFilters, (filter) => {
return filter.value !== undefined;
});
}
constructor(
// private ngZone: NgZone,
private cdRef: ChangeDetectorRef,
private timerService: TimerService
) {}
static prepareSearch(search: string) {
search = search.toLowerCase().replace(/,/g, '');
if (search.match(/['"][^'"]+['"]/)) {
search = search.replace(/['"][^'"]+['"]/g, (match: string) => {
return match.replace(/(['"])([^'"]+)(['"])/g, '$2').replace(/ /g, '+');
});
}
return search.split(' ').filter((word) => word);
}
ngOnInit() {
this.localColumns = _.clone(this.columns);
// debounce reloadData method so that search doesn't run api requests
// for every keystroke
if (this.serverSide) {
this.reloadData = _.debounce(this.reloadData, 1000);
}
// ngx-datatable triggers calculations each time mouse enters a row,
// this will prevent that.
this.table.element.addEventListener('mouseenter', (e) => e.stopPropagation());
this._addTemplates();
if (!this.sorts) {
// Check whether the specified identifier exists.
const exists = _.findIndex(this.localColumns, ['prop', this.identifier]) !== -1;
// Auto-build the sorting configuration. If the specified identifier doesn't exist,
// then use the property of the first column.
this.sorts = this.createSortingDefinition(
exists ? this.identifier : this.localColumns[0].prop + ''
);
// If the specified identifier doesn't exist and it is not forced to use it anyway,
// then use the property of the first column.
if (!exists && !this.forceIdentifier) {
this.identifier = this.localColumns[0].prop + '';
}
}
this.initUserConfig();
this.localColumns.forEach((c) => {
if (c.cellTransformation) {
c.cellTemplate = this.cellTemplates[c.cellTransformation];
}
if (!c.flexGrow) {
c.flexGrow = c.prop + '' === this.identifier ? 1 : 2;
}
if (!c.resizeable) {
c.resizeable = false;
}
});
this.initExpandCollapseColumn(); // If rows have details, add a column to expand or collapse the rows
this.initCheckboxColumn();
this.filterHiddenColumns();
this.initColumnFilters();
this.updateColumnFilterOptions();
// Notify all subscribers to reset their current selection.
this.updateSelection.emit(new CdTableSelection());
// Load the data table content every N ms or at least once.
// Force showing the loading indicator if there are subscribers to the fetchData
// event. This is necessary because it has been set to False in useData() when
// this method was triggered by ngOnChanges().
if (this.fetchData.observers.length > 0) {
this.loadingIndicator = true;
}
if (_.isInteger(this.autoReload) && this.autoReload > 0) {
this.reloadSubscriber = this.timerService
.get(() => of(0), this.autoReload)
.subscribe(() => {
this.reloadData();
});
} else if (!this.autoReload) {
this.reloadData();
} else {
this.useData();
}
}
initUserConfig() {
if (this.autoSave) {
this.tableName = this._calculateUniqueTableName(this.localColumns);
this._loadUserConfig();
this._initUserConfigAutoSave();
}
if (!this.userConfig.limit) {
this.userConfig.limit = this.limit;
}
if (!(this.userConfig.offset >= 0)) {
this.userConfig.offset = this.table.offset;
}
if (!this.userConfig.search) {
this.userConfig.search = this.search;
}
if (!this.userConfig.sorts) {
this.userConfig.sorts = this.sorts;
}
if (!this.userConfig.columns) {
this.updateUserColumns();
} else {
this.userConfig.columns.forEach((col) => {
for (let i = 0; i < this.localColumns.length; i++) {
if (this.localColumns[i].prop === col.prop) {
this.localColumns[i].isHidden = col.isHidden;
}
}
});
}
}
_calculateUniqueTableName(columns: any[]) {
const stringToNumber = (s: string) => {
if (!_.isString(s)) {
return 0;
}
let result = 0;
for (let i = 0; i < s.length; i++) {
result += s.charCodeAt(i) * i;
}
return result;
};
return columns
.reduce(
(result, value, index) =>
(stringToNumber(value.prop) + stringToNumber(value.name)) * (index + 1) + result,
0
)
.toString();
}
_loadUserConfig() {
const loaded = this.localStorage.getItem(this.tableName);
if (loaded) {
this.userConfig = JSON.parse(loaded);
}
}
_initUserConfigAutoSave() {
const source: Observable<any> = new Observable(this._initUserConfigProxy.bind(this));
this.saveSubscriber = source.subscribe(this._saveUserConfig.bind(this));
}
_initUserConfigProxy(observer: Subject<any>) {
this.userConfig = new Proxy(this.userConfig, {
set(config, prop: string, value) {
config[prop] = value;
observer.next(config);
return true;
}
});
}
_saveUserConfig(config: any) {
this.localStorage.setItem(this.tableName, JSON.stringify(config));
}
updateUserColumns() {
this.userConfig.columns = this.localColumns.map((c) => ({
prop: c.prop,
name: c.name,
isHidden: !!c.isHidden
}));
}
/**
* Add a column containing a checkbox if selectionType is 'multiClick'.
*/
initCheckboxColumn() {
if (this.selectionType === 'multiClick') {
this.localColumns.unshift({
prop: undefined,
resizeable: false,
sortable: false,
draggable: false,
checkboxable: false,
canAutoResize: false,
cellClass: 'cd-datatable-checkbox',
cellTemplate: this.rowSelectionTpl,
width: 30
});
}
}
/**
* Add a column to expand and collapse the table row if it 'hasDetails'
*/
initExpandCollapseColumn() {
if (this.hasDetails) {
this.localColumns.unshift({
prop: undefined,
resizeable: false,
sortable: false,
draggable: false,
isHidden: false,
canAutoResize: false,
cellClass: 'cd-datatable-expand-collapse',
width: 40,
cellTemplate: this.rowDetailsTpl
});
}
}
filterHiddenColumns() {
this.tableColumns = this.localColumns.filter((c) => !c.isHidden);
}
initColumnFilters() {
let filterableColumns = _.filter(this.localColumns, { filterable: true });
filterableColumns = [...filterableColumns, ...this.extraFilterableColumns];
this.columnFilters = filterableColumns.map((col: CdTableColumn) => {
return {
column: col,
options: [],
value: col.filterInitValue
? this.createColumnFilterOption(col.filterInitValue, col.pipe)
: undefined
};
});
this.selectedFilter = _.first(this.columnFilters);
}
private createColumnFilterOption(
value: any,
pipe?: PipeTransform
): { raw: string; formatted: string } {
return {
raw: _.toString(value),
formatted: pipe ? pipe.transform(value) : _.toString(value)
};
}
updateColumnFilterOptions() {
// update all possible values in a column
this.columnFilters.forEach((filter) => {
let values: any[] = [];
if (_.isUndefined(filter.column.filterOptions)) {
// only allow types that can be easily converted into string
const pre = _.filter(_.map(this.data, filter.column.prop), (v) => {
return (_.isString(v) && v !== '') || _.isBoolean(v) || _.isFinite(v) || _.isDate(v);
});
values = _.sortedUniq(pre.sort());
} else {
values = filter.column.filterOptions;
}
const options = values.map((v) => this.createColumnFilterOption(v, filter.column.pipe));
// In case a previous value is not available anymore
if (filter.value && _.isUndefined(_.find(options, { raw: filter.value.raw }))) {
filter.value = undefined;
}
filter.options = options;
});
}
onSelectFilter(filter: CdTableColumnFilter) {
this.selectedFilter = filter;
}
onChangeFilter(filter: CdTableColumnFilter, option?: { raw: string; formatted: string }) {
filter.value = _.isEqual(filter.value, option) ? undefined : option;
this.updateFilter();
}
doColumnFiltering() {
const appliedFilters: CdTableColumnFiltersChange['filters'] = [];
let data = [...this.data];
let dataOut: any[] = [];
this.columnFilters.forEach((filter) => {
if (filter.value === undefined) {
return;
}
appliedFilters.push({
name: filter.column.name,
prop: filter.column.prop,
value: filter.value
});
// Separate data to filtered and filtered-out parts.
const parts = _.partition(data, (row) => {
// Use getter from ngx-datatable to handle props like 'sys_api.size'
const valueGetter = getterForProp(filter.column.prop);
const value = valueGetter(row, filter.column.prop);
if (_.isUndefined(filter.column.filterPredicate)) {
// By default, test string equal
return `${value}` === filter.value.raw;
} else {
// Use custom function to filter
return filter.column.filterPredicate(row, filter.value.raw);
}
});
data = parts[0];
dataOut = [...dataOut, ...parts[1]];
});
this.columnFiltersChanged.emit({
filters: appliedFilters,
data: data,
dataOut: dataOut
});
// Remove the selection if previously-selected rows are filtered out.
_.forEach(this.selection.selected, (selectedItem) => {
if (_.find(data, { [this.identifier]: selectedItem[this.identifier] }) === undefined) {
this.selection = new CdTableSelection();
this.onSelect(this.selection);
}
});
return data;
}
ngOnDestroy() {
if (this.reloadSubscriber) {
this.reloadSubscriber.unsubscribe();
}
if (this.saveSubscriber) {
this.saveSubscriber.unsubscribe();
}
}
ngAfterContentChecked() {
// If the data table is not visible, e.g. another tab is active, and the
// browser window gets resized, the table and its columns won't get resized
// automatically if the tab gets visible again.
// https://github.com/swimlane/ngx-datatable/issues/193
// https://github.com/swimlane/ngx-datatable/issues/193#issuecomment-329144543
if (this.table && this.table.element.clientWidth !== this.currentWidth) {
this.currentWidth = this.table.element.clientWidth;
// Recalculate the sizes of the grid.
this.table.recalculate();
// Mark the datatable as changed, Angular's change-detection will
// do the rest for us => the grid will be redrawn.
// Note, the ChangeDetectorRef variable is private, so we need to
// use this workaround to access it and make TypeScript happy.
const cdRef = _.get(this.table, 'cd');
cdRef.markForCheck();
}
}
_addTemplates() {
this.cellTemplates.bold = this.tableCellBoldTpl;
this.cellTemplates.checkIcon = this.checkIconTpl;
this.cellTemplates.sparkline = this.sparklineTpl;
this.cellTemplates.routerLink = this.routerLinkTpl;
this.cellTemplates.perSecond = this.perSecondTpl;
this.cellTemplates.executing = this.executingTpl;
this.cellTemplates.classAdding = this.classAddingTpl;
this.cellTemplates.badge = this.badgeTpl;
this.cellTemplates.map = this.mapTpl;
this.cellTemplates.truncate = this.truncateTpl;
this.cellTemplates.timeAgo = this.timeAgoTpl;
}
useCustomClass(value: any): string {
if (!this.customCss) {
throw new Error('Custom classes are not set!');
}
const classes = Object.keys(this.customCss);
const css = Object.values(this.customCss)
.map((v, i) => ((_.isFunction(v) && v(value)) || v === value) && classes[i])
.filter((x) => x)
.join(' ');
return _.isEmpty(css) ? undefined : css;
}
ngOnChanges(changes: SimpleChanges) {
if (changes.data && changes.data.currentValue) {
this.useData();
}
}
setLimit(e: any) {
const value = Number(e.target.value);
if (value > 0) {
if (this.maxLimit && value > this.maxLimit) {
this.userConfig.limit = this.maxLimit;
// change input field to maxLimit
e.srcElement.value = this.maxLimit;
} else {
this.userConfig.limit = value;
}
}
if (this.serverSide) {
this.reloadData();
}
}
reloadData() {
if (!this.updating) {
this.status = new TableStatus();
const context = new CdTableFetchDataContext(() => {
// Do we have to display the error panel?
if (!!context.errorConfig.displayError) {
this.status = new TableStatus('danger', $localize`Failed to load data.`);
}
// Force data table to show no data?
if (context.errorConfig.resetData) {
this.data = [];
}
// Stop the loading indicator and reset the data table
// to the correct state.
this.useData();
});
context.pageInfo.offset = this.userConfig.offset;
context.pageInfo.limit = this.userConfig.limit;
context.search = this.userConfig.search;
if (this.userConfig.sorts?.length) {
const sort = this.userConfig.sorts[0];
context.sort = `${sort.dir === 'desc' ? '-' : '+'}${sort.prop}`;
}
this.fetchData.emit(context);
this.updating = true;
}
}
refreshBtn() {
this.loadingIndicator = true;
this.reloadData();
}
changePage(pageInfo: PageInfo) {
this.userConfig.offset = pageInfo.offset;
this.userConfig.limit = pageInfo.limit;
if (this.serverSide) {
this.reloadData();
}
}
rowIdentity() {
return (row: any) => {
const id = row[this.identifier];
if (_.isUndefined(id)) {
throw new Error(`Wrong identifier "${this.identifier}" -> "${id}"`);
}
return id;
};
}
useData() {
if (!this.data) {
return; // Wait for data
}
this.updateColumnFilterOptions();
this.updateFilter();
this.reset();
this.updateSelected();
this.updateExpanded();
}
/**
* Reset the data table to correct state. This includes:
* - Disable loading indicator
* - Reset 'Updating' flag
*/
reset() {
this.loadingIndicator = false;
this.updating = false;
}
/**
* After updating the data, we have to update the selected items
* because details may have changed,
* or some selected items may have been removed.
*/
updateSelected() {
if (this.updateSelectionOnRefresh === 'never') {
return;
}
const newSelected = new Set();
this.selection.selected.forEach((selectedItem) => {
for (const row of this.data) {
if (selectedItem[this.identifier] === row[this.identifier]) {
newSelected.add(row);
}
}
});
const newSelectedArray = Array.from(newSelected.values());
if (
this.updateSelectionOnRefresh === 'onChange' &&
_.isEqual(this.selection.selected, newSelectedArray)
) {
return;
}
this.selection.selected = newSelectedArray;
this.onSelect(this.selection);
}
updateExpanded() {
if (_.isUndefined(this.expanded) || this.updateExpandedOnRefresh === 'never') {
return;
}
const expandedId = this.expanded[this.identifier];
const newExpanded = _.find(this.data, (row) => expandedId === row[this.identifier]);
if (this.updateExpandedOnRefresh === 'onChange' && _.isEqual(this.expanded, newExpanded)) {
return;
}
this.expanded = newExpanded;
this.setExpandedRow.emit(newExpanded);
}
onSelect($event: any) {
// Ensure we do not process DOM 'select' events.
// https://github.com/swimlane/ngx-datatable/issues/899
if (_.has($event, 'selected')) {
this.selection.selected = $event['selected'];
}
this.updateSelection.emit(_.clone(this.selection));
}
toggleColumn(column: CdTableColumn) {
const prop: TableColumnProp = column.prop;
const hide = !column.isHidden;
if (hide && this.tableColumns.length === 1) {
column.isHidden = true;
return;
}
_.find(this.localColumns, (c: CdTableColumn) => c.prop === prop).isHidden = hide;
this.updateColumns();
}
updateColumns() {
this.updateUserColumns();
this.filterHiddenColumns();
const sortProp = this.userConfig.sorts[0].prop;
if (!_.find(this.tableColumns, (c: CdTableColumn) => c.prop === sortProp)) {
this.userConfig.sorts = this.createSortingDefinition(this.tableColumns[0].prop);
}
this.table.recalculate();
this.cdRef.detectChanges();
}
createSortingDefinition(prop: TableColumnProp): SortPropDir[] {
return [
{
prop: prop,
dir: SortDirection.asc
}
];
}
changeSorting({ sorts }: any) {
this.userConfig.sorts = sorts;
if (this.serverSide) {
this.userConfig.offset = 0;
this.reloadData();
}
}
onClearSearch() {
this.search = '';
this.updateFilter();
}
onClearFilters() {
this.columnFilters.forEach((filter) => {
filter.value = undefined;
});
this.selectedFilter = _.first(this.columnFilters);
this.updateFilter();
}
updateFilter() {
if (this.serverSide) {
if (this.userConfig.search !== this.search) {
// if we don't go back to the first page it will try load
// a page which could not exists with an especific search
this.userConfig.offset = 0;
this.userConfig.limit = this.limit;
this.userConfig.search = this.search;
this.updating = false;
this.reloadData();
}
this.rows = this.data;
} else {
let rows = this.columnFilters.length !== 0 ? this.doColumnFiltering() : this.data;
if (this.search.length > 0 && rows) {
const columns = this.localColumns.filter(
(c) => c.cellTransformation !== CellTemplate.sparkline
);
// update the rows
rows = this.subSearch(rows, TableComponent.prepareSearch(this.search), columns);
// Whenever the filter changes, always go back to the first page
this.table.offset = 0;
}
this.rows = rows;
}
}
subSearch(data: any[], currentSearch: string[], columns: CdTableColumn[]): any[] {
if (currentSearch.length === 0 || data.length === 0) {
return data;
}
const searchTerms: string[] = currentSearch.pop().replace(/\+/g, ' ').split(':');
const columnsClone = [...columns];
if (searchTerms.length === 2) {
columns = columnsClone.filter((c) => c.name.toLowerCase().indexOf(searchTerms[0]) !== -1);
}
data = this.basicDataSearch(_.last(searchTerms), data, columns);
// Checks if user searches for column but he is still typing
return this.subSearch(data, currentSearch, columnsClone);
}
basicDataSearch(searchTerm: string, rows: any[], columns: CdTableColumn[]) {
if (searchTerm.length === 0) {
return rows;
}
return rows.filter((row) => {
return (
columns.filter((col) => {
let cellValue: any = _.get(row, col.prop);
if (!_.isUndefined(col.pipe)) {
cellValue = col.pipe.transform(cellValue);
}
if (_.isUndefined(cellValue) || _.isNull(cellValue)) {
return false;
}
if (_.isObjectLike(cellValue)) {
if (this.searchableObjects) {
cellValue = JSON.stringify(cellValue);
} else {
return false;
}
}
if (_.isArray(cellValue)) {
cellValue = cellValue.join(' ');
} else if (_.isNumber(cellValue) || _.isBoolean(cellValue)) {
cellValue = cellValue.toString();
}
return cellValue.toLowerCase().indexOf(searchTerm) !== -1;
}).length > 0
);
});
}
getRowClass() {
// Return the function used to populate a row's CSS classes.
return () => {
return {
clickable: !_.isUndefined(this.selectionType)
};
};
}
toggleExpandRow(row: any, isExpanded: boolean, event: any) {
event.stopPropagation();
if (!isExpanded) {
// If current row isn't expanded, collapse others
this.expanded = row;
this.table.rowDetail.collapseAllRows();
this.setExpandedRow.emit(row);
} else {
// If all rows are closed, emit undefined
this.expanded = undefined;
this.setExpandedRow.emit(undefined);
}
this.table.rowDetail.toggleExpandRow(row);
}
}
| 28,752
| 30.050756
| 105
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/decorators/cd-encode.spec.ts
|
import { cdEncode, cdEncodeNot } from './cd-encode';
describe('cdEncode', () => {
@cdEncode
class ClassA {
x2: string;
y2: string;
methodA(x1: string, @cdEncodeNot y1: string) {
this.x2 = x1;
this.y2 = y1;
}
}
class ClassB {
x2: string;
y2: string;
@cdEncode
methodB(x1: string, @cdEncodeNot y1: string) {
this.x2 = x1;
this.y2 = y1;
}
}
const word = 'a+b/c-d';
it('should encode all params of ClassA, with exception of y1', () => {
const a = new ClassA();
a.methodA(word, word);
expect(a.x2).toBe('a%2Bb%2Fc-d');
expect(a.y2).toBe(word);
});
it('should encode all params of methodB, with exception of y1', () => {
const b = new ClassB();
b.methodB(word, word);
expect(b.x2).toBe('a%2Bb%2Fc-d');
expect(b.y2).toBe(word);
});
});
| 848
| 19.214286
| 73
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/decorators/cd-encode.ts
|
import _ from 'lodash';
/**
* This decorator can be used in a class or method.
* It will encode all the string parameters of all the methods of a class
* or, if applied on a method, the specified method.
*
* @export
* @param {Function} [target=null]
* @returns {*}
*/
export function cdEncode(...args: any[]): any {
switch (args.length) {
case 1:
return encodeClass.apply(undefined, args);
case 3:
return encodeMethod.apply(undefined, args);
default:
throw new Error();
}
}
/**
* This decorator can be used in parameters only.
* It will exclude the parameter from being encode.
* This should be used in parameters that are going
* to be sent in the request's body.
*
* @export
* @param {Object} target
* @param {string} propertyKey
* @param {number} index
*/
export function cdEncodeNot(target: object, propertyKey: string, index: number) {
const metadataKey = `__ignore_${propertyKey}`;
if (Array.isArray(target[metadataKey])) {
target[metadataKey].push(index);
} else {
target[metadataKey] = [index];
}
}
function encodeClass(target: Function) {
for (const propertyName of Object.getOwnPropertyNames(target.prototype)) {
const descriptor = Object.getOwnPropertyDescriptor(target.prototype, propertyName);
const isMethod = descriptor.value instanceof Function;
const isConstructor = propertyName === 'constructor';
if (!isMethod || isConstructor) {
continue;
}
encodeMethod(target.prototype, propertyName, descriptor);
Object.defineProperty(target.prototype, propertyName, descriptor);
}
}
function encodeMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
if (descriptor === undefined) {
descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
}
const originalMethod = descriptor.value;
descriptor.value = function () {
const metadataKey = `__ignore_${propertyKey}`;
const indices: number[] = target[metadataKey] || [];
const args = [];
for (let i = 0; i < arguments.length; i++) {
if (_.isString(arguments[i]) && indices.indexOf(i) === -1) {
args[i] = encodeURIComponent(arguments[i]);
} else {
args[i] = arguments[i];
}
}
const result = originalMethod.apply(this, args);
return result;
};
}
| 2,320
| 27.654321
| 89
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/auth-storage.directive.spec.ts
|
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Permissions } from '~/app/shared/models/permissions';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { AuthStorageDirective } from './auth-storage.directive';
@Component({
template: `<div id="permitted" *cdScope="condition; matchAll: matchAll"></div>`
})
export class AuthStorageDirectiveTestComponent {
condition: string | string[] | object;
matchAll = true;
}
describe('AuthStorageDirective', () => {
let fixture: ComponentFixture<AuthStorageDirectiveTestComponent>;
let component: AuthStorageDirectiveTestComponent;
let getPermissionsSpy: jasmine.Spy;
let el: HTMLElement;
configureTestBed({
declarations: [AuthStorageDirective, AuthStorageDirectiveTestComponent],
providers: [AuthStorageService]
});
beforeEach(() => {
getPermissionsSpy = spyOn(TestBed.inject(AuthStorageService), 'getPermissions');
getPermissionsSpy.and.returnValue(new Permissions({ osd: ['read'], rgw: ['read'] }));
fixture = TestBed.createComponent(AuthStorageDirectiveTestComponent);
el = fixture.debugElement.nativeElement;
component = fixture.componentInstance;
});
it('should show div on valid condition', () => {
// String condition
component.condition = 'rgw';
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeTruthy();
// Array condition
component.condition = ['osd', 'rgw'];
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeTruthy();
// Object condition
component.condition = { rgw: ['read'], osd: ['read'] };
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeTruthy();
});
it('should show div with loose matching', () => {
component.matchAll = false;
fixture.detectChanges();
// Array condition
component.condition = ['configOpt', 'osd', 'rgw'];
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeTruthy();
// Object condition
component.condition = { rgw: ['read', 'update', 'fake'], osd: ['read'] };
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeTruthy();
});
it('should not show div on invalid condition', () => {
// String condition
component.condition = 'fake';
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeFalsy();
// Array condition
component.condition = ['configOpt', 'osd', 'rgw'];
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeFalsy();
// Object condition
component.condition = { rgw: ['read', 'update'], osd: ['read'] };
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeFalsy();
});
it('should hide div on condition change', () => {
component.condition = 'osd';
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeTruthy();
component.condition = 'grafana';
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeFalsy();
});
it('should hide div on permission change', () => {
component.condition = ['osd'];
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeTruthy();
getPermissionsSpy.and.returnValue(new Permissions({}));
component.condition = 'osd';
fixture.detectChanges();
expect(el.querySelector('#permitted')).toBeFalsy();
});
});
| 3,535
| 32.67619
| 89
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/auth-storage.directive.ts
|
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import _ from 'lodash';
import { Permission, Permissions } from '~/app/shared/models/permissions';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
type Condition = string | string[] | Partial<{ [Property in keyof Permissions]: keyof Permission }>;
@Directive({
selector: '[cdScope]'
})
export class AuthStorageDirective {
permissions: Permissions;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private authStorageService: AuthStorageService
) {}
@Input() set cdScope(condition: Condition) {
this.permissions = this.authStorageService.getPermissions();
if (this.isAuthorized(condition)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
@Input() cdScopeMatchAll = true;
private isAuthorized(condition: Condition): boolean {
const everyOrSome = this.cdScopeMatchAll ? _.every : _.some;
if (_.isString(condition)) {
return _.get(this.permissions, [condition, 'read'], false);
} else if (_.isArray(condition)) {
return everyOrSome(condition, (permission) => this.permissions[permission]['read']);
} else if (_.isObject(condition)) {
return everyOrSome(condition, (value, key) => {
return everyOrSome(value, (val) => this.permissions[key][val]);
});
}
return false;
}
}
| 1,500
| 29.632653
| 100
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/autofocus.directive.spec.ts
|
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { configureTestBed } from '~/testing/unit-test-helper';
import { AutofocusDirective } from './autofocus.directive';
@Component({
template: `
<form>
<input id="x" type="text" />
<input id="y" type="password" autofocus />
</form>
`
})
export class PasswordFormComponent {}
@Component({
template: `
<form>
<input id="x" type="checkbox" [autofocus]="edit" />
<input id="y" type="text" />
</form>
`
})
export class CheckboxFormComponent {
public edit = true;
}
@Component({
template: `
<form>
<input id="x" type="text" [autofocus]="foo" />
</form>
`
})
export class TextFormComponent {
foo() {
return false;
}
}
describe('AutofocusDirective', () => {
configureTestBed({
declarations: [
AutofocusDirective,
CheckboxFormComponent,
PasswordFormComponent,
TextFormComponent
]
});
it('should create an instance', () => {
const directive = new AutofocusDirective(null);
expect(directive).toBeTruthy();
});
it('should focus the password form field', () => {
const fixture: ComponentFixture<PasswordFormComponent> = TestBed.createComponent(
PasswordFormComponent
);
fixture.detectChanges();
const focused = fixture.debugElement.query(By.css(':focus'));
expect(focused.attributes.id).toBe('y');
expect(focused.attributes.type).toBe('password');
const element = document.getElementById('y');
expect(element === document.activeElement).toBeTruthy();
});
it('should focus the checkbox form field', () => {
const fixture: ComponentFixture<CheckboxFormComponent> = TestBed.createComponent(
CheckboxFormComponent
);
fixture.detectChanges();
const focused = fixture.debugElement.query(By.css(':focus'));
expect(focused.attributes.id).toBe('x');
expect(focused.attributes.type).toBe('checkbox');
const element = document.getElementById('x');
expect(element === document.activeElement).toBeTruthy();
});
it('should not focus the text form field', () => {
const fixture: ComponentFixture<TextFormComponent> = TestBed.createComponent(TextFormComponent);
fixture.detectChanges();
const focused = fixture.debugElement.query(By.css(':focus'));
expect(focused).toBeNull();
const element = document.getElementById('x');
expect(element !== document.activeElement).toBeTruthy();
});
});
| 2,565
| 27.197802
| 100
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/autofocus.directive.ts
|
import { AfterViewInit, Directive, ElementRef, Input } from '@angular/core';
import _ from 'lodash';
@Directive({
selector: '[autofocus]' // eslint-disable-line
})
export class AutofocusDirective implements AfterViewInit {
private focus = true;
constructor(private elementRef: ElementRef) {}
ngAfterViewInit() {
const el: HTMLInputElement = this.elementRef.nativeElement;
if (this.focus && _.isFunction(el.focus)) {
el.focus();
}
}
@Input()
public set autofocus(condition: any) {
if (_.isBoolean(condition)) {
this.focus = condition;
} else if (_.isFunction(condition)) {
this.focus = condition();
}
}
}
| 667
| 22.034483
| 76
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/dimless-binary-per-second.directive.spec.ts
|
import { DimlessBinaryPerSecondDirective } from './dimless-binary-per-second.directive';
export class MockElementRef {
nativeElement: {};
}
describe('DimlessBinaryPerSecondDirective', () => {
it('should create an instance', () => {
const directive = new DimlessBinaryPerSecondDirective(new MockElementRef(), null, null, null);
expect(directive).toBeTruthy();
});
});
| 383
| 28.538462
| 98
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/dimless-binary-per-second.directive.ts
|
import {
Directive,
ElementRef,
EventEmitter,
HostListener,
Input,
OnInit,
Output
} from '@angular/core';
import { NgControl } from '@angular/forms';
import _ from 'lodash';
import { DimlessBinaryPerSecondPipe } from '../pipes/dimless-binary-per-second.pipe';
import { FormatterService } from '../services/formatter.service';
@Directive({
selector: '[cdDimlessBinaryPerSecond]'
})
export class DimlessBinaryPerSecondDirective implements OnInit {
@Output()
ngModelChange: EventEmitter<any> = new EventEmitter();
/**
* Event emitter for letting this directive know that the data has (asynchronously) been loaded
* and the value needs to be adapted by this directive.
*/
@Input()
ngDataReady: EventEmitter<any>;
/**
* Minimum size in bytes.
* If user enter a value lower than <minBytes>,
* the model will automatically be update to <minBytes>.
*
* If <roundPower> is used, this value should be a power of <roundPower>.
*
* Example:
* Given minBytes=4096 (4KiB), if user type 1KiB, then model will be updated to 4KiB
*/
@Input()
minBytes: number;
/**
* Maximum size in bytes.
* If user enter a value greater than <maxBytes>,
* the model will automatically be update to <maxBytes>.
*
* If <roundPower> is used, this value should be a power of <roundPower>.
*
* Example:
* Given maxBytes=3145728 (3MiB), if user type 4MiB, then model will be updated to 3MiB
*/
@Input()
maxBytes: number;
/**
* Value will be rounded up the nearest power of <roundPower>
*
* Example:
* Given roundPower=2, if user type 7KiB, then model will be updated to 8KiB
* Given roundPower=2, if user type 5KiB, then model will be updated to 4KiB
*/
@Input()
roundPower: number;
/**
* Default unit that should be used when user do not type a unit.
* By default, "MiB" will be used.
*
* Example:
* Given defaultUnit=null, if user type 7, then model will be updated to 7MiB
* Given defaultUnit=k, if user type 7, then model will be updated to 7KiB
*/
@Input()
defaultUnit: string;
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private control: NgControl,
private dimlessBinaryPerSecondPipe: DimlessBinaryPerSecondPipe,
private formatter: FormatterService
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.setValue(this.el.value);
if (this.ngDataReady) {
this.ngDataReady.subscribe(() => this.setValue(this.el.value));
}
}
setValue(value: string) {
if (/^[\d.]+$/.test(value)) {
value += this.defaultUnit || 'm';
}
const size = this.formatter.toBytes(value, 0);
const roundedSize = this.round(size);
this.el.value = this.dimlessBinaryPerSecondPipe.transform(roundedSize);
if (size !== null) {
this.ngModelChange.emit(this.el.value);
this.control.control.setValue(this.el.value);
} else {
this.ngModelChange.emit(null);
this.control.control.setValue(null);
}
}
round(size: number) {
if (size !== null && size !== 0) {
if (!_.isUndefined(this.minBytes) && size < this.minBytes) {
return this.minBytes;
}
if (!_.isUndefined(this.maxBytes) && size > this.maxBytes) {
return this.maxBytes;
}
if (!_.isUndefined(this.roundPower)) {
const power = Math.round(Math.log(size) / Math.log(this.roundPower));
return Math.pow(this.roundPower, power);
}
}
return size;
}
@HostListener('blur', ['$event.target.value'])
onBlur(value: string) {
this.setValue(value);
}
}
| 3,647
| 26.428571
| 97
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/dimless-binary.directive.spec.ts
|
import { DimlessBinaryDirective } from './dimless-binary.directive';
export class MockElementRef {
nativeElement: {};
}
describe('DimlessBinaryDirective', () => {
it('should create an instance', () => {
const directive = new DimlessBinaryDirective(new MockElementRef(), null, null, null);
expect(directive).toBeTruthy();
});
});
| 345
| 25.615385
| 89
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/dimless-binary.directive.ts
|
import {
Directive,
ElementRef,
EventEmitter,
HostListener,
Input,
OnInit,
Output
} from '@angular/core';
import { NgControl } from '@angular/forms';
import _ from 'lodash';
import { DimlessBinaryPipe } from '../pipes/dimless-binary.pipe';
import { FormatterService } from '../services/formatter.service';
@Directive({
selector: '[cdDimlessBinary]'
})
export class DimlessBinaryDirective implements OnInit {
@Output()
ngModelChange: EventEmitter<any> = new EventEmitter();
/**
* Minimum size in bytes.
* If user enter a value lower than <minBytes>,
* the model will automatically be update to <minBytes>.
*
* If <roundPower> is used, this value should be a power of <roundPower>.
*
* Example:
* Given minBytes=4096 (4KiB), if user type 1KiB, then model will be updated to 4KiB
*/
@Input()
minBytes: number;
/**
* Maximum size in bytes.
* If user enter a value greater than <maxBytes>,
* the model will automatically be update to <maxBytes>.
*
* If <roundPower> is used, this value should be a power of <roundPower>.
*
* Example:
* Given maxBytes=3145728 (3MiB), if user type 4MiB, then model will be updated to 3MiB
*/
@Input()
maxBytes: number;
/**
* Value will be rounded up the nearest power of <roundPower>
*
* Example:
* Given roundPower=2, if user type 7KiB, then model will be updated to 8KiB
* Given roundPower=2, if user type 5KiB, then model will be updated to 4KiB
*/
@Input()
roundPower: number;
/**
* Default unit that should be used when user do not type a unit.
* By default, "MiB" will be used.
*
* Example:
* Given defaultUnit=null, if user type 7, then model will be updated to 7MiB
* Given defaultUnit=k, if user type 7, then model will be updated to 7KiB
*/
@Input()
defaultUnit: string;
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private control: NgControl,
private dimlessBinaryPipe: DimlessBinaryPipe,
private formatter: FormatterService
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.setValue(this.el.value);
}
setValue(value: string) {
if (/^[\d.]+$/.test(value)) {
value += this.defaultUnit || 'm';
}
const size = this.formatter.toBytes(value);
const roundedSize = this.round(size);
this.el.value = this.dimlessBinaryPipe.transform(roundedSize);
if (size !== null) {
this.ngModelChange.emit(this.el.value);
this.control.control.setValue(this.el.value);
} else {
this.ngModelChange.emit(null);
this.control.control.setValue(null);
}
}
round(size: number) {
if (size !== null && size !== 0) {
if (!_.isUndefined(this.minBytes) && size < this.minBytes) {
return this.minBytes;
}
if (!_.isUndefined(this.maxBytes) && size > this.maxBytes) {
return this.maxBytes;
}
if (!_.isUndefined(this.roundPower)) {
const power = Math.round(Math.log(size) / Math.log(this.roundPower));
return Math.pow(this.roundPower, power);
}
}
return size;
}
@HostListener('blur', ['$event.target.value'])
onBlur(value: string) {
this.setValue(value);
}
}
| 3,261
| 25.520325
| 91
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/directives.module.ts
|
import { NgModule } from '@angular/core';
import { AuthStorageDirective } from './auth-storage.directive';
import { AutofocusDirective } from './autofocus.directive';
import { DimlessBinaryPerSecondDirective } from './dimless-binary-per-second.directive';
import { DimlessBinaryDirective } from './dimless-binary.directive';
import { FormInputDisableDirective } from './form-input-disable.directive';
import { FormLoadingDirective } from './form-loading.directive';
import { FormScopeDirective } from './form-scope.directive';
import { IopsDirective } from './iops.directive';
import { MillisecondsDirective } from './milliseconds.directive';
import { CdFormControlDirective } from './ng-bootstrap-form-validation/cd-form-control.directive';
import { CdFormGroupDirective } from './ng-bootstrap-form-validation/cd-form-group.directive';
import { CdFormValidationDirective } from './ng-bootstrap-form-validation/cd-form-validation.directive';
import { PasswordButtonDirective } from './password-button.directive';
import { StatefulTabDirective } from './stateful-tab.directive';
import { TrimDirective } from './trim.directive';
@NgModule({
imports: [],
declarations: [
AutofocusDirective,
DimlessBinaryDirective,
DimlessBinaryPerSecondDirective,
PasswordButtonDirective,
TrimDirective,
MillisecondsDirective,
IopsDirective,
FormLoadingDirective,
StatefulTabDirective,
FormInputDisableDirective,
FormScopeDirective,
CdFormControlDirective,
CdFormGroupDirective,
CdFormValidationDirective,
AuthStorageDirective
],
exports: [
AutofocusDirective,
DimlessBinaryDirective,
DimlessBinaryPerSecondDirective,
PasswordButtonDirective,
TrimDirective,
MillisecondsDirective,
IopsDirective,
FormLoadingDirective,
StatefulTabDirective,
FormInputDisableDirective,
FormScopeDirective,
CdFormControlDirective,
CdFormGroupDirective,
CdFormValidationDirective,
AuthStorageDirective
]
})
export class DirectivesModule {}
| 2,033
| 34.684211
| 104
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/form-input-disable.directive.spec.ts
|
import { Component, DebugElement, Input } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { configureTestBed } from '~/testing/unit-test-helper';
import { Permission } from '../models/permissions';
import { AuthStorageService } from '../services/auth-storage.service';
import { FormInputDisableDirective } from './form-input-disable.directive';
import { FormScopeDirective } from './form-scope.directive';
@Component({
template: `
<form cdFormScope="osd">
<input type="checkbox" />
</form>
`
})
export class FormDisableComponent {}
class MockFormScopeDirective {
@Input() cdFormScope = 'osd';
}
describe('FormInputDisableDirective', () => {
let fakePermissions: Permission;
let authStorageService: AuthStorageService;
let directive: FormInputDisableDirective;
let fixture: ComponentFixture<FormDisableComponent>;
let inputElement: DebugElement;
configureTestBed({
declarations: [FormScopeDirective, FormInputDisableDirective, FormDisableComponent]
});
beforeEach(() => {
directive = new FormInputDisableDirective(
new MockFormScopeDirective(),
new AuthStorageService(),
null
);
fakePermissions = {
create: false,
update: false,
read: false,
delete: false
};
authStorageService = TestBed.inject(AuthStorageService);
spyOn(authStorageService, 'getPermissions').and.callFake(() => ({
osd: fakePermissions
}));
fixture = TestBed.createComponent(FormDisableComponent);
inputElement = fixture.debugElement.query(By.css('input'));
});
afterEach(() => {
directive = null;
});
it('should create an instance', () => {
expect(directive).toBeTruthy();
});
it('should disable the input if update permission is false', () => {
fixture.detectChanges();
expect(inputElement.nativeElement.disabled).toBeTruthy();
});
it('should not disable the input if update permission is true', () => {
fakePermissions.update = true;
fakePermissions.read = false;
fixture.detectChanges();
expect(inputElement.nativeElement.disabled).toBeFalsy();
});
});
| 2,204
| 28.013158
| 87
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/form-input-disable.directive.ts
|
import { AfterViewInit, Directive, ElementRef, Optional } from '@angular/core';
import { Permissions } from '../models/permissions';
import { AuthStorageService } from '../services/auth-storage.service';
import { FormScopeDirective } from './form-scope.directive';
@Directive({
selector:
'input:not([cdNoFormInputDisable]), select:not([cdNoFormInputDisable]), button:not([cdNoFormInputDisable]), [cdFormInputDisable]'
})
export class FormInputDisableDirective implements AfterViewInit {
permissions: Permissions;
constructor(
@Optional() private formScope: FormScopeDirective,
private authStorageService: AuthStorageService,
private elementRef: ElementRef
) {}
ngAfterViewInit() {
this.permissions = this.authStorageService.getPermissions();
const service_name = this.formScope?.cdFormScope;
if (service_name && !this.permissions?.[service_name]?.update) {
this.elementRef.nativeElement.disabled = true;
}
}
}
| 964
| 33.464286
| 133
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/form-loading.directive.spec.ts
|
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap';
import { configureTestBed } from '~/testing/unit-test-helper';
import { AlertPanelComponent } from '../components/alert-panel/alert-panel.component';
import { LoadingPanelComponent } from '../components/loading-panel/loading-panel.component';
import { CdForm } from '../forms/cd-form';
import { SharedModule } from '../shared.module';
import { FormLoadingDirective } from './form-loading.directive';
@Component({ selector: 'cd-test-cmp', template: '<span *cdFormLoading="loading">foo</span>' })
class TestComponent extends CdForm {
constructor() {
super();
}
}
describe('FormLoadingDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<any>;
const expectShown = (elem: number, error: number, loading: number) => {
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(elem);
expect(fixture.debugElement.queryAll(By.css('cd-alert-panel')).length).toEqual(error);
expect(fixture.debugElement.queryAll(By.css('cd-loading-panel')).length).toEqual(loading);
};
configureTestBed(
{
declarations: [TestComponent],
imports: [SharedModule, NgbAlertModule]
},
[LoadingPanelComponent, AlertPanelComponent]
);
afterEach(() => {
fixture = null;
});
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create an instance', () => {
const directive = new FormLoadingDirective(null, null);
expect(directive).toBeTruthy();
});
it('should show loading component by default', () => {
expectShown(0, 0, 1);
const alert = fixture.debugElement.nativeElement.querySelector('cd-loading-panel ngb-alert');
expect(alert.textContent).toBe('Loading form data...');
});
it('should show error component when calling loadingError()', () => {
component.loadingError();
fixture.detectChanges();
expectShown(0, 1, 0);
const alert = fixture.debugElement.nativeElement.querySelector(
'cd-alert-panel .alert-panel-text'
);
expect(alert.textContent).toBe('Form data could not be loaded.');
});
it('should show original component when calling loadingReady()', () => {
component.loadingReady();
fixture.detectChanges();
expectShown(1, 0, 0);
const alert = fixture.debugElement.nativeElement.querySelector('span');
expect(alert.textContent).toBe('foo');
});
it('should show nothing when calling loadingNone()', () => {
component.loadingNone();
fixture.detectChanges();
expectShown(0, 0, 0);
});
});
| 2,814
| 30.277778
| 97
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/form-loading.directive.ts
|
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { AlertPanelComponent } from '../components/alert-panel/alert-panel.component';
import { LoadingPanelComponent } from '../components/loading-panel/loading-panel.component';
import { LoadingStatus } from '../forms/cd-form';
@Directive({
selector: '[cdFormLoading]'
})
export class FormLoadingDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
@Input() set cdFormLoading(condition: LoadingStatus) {
let content: any;
this.viewContainer.clear();
switch (condition) {
case LoadingStatus.Loading:
content = this.resolveNgContent($localize`Loading form data...`);
this.viewContainer.createComponent(LoadingPanelComponent, { projectableNodes: content });
break;
case LoadingStatus.Ready:
this.viewContainer.createEmbeddedView(this.templateRef);
break;
case LoadingStatus.Error:
content = this.resolveNgContent($localize`Form data could not be loaded.`);
const componentRef = this.viewContainer.createComponent(AlertPanelComponent, {
projectableNodes: content
});
(<AlertPanelComponent>componentRef.instance).type = 'error';
break;
}
}
resolveNgContent(content: string) {
const element = document.createTextNode(content);
return [[element]];
}
}
| 1,432
| 33.95122
| 97
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/form-scope.directive.spec.ts
|
import { FormScopeDirective } from './form-scope.directive';
describe('UpdateOnlyDirective', () => {
it('should create an instance', () => {
const directive = new FormScopeDirective();
expect(directive).toBeTruthy();
});
});
| 238
| 25.555556
| 60
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/form-scope.directive.ts
|
import { Directive, Input } from '@angular/core';
@Directive({
selector: '[cdFormScope]'
})
export class FormScopeDirective {
@Input() cdFormScope: any;
}
| 160
| 16.888889
| 49
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/iops.directive.spec.ts
|
import { IopsDirective } from './iops.directive';
describe('IopsDirective', () => {
it('should create an instance', () => {
const directive = new IopsDirective(null, null);
expect(directive).toBeTruthy();
});
});
| 226
| 24.222222
| 52
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/iops.directive.ts
|
import { Directive, EventEmitter, HostListener, Input, OnInit } from '@angular/core';
import { NgControl } from '@angular/forms';
import { FormatterService } from '../services/formatter.service';
@Directive({
selector: '[cdIops]'
})
export class IopsDirective implements OnInit {
@Input()
ngDataReady: EventEmitter<any>;
constructor(private formatter: FormatterService, private ngControl: NgControl) {}
setValue(value: string): void {
const iops = this.formatter.toIops(value);
this.ngControl.control.setValue(`${iops} IOPS`);
}
ngOnInit(): void {
this.setValue(this.ngControl.value);
if (this.ngDataReady) {
this.ngDataReady.subscribe(() => this.setValue(this.ngControl.value));
}
}
@HostListener('blur', ['$event.target.value'])
onUpdate(value: string) {
this.setValue(value);
}
}
| 841
| 25.3125
| 85
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/milliseconds.directive.spec.ts
|
import { MillisecondsDirective } from './milliseconds.directive';
describe('MillisecondsDirective', () => {
it('should create an instance', () => {
const directive = new MillisecondsDirective(null, null);
expect(directive).toBeTruthy();
});
});
| 258
| 27.777778
| 65
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/milliseconds.directive.ts
|
import { Directive, EventEmitter, HostListener, Input, OnInit } from '@angular/core';
import { NgControl } from '@angular/forms';
import { FormatterService } from '../services/formatter.service';
@Directive({
selector: '[cdMilliseconds]'
})
export class MillisecondsDirective implements OnInit {
@Input()
ngDataReady: EventEmitter<any>;
constructor(private control: NgControl, private formatter: FormatterService) {}
setValue(value: string): void {
const ms = this.formatter.toMilliseconds(value);
this.control.control.setValue(`${ms} ms`);
}
ngOnInit(): void {
this.setValue(this.control.value);
if (this.ngDataReady) {
this.ngDataReady.subscribe(() => this.setValue(this.control.value));
}
}
@HostListener('blur', ['$event.target.value'])
onUpdate(value: string) {
this.setValue(value);
}
}
| 851
| 25.625
| 85
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/password-button.directive.spec.ts
|
import { PasswordButtonDirective } from './password-button.directive';
describe('PasswordButtonDirective', () => {
it('should create an instance', () => {
const directive = new PasswordButtonDirective(null, null);
expect(directive).toBeTruthy();
});
});
| 267
| 28.777778
| 70
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/password-button.directive.ts
|
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[cdPasswordButton]'
})
export class PasswordButtonDirective implements OnInit {
private iElement: HTMLElement;
@Input()
private cdPasswordButton: string;
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.renderer.setAttribute(this.elementRef.nativeElement, 'tabindex', '-1');
this.iElement = this.renderer.createElement('i');
this.renderer.addClass(this.iElement, 'fa');
this.renderer.appendChild(this.elementRef.nativeElement, this.iElement);
this.update();
}
private getInputElement() {
return document.getElementById(this.cdPasswordButton) as HTMLInputElement;
}
private update() {
const inputElement = this.getInputElement();
if (inputElement && inputElement.type === 'text') {
this.renderer.removeClass(this.iElement, 'fa-eye');
this.renderer.addClass(this.iElement, 'fa-eye-slash');
} else {
this.renderer.removeClass(this.iElement, 'fa-eye-slash');
this.renderer.addClass(this.iElement, 'fa-eye');
}
}
@HostListener('click')
onClick() {
const inputElement = this.getInputElement();
// Modify the type of the input field.
inputElement.type = inputElement.type === 'password' ? 'text' : 'password';
// Update the button icon/tooltip.
this.update();
}
}
| 1,440
| 30.326087
| 94
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/stateful-tab.directive.spec.ts
|
import { NgbConfig, NgbNav, NgbNavChangeEvent, NgbNavConfig } from '@ng-bootstrap/ng-bootstrap';
import { StatefulTabDirective } from './stateful-tab.directive';
describe('StatefulTabDirective', () => {
it('should create an instance', () => {
const directive = new StatefulTabDirective(null);
expect(directive).toBeTruthy();
});
it('should get and select active tab', () => {
const nav = new NgbNav('tablist', new NgbNavConfig(new NgbConfig()), <any>null, null);
spyOn(nav, 'select');
const directive = new StatefulTabDirective(nav);
directive.cdStatefulTab = 'bar';
window.localStorage.setItem('tabset_bar', 'foo');
directive.ngOnInit();
expect(nav.select).toHaveBeenCalledWith('foo');
});
it('should store active tab', () => {
const directive = new StatefulTabDirective(null);
directive.cdStatefulTab = 'bar';
const event: NgbNavChangeEvent<string> = { activeId: '', nextId: 'xyz', preventDefault: null };
directive.onNavChange(event);
expect(window.localStorage.getItem('tabset_bar')).toBe('xyz');
});
});
| 1,081
| 36.310345
| 99
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/stateful-tab.directive.ts
|
import { Directive, Host, HostListener, Input, OnInit, Optional } from '@angular/core';
import { NgbNav, NgbNavChangeEvent } from '@ng-bootstrap/ng-bootstrap';
@Directive({
selector: '[cdStatefulTab]'
})
export class StatefulTabDirective implements OnInit {
@Input()
cdStatefulTab: string;
private localStorage = window.localStorage;
constructor(@Optional() @Host() private nav: NgbNav) {}
ngOnInit() {
// Is an activate tab identifier stored in the local storage?
const activeId = this.localStorage.getItem(`tabset_${this.cdStatefulTab}`);
if (activeId) {
this.nav.select(activeId);
}
}
@HostListener('navChange', ['$event'])
onNavChange(event: NgbNavChangeEvent) {
// Store the current active tab identifier in the local storage.
if (this.cdStatefulTab && event.nextId) {
this.localStorage.setItem(`tabset_${this.cdStatefulTab}`, event.nextId);
}
}
}
| 919
| 27.75
| 87
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/trim.directive.spec.ts
|
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { configureTestBed } from '~/testing/unit-test-helper';
import { CdFormGroup } from '../forms/cd-form-group';
import { TrimDirective } from './trim.directive';
@Component({
template: `
<form [formGroup]="trimForm">
<input type="text" formControlName="trimInput" cdTrim />
</form>
`
})
export class TrimComponent {
trimForm: CdFormGroup;
constructor() {
this.trimForm = new CdFormGroup({
trimInput: new FormControl()
});
}
}
describe('TrimDirective', () => {
configureTestBed({
imports: [FormsModule, ReactiveFormsModule],
declarations: [TrimDirective, TrimComponent]
});
it('should create an instance', () => {
const directive = new TrimDirective(null);
expect(directive).toBeTruthy();
});
it('should trim', () => {
const fixture: ComponentFixture<TrimComponent> = TestBed.createComponent(TrimComponent);
const component: TrimComponent = fixture.componentInstance;
const inputElement: HTMLInputElement = fixture.debugElement.query(By.css('input'))
.nativeElement;
fixture.detectChanges();
inputElement.value = ' a b ';
inputElement.dispatchEvent(new Event('input'));
const expectedValue = 'a b';
expect(inputElement.value).toBe(expectedValue);
expect(component.trimForm.getValue('trimInput')).toBe(expectedValue);
});
});
| 1,581
| 30.019608
| 92
|
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/trim.directive.ts
|
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
import _ from 'lodash';
@Directive({
selector: '[cdTrim]'
})
export class TrimDirective {
constructor(private ngControl: NgControl) {}
@HostListener('input', ['$event.target.value'])
onInput(value: string) {
this.setValue(value);
}
setValue(value: string): void {
value = _.isString(value) ? value.trim() : value;
this.ngControl.control.setValue(value);
}
}
| 489
| 21.272727
| 56
|
ts
|