12 Commits

Author SHA1 Message Date
6280d04ee7 fix scroll position 2026-03-11 18:33:41 +01:00
196e8c80d8 global filter 2026-03-11 18:05:33 +01:00
c2bcac58b3 global filter 2026-03-11 17:56:17 +01:00
ce67fb4a34 fix show song header 2026-03-11 17:34:30 +01:00
3082ae1b55 fix show song header 2026-03-11 17:28:04 +01:00
0452ec55b2 validate chords #3 2026-03-11 17:13:17 +01:00
9f47f259c0 validate chords #2 2026-03-11 16:35:29 +01:00
ae4459f5ce validate chords 2026-03-11 16:18:36 +01:00
03fb395605 optimize drag'n'drop 2026-03-11 12:08:34 +01:00
68a257e2bd optimize shadows & paddings 2026-03-11 12:02:53 +01:00
2ac1156e20 optimize chords 2026-03-10 00:23:04 +01:00
7170e4a08e add unit tests 2026-03-10 00:05:15 +01:00
66 changed files with 2718 additions and 432 deletions

View File

@@ -54,6 +54,21 @@
"plugin:@angular-eslint/template/recommended"
],
"rules": {}
},
{
"files": [
"*.spec.ts"
],
"rules": {
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-return": "off"
}
}
]
}

View File

@@ -1,6 +1,5 @@
import {ChangeDetectionStrategy, Component, OnInit, inject} from '@angular/core';
import {ChangeDetectionStrategy, Component, OnInit} from '@angular/core';
import {fader} from './animations';
import {ScrollService} from './services/scroll.service';
import {register} from 'swiper/element/bundle';
import {RouterOutlet} from '@angular/router';
import {NavigationComponent} from './widget-modules/components/application-frame/navigation/navigation.component';
@@ -14,8 +13,6 @@ import {NavigationComponent} from './widget-modules/components/application-frame
imports: [RouterOutlet, NavigationComponent],
})
export class AppComponent implements OnInit {
private scrollService = inject(ScrollService);
public constructor() {
register();
}
@@ -24,8 +21,4 @@ export class AppComponent implements OnInit {
setTimeout(() => document.querySelector('#load-bg')?.classList.add('hidden'), 1000);
setTimeout(() => document.querySelector('#load-bg')?.remove(), 5000);
}
public onScoll($event: {srcElement: {scrollTop: number}}): void {
this.scrollService.saveScrollPosition($event.srcElement.scrollTop);
}
}

View File

@@ -12,7 +12,7 @@ describe('GuestShowDataService', () => {
let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => {
beforeEach(async () => {
docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.returnValue({
@@ -27,7 +27,7 @@ describe('GuestShowDataService', () => {
dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy);
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});

View File

@@ -2,20 +2,22 @@ import {TestBed} from '@angular/core/testing';
import {GuestShowDataService} from './guest-show-data.service';
import {GuestShowService} from './guest-show.service';
import {ShowService} from '../shows/services/show.service';
import {Show} from '../shows/services/show';
import {Song} from '../songs/services/song';
describe('GuestShowService', () => {
let service: GuestShowService;
let guestShowDataServiceSpy: jasmine.SpyObj<GuestShowDataService>;
let showServiceSpy: jasmine.SpyObj<ShowService>;
beforeEach(() => {
beforeEach(async () => {
guestShowDataServiceSpy = jasmine.createSpyObj<GuestShowDataService>('GuestShowDataService', ['add', 'update$']);
showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['update$']);
guestShowDataServiceSpy.add.and.resolveTo('share-1');
guestShowDataServiceSpy.update$.and.resolveTo();
showServiceSpy.update$.and.resolveTo();
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [
{provide: GuestShowDataService, useValue: guestShowDataServiceSpy},
{provide: ShowService, useValue: showServiceSpy},
@@ -30,8 +32,8 @@ describe('GuestShowService', () => {
});
it('should create a new guest share, persist the generated shareId on the show and return the share url', async () => {
const show = {id: 'show-1', showType: 'service-worship', date: new Date(), shareId: ''} as any;
const songs = [{id: 'song-1'}] as any;
const show = {id: 'show-1', showType: 'service-worship', date: new Date(), shareId: ''} as unknown as Show;
const songs = [{id: 'song-1'}] as unknown as Song[];
const expectedUrl = window.location.protocol + '//' + window.location.host + '/guest/share-1';
await expectAsync(service.share(show, songs)).toBeResolvedTo(expectedUrl);
@@ -45,8 +47,8 @@ describe('GuestShowService', () => {
});
it('should update an existing share and reuse its id in the returned url', async () => {
const show = {id: 'show-1', showType: 'service-worship', date: new Date(), shareId: 'share-9'} as any;
const songs = [{id: 'song-1'}] as any;
const show = {id: 'show-1', showType: 'service-worship', date: new Date(), shareId: 'share-9'} as unknown as Show;
const songs = [{id: 'song-1'}] as unknown as Song[];
const expectedUrl = window.location.protocol + '//' + window.location.host + '/guest/share-9';
await expectAsync(service.share(show, songs)).toBeResolvedTo(expectedUrl);

View File

@@ -0,0 +1,73 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {of} from 'rxjs';
import {GlobalSettingsService} from '../../../services/global-settings.service';
import {ShowService} from '../../shows/services/show.service';
import {SelectComponent} from './select.component';
describe('SelectComponent', () => {
let component: SelectComponent;
let fixture: ComponentFixture<SelectComponent>;
let showServiceSpy: jasmine.SpyObj<ShowService>;
let globalSettingsServiceSpy: jasmine.SpyObj<GlobalSettingsService>;
let routerSpy: jasmine.SpyObj<Router>;
beforeEach(async () => {
showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['list$', 'update$']);
globalSettingsServiceSpy = jasmine.createSpyObj<GlobalSettingsService>('GlobalSettingsService', ['set']);
routerSpy = jasmine.createSpyObj<Router>('Router', ['navigateByUrl']);
showServiceSpy.list$.and.returnValue(
of([
{id: 'older', date: {toDate: () => new Date('2025-12-15T00:00:00Z')}},
{id: 'recent-a', date: {toDate: () => new Date('2026-03-01T00:00:00Z')}},
{id: 'recent-b', date: {toDate: () => new Date('2026-02-20T00:00:00Z')}},
] as never)
);
showServiceSpy.update$.and.resolveTo();
globalSettingsServiceSpy.set.and.resolveTo();
routerSpy.navigateByUrl.and.resolveTo(true);
await TestBed.configureTestingModule({
imports: [SelectComponent],
providers: [
{provide: ShowService, useValue: showServiceSpy},
{provide: GlobalSettingsService, useValue: globalSettingsServiceSpy},
{provide: Router, useValue: routerSpy},
],
}).compileComponents();
fixture = TestBed.createComponent(SelectComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should become visible on init', () => {
component.ngOnInit();
expect(component.visible).toBeTrue();
});
it('should expose recent shows sorted descending by date', done => {
component.shows$.subscribe(shows => {
expect(showServiceSpy.list$).toHaveBeenCalledWith(true);
expect(shows.map(show => show.id)).toEqual(['recent-a', 'recent-b']);
done();
});
});
it('should persist the selected show, trigger presentation reset and navigate', async () => {
const show = {id: 'show-1'} as never;
component.visible = true;
await component.selectShow(show);
expect(component.visible).toBeFalse();
expect(globalSettingsServiceSpy.set).toHaveBeenCalledWith({currentShow: 'show-1'});
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {presentationSongId: 'title'});
expect(routerSpy.navigateByUrl).toHaveBeenCalledWith('/presentation/remote');
});
});

View File

@@ -0,0 +1,82 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ActivatedRoute, Router} from '@angular/router';
import {Timestamp} from '@angular/fire/firestore';
import {of} from 'rxjs';
import {ShowDataService} from '../services/show-data.service';
import {ShowService} from '../services/show.service';
import {EditComponent} from './edit.component';
describe('EditComponent', () => {
let component: EditComponent;
let fixture: ComponentFixture<EditComponent>;
let showServiceSpy: jasmine.SpyObj<ShowService>;
let showDataServiceStub: Pick<ShowDataService, 'list$'>;
let routerSpy: jasmine.SpyObj<Router>;
beforeEach(async () => {
showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['read$', 'update$']);
showDataServiceStub = {list$: of([] as never)};
routerSpy = jasmine.createSpyObj<Router>('Router', ['navigateByUrl']);
showServiceSpy.read$.and.returnValue(
of({
id: 'show-1',
showType: 'service-worship',
date: {toDate: () => new Date('2026-03-10T00:00:00Z')},
} as never)
);
showServiceSpy.update$.and.resolveTo();
routerSpy.navigateByUrl.and.resolveTo(true);
await TestBed.configureTestingModule({
imports: [EditComponent],
providers: [
{provide: ShowService, useValue: showServiceSpy},
{provide: ShowDataService, useValue: showDataServiceStub},
{provide: Router, useValue: routerSpy},
{provide: ActivatedRoute, useValue: {params: of({showId: 'show-1'})}},
],
}).compileComponents();
fixture = TestBed.createComponent(EditComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should load the current show into the form on init', () => {
component.ngOnInit();
expect(showServiceSpy.read$).toHaveBeenCalledWith('show-1');
expect(component.form.value.id).toBe('show-1');
expect(component.form.value.showType).toBe('service-worship');
expect(component.form.value.date).toEqual(new Date('2026-03-10T00:00:00Z'));
});
it('should not save when the form is invalid', async () => {
component.form.setValue({id: null, date: null, showType: null});
await component.onSave();
expect(showServiceSpy.update$).not.toHaveBeenCalled();
expect(routerSpy.navigateByUrl).not.toHaveBeenCalled();
});
it('should update the show and navigate back to the detail page', async () => {
const date = new Date('2026-03-11T00:00:00Z');
const firestoreTimestamp = {seconds: 1} as never;
spyOn(Timestamp, 'fromDate').and.returnValue(firestoreTimestamp);
component.form.setValue({id: 'show-1', date, showType: 'home-group'});
await component.onSave();
expect(Timestamp.fromDate).toHaveBeenCalledWith(date);
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {
date: firestoreTimestamp,
showType: 'home-group',
} as never);
expect(routerSpy.navigateByUrl).toHaveBeenCalledWith('/shows/show-1');
});
});

View File

@@ -16,7 +16,7 @@
<mat-form-field appearance="outline">
<mat-label>Ersteller</mat-label>
<mat-select formControlName="owner">
<mat-option [value]="null">Alle</mat-option>
<mat-option value="">Alle</mat-option>
@for (owner of owners; track owner) {
<mat-option [value]="owner.key">{{
owner.value
@@ -29,7 +29,7 @@
<mat-form-field appearance="outline">
<mat-label>Art der Veranstaltung</mat-label>
<mat-select formControlName="showType">
<mat-option [value]="null">Alle</mat-option>
<mat-option value="">Alle</mat-option>
<mat-optgroup label="öffentlich">
@for (key of showTypePublic; track key) {
<mat-option [value]="key">{{

View File

@@ -1,6 +1,5 @@
import {Component, Input, inject} from '@angular/core';
import {KeyValue} from '@angular/common';
import {ActivatedRoute, Router} from '@angular/router';
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup} from '@angular/forms';
import {FilterValues} from './filter-values';
import {Show} from '../../services/show';
@@ -9,6 +8,7 @@ import {distinctUntilChanged, map, switchMap} from 'rxjs/operators';
import {combineLatest, Observable, of} from 'rxjs';
import {dynamicSort, onlyUnique} from '../../../../services/filter.helper';
import {UserService} from '../../../../services/user/user.service';
import {FilterStoreService} from '../../../../services/filter-store.service';
import {MatFormField, MatLabel} from '@angular/material/form-field';
import {MatSelect} from '@angular/material/select';
import {MatOptgroup, MatOption} from '@angular/material/core';
@@ -21,11 +21,10 @@ import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translate
imports: [ReactiveFormsModule, MatFormField, MatLabel, MatSelect, MatOption, MatOptgroup, ShowTypePipe],
})
export class FilterComponent {
private router = inject(Router);
private showService = inject(ShowService);
private userService = inject(UserService);
private filterStore = inject(FilterStoreService);
@Input() public route = '/shows/';
@Input() public shows: Show[] = [];
public showTypePublic = ShowService.SHOW_TYPE_PUBLIC;
@@ -42,7 +41,6 @@ export class FilterComponent {
public owners: {key: string; value: string}[] = [];
public constructor() {
const activatedRoute = inject(ActivatedRoute);
const fb = inject(UntypedFormBuilder);
this.filterFormGroup = fb.group({
@@ -51,16 +49,20 @@ export class FilterComponent {
showType: null,
});
activatedRoute.queryParams.subscribe(params => {
const filterValues = params as FilterValues;
if (filterValues.time) this.filterFormGroup.controls.time.setValue(+filterValues.time);
this.filterFormGroup.controls.owner.setValue(filterValues.owner ?? null, {emitEvent: false});
this.filterFormGroup.controls.showType.setValue(filterValues.showType ?? null, {emitEvent: false});
this.filterStore.showFilter$.subscribe(filterValues => {
this.filterFormGroup.patchValue(
{
time: filterValues.time,
owner: filterValues.owner || null,
showType: filterValues.showType || null,
},
{emitEvent: false}
);
});
this.filterFormGroup.controls.time.valueChanges.subscribe(_ => void this.filerValueChanged('time', _ as number));
this.filterFormGroup.controls.owner.valueChanges.subscribe(_ => void this.filerValueChanged('owner', _ as string));
this.filterFormGroup.controls.showType.valueChanges.subscribe(_ => void this.filerValueChanged('showType', _ as string));
this.filterFormGroup.controls.time.valueChanges.subscribe(_ => this.filterValueChanged('time', (_ as number) ?? 1));
this.filterFormGroup.controls.owner.valueChanges.subscribe(_ => this.filterValueChanged('owner', (_ as string | null) ?? ''));
this.filterFormGroup.controls.showType.valueChanges.subscribe(_ => this.filterValueChanged('showType', (_ as string | null) ?? ''));
this.owners$().subscribe(owners => (this.owners = owners));
}
@@ -97,12 +99,8 @@ export class FilterComponent {
);
};
private async filerValueChanged<T>(key: string, value: T): Promise<void> {
const route = this.router.createUrlTree([this.route], {
queryParams: {[key]: value || null},
queryParamsHandling: 'merge',
});
await this.router.navigateByUrl(route);
private filterValueChanged<T>(key: keyof FilterValues, value: T): void {
this.filterStore.updateShowFilter({[key]: value} as Partial<FilterValues>);
}
private sameOwners(left: {key: string; value: string}[], right: {key: string; value: string}[]): boolean {

View File

@@ -4,8 +4,9 @@ import {Show} from '../services/show';
import {fade} from '../../../animations';
import {ShowService} from '../services/show.service';
import {FilterValues} from './filter/filter-values';
import {ActivatedRoute, RouterLink} from '@angular/router';
import {RouterLink} from '@angular/router';
import {map, switchMap} from 'rxjs/operators';
import {FilterStoreService} from '../../../services/filter-store.service';
import {RoleDirective} from '../../../services/user/role.directive';
import {ListHeaderComponent} from '../../../widget-modules/components/list-header/list-header.component';
import {AsyncPipe} from '@angular/common';
@@ -23,37 +24,20 @@ import {SortByPipe} from '../../../widget-modules/pipes/sort-by/sort-by.pipe';
})
export class ListComponent {
private showService = inject(ShowService);
private activatedRoute = inject(ActivatedRoute);
private filterStore = inject(FilterStoreService);
public lastMonths$ = this.activatedRoute.queryParams.pipe(
map(params => {
const filterValues = params as FilterValues;
if (!filterValues?.time) return 1;
return +filterValues.time;
})
);
public owner$ = this.activatedRoute.queryParams.pipe(
map(params => {
const filterValues = params as FilterValues;
return filterValues?.owner;
})
);
public showType$ = this.activatedRoute.queryParams.pipe(
map(params => {
const filterValues = params as FilterValues;
return filterValues?.showType;
})
);
public filter$ = this.filterStore.showFilter$;
public lastMonths$ = this.filter$.pipe(map((filterValues: FilterValues) => filterValues.time || 1));
public owner$ = this.filter$.pipe(map((filterValues: FilterValues) => filterValues.owner));
public showType$ = this.filter$.pipe(map((filterValues: FilterValues) => filterValues.showType));
public shows$ = this.showService.list$();
public privateShows$ = this.showService.list$().pipe(map(show => show.filter(_ => !_.published)));
public privateShows$ = combineLatest([this.shows$, this.filter$]).pipe(
map(([shows, filter]) => shows.filter(show => !show.published).filter(show => this.matchesPrivateFilter(show, filter)))
);
public queriedPublicShows$ = this.lastMonths$.pipe(switchMap(lastMonths => this.showService.listPublicSince$(lastMonths)));
public fallbackPublicShows$ = combineLatest([this.shows$, this.lastMonths$]).pipe(
map(([shows, lastMonths]) => {
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - lastMonths * 30);
return shows.filter(show => show.published && !show.archived && show.date.toDate() >= startDate);
return shows.filter(show => show.published && !show.archived).filter(show => this.matchesTimeFilter(show, lastMonths));
})
);
public publicShows$ = combineLatest([this.queriedPublicShows$, this.fallbackPublicShows$, this.owner$, this.showType$]).pipe(
@@ -65,4 +49,15 @@ export class ListComponent {
);
public trackBy = (index: number, show: unknown) => (show as Show).id;
private matchesPrivateFilter(show: Show, filter: FilterValues): boolean {
return this.matchesTimeFilter(show, filter.time || 1) && (!filter.showType || show.showType === filter.showType);
}
private matchesTimeFilter(show: Show, lastMonths: number): boolean {
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - lastMonths * 30);
return show.date.toDate() >= startDate;
}
}

View File

@@ -1,16 +1,56 @@
import {TestBed} from '@angular/core/testing';
import {Packer} from 'docx';
import {DocxService} from './docx.service';
describe('DocxService', () => {
let service: DocxService;
type DocxServiceInternals = DocxService & {
prepareData: (showId: string) => Promise<unknown>;
prepareNewDocument: (data: unknown, options?: unknown) => unknown;
saveAs: (blob: Blob, name: string) => void;
};
beforeEach(() => {
void TestBed.configureTestingModule({});
beforeEach(async () => {
await TestBed.configureTestingModule({});
service = TestBed.inject(DocxService);
});
it('should be created', () => {
void expect(service).toBeTruthy();
});
it('should not try to save a document when the required data cannot be prepared', async () => {
const serviceInternals = service as DocxServiceInternals;
const prepareDataSpy = spyOn(serviceInternals, 'prepareData').and.resolveTo(null);
const saveAsSpy = spyOn(serviceInternals, 'saveAs');
await service.create('show-1');
expect(prepareDataSpy).toHaveBeenCalledWith('show-1');
expect(saveAsSpy).not.toHaveBeenCalled();
});
it('should build and save a docx file when all data is available', async () => {
const blob = new Blob(['docx']);
const serviceInternals = service as DocxServiceInternals;
const prepareDataSpy = spyOn(serviceInternals, 'prepareData').and.resolveTo({
show: {
showType: 'service-worship',
date: {toDate: () => new Date('2026-03-10T00:00:00Z')},
},
songs: [],
user: {name: 'Benjamin'},
config: {ccliLicenseId: '12345'},
});
const prepareNewDocumentSpy = spyOn(serviceInternals, 'prepareNewDocument').and.returnValue({doc: true});
const saveAsSpy = spyOn(serviceInternals, 'saveAs');
spyOn(Packer, 'toBlob').and.resolveTo(blob);
await service.create('show-1', {copyright: true});
expect(prepareDataSpy).toHaveBeenCalledWith('show-1');
expect(prepareNewDocumentSpy).toHaveBeenCalled();
expect(Packer.toBlob).toHaveBeenCalledWith({doc: true} as never);
expect(saveAsSpy).toHaveBeenCalledWith(blob, jasmine.stringMatching(/\.docx$/));
});
});

View File

@@ -1,6 +1,6 @@
import {TestBed} from '@angular/core/testing';
import {firstValueFrom, of, Subject} from 'rxjs';
import {skip, take} from 'rxjs/operators';
import {take} from 'rxjs/operators';
import {DbService} from '../../../services/db.service';
import {ShowDataService} from './show-data.service';
@@ -13,7 +13,7 @@ describe('ShowDataService', () => {
let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => {
beforeEach(async () => {
shows$ = new Subject<Array<{id: string; date: {toMillis: () => number}; archived?: boolean}>>();
docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.returnValue({update: docUpdateSpy});
@@ -25,7 +25,7 @@ describe('ShowDataService', () => {
dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy);
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});
@@ -76,11 +76,7 @@ describe('ShowDataService', () => {
});
it('should request only published recent shows and filter archived entries', async () => {
const publicShows$ = of([
{id: 'show-1', archived: false},
{id: 'show-2', archived: true},
{id: 'show-3'},
]);
const publicShows$ = of([{id: 'show-1', archived: false}, {id: 'show-2', archived: true}, {id: 'show-3'}]);
dbServiceSpy.col$.and.returnValue(publicShows$ as never);
const result = await firstValueFrom(service.listPublicSince$(3));

View File

@@ -24,12 +24,15 @@ export class ShowDataService {
public listRaw$ = () => this.dbService.col$<Show>(this.collection);
public listPublicSince$(lastMonths: number): Observable<Show[]> {
const queryConstraints: QueryConstraint[] = [where('published', '==', true), orderBy('date', 'desc')];
if (lastMonths < 99999) {
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - lastMonths * 30);
const startTimestamp = Timestamp.fromDate(startDate);
const queryConstraints: QueryConstraint[] = [where('published', '==', true), where('date', '>=', startTimestamp), orderBy('date', 'desc')];
queryConstraints.splice(1, 0, where('date', '>=', startTimestamp));
}
return this.dbService.col$<Show>(this.collection, queryConstraints).pipe(
map(shows => shows.filter(show => !show.archived)),

View File

@@ -12,7 +12,7 @@ describe('ShowSongDataService', () => {
let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => {
beforeEach(async () => {
docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.returnValue({
@@ -27,7 +27,7 @@ describe('ShowSongDataService', () => {
dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy);
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});

View File

@@ -5,6 +5,10 @@ import {UserService} from '../../../services/user/user.service';
import {ShowService} from './show.service';
import {ShowSongDataService} from './show-song-data.service';
import {ShowSongService} from './show-song.service';
import {ShowSong} from './show-song';
import {Song} from '../../songs/services/song';
import {Show} from './show';
import {User} from '../../../services/user/user';
describe('ShowSongService', () => {
let service: ShowSongService;
@@ -12,13 +16,13 @@ describe('ShowSongService', () => {
let songDataServiceSpy: jasmine.SpyObj<SongDataService>;
let userServiceSpy: jasmine.SpyObj<UserService>;
let showServiceSpy: jasmine.SpyObj<ShowService>;
let user$: BehaviorSubject<any>;
const song = {id: 'song-1', key: 'G', title: 'Amazing Grace'} as any;
const showSong = {id: 'show-song-1', songId: 'song-1'} as any;
const show = {id: 'show-1', order: ['show-song-1', 'show-song-2']} as any;
let user$: BehaviorSubject<User | null>;
const song = {id: 'song-1', key: 'G', title: 'Amazing Grace'} as unknown as Song;
const showSong = {id: 'show-song-1', songId: 'song-1'} as unknown as ShowSong;
const show = {id: 'show-1', order: ['show-song-1', 'show-song-2']} as unknown as Show;
beforeEach(() => {
user$ = new BehaviorSubject<any>({id: 'user-1', name: 'Benjamin', role: 'editor', chordMode: 'letters', songUsage: {}});
beforeEach(async () => {
user$ = new BehaviorSubject<User | null>({id: 'user-1', name: 'Benjamin', role: 'editor', chordMode: 'letters', songUsage: {}});
showSongDataServiceSpy = jasmine.createSpyObj<ShowSongDataService>('ShowSongDataService', ['add', 'read$', 'list$', 'delete', 'update$']);
songDataServiceSpy = jasmine.createSpyObj<SongDataService>('SongDataService', ['read$']);
userServiceSpy = jasmine.createSpyObj<UserService>('UserService', ['incSongCount', 'decSongCount'], {
@@ -37,7 +41,7 @@ describe('ShowSongService', () => {
showServiceSpy.read$.and.returnValue(of(show));
showServiceSpy.update$.and.resolveTo();
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [
{provide: ShowSongDataService, useValue: showSongDataServiceSpy},
{provide: SongDataService, useValue: songDataServiceSpy},

View File

@@ -14,7 +14,7 @@ describe('ShowService', () => {
{id: 'show-3', owner: 'user-1', published: true, archived: true},
] as never;
beforeEach(() => {
beforeEach(async () => {
user$ = new BehaviorSubject<unknown>({id: 'user-1'});
showDataServiceSpy = jasmine.createSpyObj<ShowDataService>('ShowDataService', ['read$', 'listPublicSince$', 'update', 'add'], {
list$: of(shows),
@@ -24,7 +24,7 @@ describe('ShowService', () => {
showDataServiceSpy.update.and.resolveTo();
showDataServiceSpy.add.and.resolveTo('new-show-id');
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [
{provide: ShowDataService, useValue: showDataServiceSpy},
{provide: UserService, useValue: {user$: user$.asObservable()}},

View File

@@ -31,13 +31,14 @@
@if (showSongs && !useSwiper) {
<div (cdkDropListDropped)="drop($event, show)"
[cdkDropListDisabled]="show.published || showText"
[style.cursor]="!(show.published || showText) ? 'drag' : 'inherit'"
[style.--song-key-column-width]="getSongKeyColumnWidth(show)"
[style.font-size]="textSize + 'em'"
cdkDropList
class="song-list">
@for (song of orderedShowSongs(show); track trackBy(i, song); let i = $index) {
<div cdkDrag class="song-row">
<app-song
[dragHandle]="!(show.published || showText)"
[fullscreen]="useSwiper"
[index]="i"
[showId]="showId"

View File

@@ -255,6 +255,20 @@ export class ShowComponent implements OnInit, OnDestroy {
const song = showSongs[i + 1];
return song?.title ?? '';
}
public getSongKeyColumnWidth(show: Show): string {
const labels = this.orderedShowSongs(show).map(song => {
if (song.keyOriginal && song.keyOriginal !== song.key) {
return `${song.keyOriginal} -> ${song.key}`;
}
return song.key ?? '';
});
const longestLabelLength = labels.reduce((max, label) => Math.max(max, label.length), 0);
const widthInCh = Math.max(3, longestLabelLength);
return `${widthInCh}ch`;
}
}
export interface Swiper {

View File

@@ -7,24 +7,30 @@
</div>
}
@if (!show.published && !fullscreen) {
<div class="song">
<div
class="song"
[class.show-text-layout]="!!showText"
[class.compact-layout]="!showText"
[class.with-drag]="dragHandle && !edit"
>
@if (dragHandle && !edit) {
<button
aria-label="Lied verschieben"
cdkDragHandle
class="drag-handle"
type="button"
></button>
}
<span class="title">{{ iSong.title }}</span>
@if (!edit) {
<span class="keys">
<div class="keys-container">
<div (click)="openKeySelect()" class="keys">
@if (iSong.keyOriginal !== iSong.key) {
<span>{{ iSong.keyOriginal }}&nbsp;&nbsp;</span>
}<span
(click)="openKeySelect()">{{ iSong.key }}</span>
@if (keys) {
<mat-form-field (click)="option.open()" class="transpose">
<mat-select #option [formControl]="keyFormControl">
@for (key of keys; track key) {
<mat-option [value]="key">{{ key }}</mat-option>
}
</mat-select>
</mat-form-field>
}
</span>
<span>{{ iSong.key }}</span>
</div>
</div>
}
@if (!edit) {
<app-menu-button (click)="onEdit()" [icon]="faEdit" class="btn-edit btn-icon"
@@ -35,6 +41,44 @@
matTooltip="Lied aus Veranstaltung entfernen"></app-menu-button>
}
</div>
@if (!edit) {
<div
aria-hidden="true"
class="song select"
[class.show-text-layout]="!!showText"
[class.compact-layout]="!showText"
[class.with-drag]="dragHandle"
>
@if (dragHandle) {
<span class="drag-handle-placeholder"></span>
}
@if (!showText) {
<span class="keys">
<mat-form-field class="keys-select">
<mat-select #option [formControl]="keyFormControl" tabIndex="-1">
@for (key of keys; track key) {
<mat-option [value]="key">{{ key }}</mat-option>
}
</mat-select>
</mat-form-field>
</span>
<span class="title"></span>
} @else {
<span class="title"></span>
<span class="keys">
<mat-form-field class="keys-select">
<mat-select #option [formControl]="keyFormControl" tabIndex="-1">
@for (key of keys; track key) {
<mat-option [value]="key">{{ key }}</mat-option>
}
</mat-select>
</mat-form-field>
</span>
}
<span class="btn-edit"></span>
<span class="btn-delete"></span>
</div>
}
}
@if (edit) {
<mat-form-field appearance="outline">

View File

@@ -1,12 +1,10 @@
.song {
&:not(.select) {
min-height: 28px;
display: grid;
grid-template-columns: auto 70px 25px 25px;
@media screen and (max-width: 860px) {
grid-template-columns: auto 70px 45px 45px;
}
grid-template-areas: "title keys edit delete";
display: grid;
& > * {
display: flex;
@@ -14,12 +12,109 @@
}
overflow: hidden;
&.compact-layout {
grid-template-columns: var(--song-key-column-width, 30px) auto 25px 25px;
grid-template-areas: "keys title edit delete";
@media screen and (max-width: 860px) {
grid-template-columns: var(--song-key-column-width, 30px) auto 45px 45px;
}
&.with-drag {
grid-template-columns: 24px var(--song-key-column-width, 30px) auto 25px 25px;
grid-template-areas: "drag keys title edit delete";
@media screen and (max-width: 860px) {
grid-template-columns: 24px var(--song-key-column-width, 30px) auto 45px 45px;
}
}
}
&.show-text-layout {
grid-template-columns: auto var(--song-key-column-width, 30px) 25px 25px;
grid-template-areas: "title keys edit delete";
@media screen and (max-width: 860px) {
grid-template-columns: auto var(--song-key-column-width, 30px) 45px 45px;
}
&.with-drag {
grid-template-columns: 24px auto var(--song-key-column-width, 30px) 25px 25px;
grid-template-areas: "drag title keys edit delete";
@media screen and (max-width: 860px) {
grid-template-columns: 24px auto var(--song-key-column-width, 30px) 45px 45px;
}
}
}
}
.drag-handle,
.drag-handle-placeholder {
grid-area: drag;
}
.drag-handle {
width: 16px;
height: 36px;
padding: 4px 0;
border: 0;
background: transparent;
cursor: grab;
justify-self: start;
position: relative;
&::before {
content: "";
width: 10px;
height: 18px;
display: block;
border-radius: 999px;
background-image: radial-gradient(circle, var(--text-soft) 1.2px, transparent 1.3px),
radial-gradient(circle, var(--text-soft) 1.2px, transparent 1.3px);
background-position: 0 0, 6px 0;
background-size: 6px 6px;
background-repeat: repeat-y;
opacity: 0.65;
transition: var(--transition);
}
&:hover::before {
opacity: 1;
background-image: radial-gradient(circle, var(--primary-color) 1.2px, transparent 1.3px),
radial-gradient(circle, var(--primary-color) 1.2px, transparent 1.3px);
}
&:active {
cursor: grabbing;
}
}
.drag-handle-placeholder {
width: 16px;
}
.keys-container {
display: flex;
flex-direction: column;
}
.keys-select {
height: 0;
overflow: hidden;
line-height: 0;
min-width: max(100px, var(--song-key-column-width, 30px));
}
.keys {
display: flex;
align-items: center;
position: relative;
margin-right: 10px;
cursor: pointer;
flex-grow: 0;
height: 100%;
&:hover {
color: var(--color-primary);
@@ -41,6 +136,7 @@
.title {
grid-area: title;
min-width: 0;
&.published {
margin: 10px 0;

View File

@@ -17,6 +17,7 @@ import {MatInput} from '@angular/material/input';
import {CdkTextareaAutosize} from '@angular/cdk/text-field';
import {ButtonRowComponent} from '../../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../../widget-modules/components/button/button.component';
import {CdkDragHandle} from '@angular/cdk/drag-drop';
@Component({
selector: 'app-song',
@@ -36,6 +37,7 @@ import {ButtonComponent} from '../../../../widget-modules/components/button/butt
ButtonRowComponent,
ButtonComponent,
SongTextComponent,
CdkDragHandle,
],
})
export class SongComponent implements OnInit {
@@ -44,6 +46,7 @@ export class SongComponent implements OnInit {
@Input() public show: Show | null = null;
@Input() public showId: string | null = null;
@Input() public showText: boolean | null = null;
@Input() public dragHandle = false;
@Input() public index = -1;
@Input() public fullscreen = false;
public keys: string[] = [];

View File

@@ -1,7 +1,29 @@
export interface ChordAddDescriptor {
raw: string;
quality: 'major' | 'minor' | 'diminished' | 'augmented' | null;
extensions: string[];
additions: string[];
suspensions: string[];
alterations: string[];
modifiers: string[];
}
export interface ChordValidationIssue {
lineNumber: number;
lineText: string;
token: string;
suggestion: string | null;
reason: 'alias' | 'minor_format' | 'major_format' | 'invalid_suffix' | 'unknown_token' | 'tab_character';
message: string;
}
export interface Chord {
chord: string;
length: number;
position: number;
slashChord: string | null;
add: string | null;
addDescriptor?: ChordAddDescriptor | null;
prefix?: string;
suffix?: string;
}

View File

@@ -12,7 +12,7 @@ describe('FileDataService', () => {
let fileDeleteSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => {
beforeEach(async () => {
filesCollectionValueChangesSpy = jasmine.createSpy('valueChanges').and.returnValue(of([{id: 'file-1', name: 'plan.pdf'}]));
filesCollectionAddSpy = jasmine.createSpy('add').and.resolveTo({id: 'file-2'});
songDocCollectionSpy = jasmine.createSpy('collection').and.returnValue({
@@ -30,7 +30,7 @@ describe('FileDataService', () => {
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['doc']);
dbServiceSpy.doc.and.callFake(songDocSpy);
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});

View File

@@ -1,23 +1,48 @@
import {TestBed} from '@angular/core/testing';
import {Storage} from '@angular/fire/storage';
import {FileService} from './file.service';
import {FileDataService} from './file-data.service';
import {FileService} from './file.service';
describe('FileService', () => {
let service: FileService;
let fileDataServiceSpy: jasmine.SpyObj<FileDataService>;
type FileServiceInternals = FileService & {
resolveDownloadUrl: (path: string) => Promise<string>;
deleteFromStorage: (path: string) => Promise<void>;
};
beforeEach(() => {
void TestBed.configureTestingModule({
beforeEach(async () => {
fileDataServiceSpy = jasmine.createSpyObj<FileDataService>('FileDataService', ['delete']);
fileDataServiceSpy.delete.and.resolveTo();
await TestBed.configureTestingModule({
providers: [
{provide: Storage, useValue: {}},
{provide: FileDataService, useValue: {delete: () => Promise.resolve()}},
{provide: Storage, useValue: {app: 'test-storage'}},
{provide: FileDataService, useValue: fileDataServiceSpy},
],
});
service = TestBed.inject(FileService);
});
it('should be created', () => {
void expect(service).toBeTruthy();
expect(service).toBeTruthy();
});
it('should resolve download urls via AngularFire storage helpers', async () => {
const resolveSpy = spyOn(service as FileServiceInternals, 'resolveDownloadUrl').and.resolveTo('https://cdn.example/file.pdf');
await expectAsync(service.getDownloadUrl('songs/song-1/file.pdf').toPromise()).toBeResolvedTo('https://cdn.example/file.pdf');
expect(resolveSpy).toHaveBeenCalledWith('songs/song-1/file.pdf');
});
it('should delete the file from storage and metadata from firestore', async () => {
const deleteFromStorageSpy = spyOn(service as FileServiceInternals, 'deleteFromStorage').and.resolveTo();
await service.delete('songs/song-1/file.pdf', 'song-1', 'file-1');
expect(deleteFromStorageSpy).toHaveBeenCalledWith('songs/song-1/file.pdf');
expect(fileDataServiceSpy.delete).toHaveBeenCalledWith('song-1', 'file-1');
});
});

View File

@@ -1,4 +1,4 @@
import {EnvironmentInjector, Injectable, inject, runInInjectionContext} from '@angular/core';
import {EnvironmentInjector, inject, Injectable, runInInjectionContext} from '@angular/core';
import {deleteObject, getDownloadURL, ref, Storage} from '@angular/fire/storage';
import {from, Observable} from 'rxjs';
import {FileDataService} from './file-data.service';
@@ -12,11 +12,19 @@ export class FileService {
private environmentInjector = inject(EnvironmentInjector);
public getDownloadUrl(path: string): Observable<string> {
return from(runInInjectionContext(this.environmentInjector, () => getDownloadURL(ref(this.storage, path))));
return from(runInInjectionContext(this.environmentInjector, () => this.resolveDownloadUrl(path)));
}
public delete(path: string, songId: string, fileId: string): void {
void runInInjectionContext(this.environmentInjector, () => deleteObject(ref(this.storage, path)));
void runInInjectionContext(this.environmentInjector, () => this.deleteFromStorage(path));
void this.fileDataService.delete(songId, fileId);
}
private resolveDownloadUrl(path: string): Promise<string> {
return getDownloadURL(ref(this.storage, path));
}
private deleteFromStorage(path: string): Promise<void> {
return deleteObject(ref(this.storage, path));
}
}

View File

@@ -5,4 +5,5 @@ export interface Line {
type: LineType;
text: string;
chords: Chord[] | null;
lineNumber?: number;
}

View File

@@ -1,6 +1,6 @@
import {TestBed} from '@angular/core/testing';
import {firstValueFrom, Subject} from 'rxjs';
import {skip, take, toArray} from 'rxjs/operators';
import {take, toArray} from 'rxjs/operators';
import {DbService} from '../../../services/db.service';
import {SongDataService} from './song-data.service';
@@ -14,7 +14,7 @@ describe('SongDataService', () => {
let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => {
beforeEach(async () => {
songs$ = new Subject<Array<{id: string; title: string}>>();
docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
@@ -32,7 +32,7 @@ describe('SongDataService', () => {
dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy);
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});

View File

@@ -11,13 +11,20 @@ export class SongDataService {
private dbService = inject(DbService);
private collection = 'songs';
public list$: Observable<Song[]> = this.dbService.col$<Song>(this.collection).pipe(
private loadedList$: Observable<Song[]> = this.dbService.col$<Song>(this.collection).pipe(
shareReplay({
bufferSize: 1,
refCount: false, // keep the listener alive after first subscription to avoid reloading on navigation
})
);
public list$: Observable<Song[]> = this.loadedList$.pipe(
startWith([] as Song[]), // immediate empty emit keeps UI responsive while first snapshot arrives
shareReplay({
bufferSize: 1,
refCount: false, // keep the listener alive after first subscription to avoid reloading on navigation
})
);
public listLoaded$ = (): Observable<Song[]> => this.loadedList$;
public read$ = (songId: string): Observable<Song | null> => this.dbService.doc$(this.collection + '/' + songId);
public update$ = async (songId: string, data: Partial<Song>): Promise<void> => await this.dbService.doc(this.collection + '/' + songId).update(data);

View File

@@ -0,0 +1,32 @@
import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {SongService} from './song.service';
import {SongListResolver} from './song-list.resolver';
describe('SongListResolver', () => {
let resolver: SongListResolver;
let songServiceSpy: jasmine.SpyObj<SongService>;
beforeEach(async () => {
songServiceSpy = jasmine.createSpyObj<SongService>('SongService', ['list$']);
songServiceSpy.list$.and.returnValue(of([{id: 'song-1', title: 'Amazing Grace'}] as never));
await TestBed.configureTestingModule({
providers: [{provide: SongService, useValue: songServiceSpy}],
});
resolver = TestBed.inject(SongListResolver);
});
it('should be created', () => {
expect(resolver).toBeTruthy();
});
it('should resolve the first emitted song list from the service', done => {
resolver.resolve().subscribe(songs => {
expect(songServiceSpy.list$).toHaveBeenCalled();
expect(songs).toEqual([{id: 'song-1', title: 'Amazing Grace'}] as never);
done();
});
});
});

View File

@@ -12,6 +12,6 @@ export class SongListResolver {
private songService = inject(SongService);
public resolve(): Observable<Song[]> {
return this.songService.list$().pipe(take(1));
return this.songService.listLoaded$().pipe(take(1));
}
}

View File

@@ -15,7 +15,7 @@ describe('SongService', () => {
edits: [],
} as never;
beforeEach(() => {
beforeEach(async () => {
songDataServiceSpy = jasmine.createSpyObj<SongDataService>('SongDataService', ['read$', 'update$', 'add', 'delete'], {
list$: of([song]),
});
@@ -27,7 +27,7 @@ describe('SongService', () => {
songDataServiceSpy.delete.and.resolveTo();
userServiceSpy.currentUser.and.resolveTo({name: 'Benjamin'} as never);
void TestBed.configureTestingModule({
await TestBed.configureTestingModule({
providers: [
{provide: SongDataService, useValue: songDataServiceSpy},
{provide: UserService, useValue: userServiceSpy},

View File

@@ -26,6 +26,7 @@ export class SongService {
public static LEGAL_TYPE: SongLegalType[] = ['open', 'allowed'];
public list$ = (): Observable<Song[]> => this.songDataService.list$; //.pipe(tap(_ => (this.list = _)));
public listLoaded$ = (): Observable<Song[]> => this.songDataService.listLoaded$();
public read$ = (songId: string): Observable<Song | null> => this.songDataService.read$(songId);
public read = (songId: string): Promise<Song | null> => firstValueFrom(this.read$(songId));

View File

@@ -2,8 +2,22 @@ import {TestBed} from '@angular/core/testing';
import {TextRenderingService} from './text-rendering.service';
import {LineType} from './line-type';
import {SectionType} from './section-type';
import {TransposeService} from './transpose.service';
import {ChordAddDescriptor} from './chord';
describe('TextRenderingService', () => {
const descriptor = (raw: string, partial: Partial<ChordAddDescriptor>) =>
jasmine.objectContaining({
raw,
quality: null,
extensions: [],
additions: [],
suspensions: [],
alterations: [],
modifiers: [],
...partial,
});
const testText = `Strophe
C D E F G A H
Text Line 1-1
@@ -31,6 +45,7 @@ Cool bridge without any chords
void expect(service).toBeTruthy();
});
describe('section parsing', () => {
it('should parse section types', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const sections = service.parse(testText, null);
@@ -44,6 +59,53 @@ Cool bridge without any chords
void expect(sections[3].number).toBe(0);
});
it('should accept section headers with numbering and lowercase letters', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `strophe 1
Text A
Refrain 2
Text B`;
const sections = service.parse(text, null);
void expect(sections.length).toBe(2);
void expect(sections[0].type).toBe(SectionType.Verse);
void expect(sections[1].type).toBe(SectionType.Chorus);
});
it('should return an empty array for empty input', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
void expect(service.parse('', null)).toEqual([]);
});
it('should ignore content before the first recognized section header', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Intro ohne Section
Noch eine Zeile
Strophe
Text`;
const sections = service.parse(text, null);
void expect(sections.length).toBe(1);
void expect(sections[0].lines.length).toBe(1);
void expect(sections[0].lines[0].text).toBe('Text');
});
it('should support windows line endings', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = 'Strophe\r\nC D E\r\nText\r\nRefrain\r\nG A H';
const sections = service.parse(text, null);
void expect(sections.length).toBe(2);
void expect(sections[0].lines[0].type).toBe(LineType.chord);
void expect(sections[1].lines[0].type).toBe(LineType.chord);
});
});
describe('comments and text lines', () => {
it('should parse text lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const sections = service.parse(testText, null);
@@ -61,6 +123,66 @@ Cool bridge without any chords
void expect(sections[3].lines[0].text).toBe('Cool bridge without any chords');
});
it('should ignore indented comment lines when comments are disabled', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
# hidden comment
Text`;
const sections = service.parse(text, null, false);
void expect(sections[0].lines.length).toBe(1);
void expect(sections[0].lines[0].text).toBe('Text');
});
it('should keep comment lines when comments are enabled', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
# Kommentar
Text`;
const sections = service.parse(text, null, true);
void expect(sections[0].lines.length).toBe(2);
void expect(sections[0].lines[0].text).toBe('# Kommentar');
void expect(sections[0].lines[1].text).toBe('Text');
});
it('should not classify ordinary text with isolated note letters as a chord line', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Anna geht heute baden
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].type).toBe(LineType.text);
void expect(sections[0].lines[0].chords).toBeNull();
});
it('should treat compact prose-like tokens as text when the chord ratio is too low', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Das ist C nicht D sondern Text
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].type).toBe(LineType.text);
void expect(sections[0].lines[0].chords).toBeNull();
});
it('should ignore prose lines even if they contain note-like words', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Heute singt Fis nicht mit
Text`;
void expect(service.validateChordNotation(text)).toEqual([]);
});
});
describe('chord parsing', () => {
it('should parse chord lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const sections = service.parse(testText, null);
@@ -75,14 +197,13 @@ Cool bridge without any chords
void expect(sections[2].lines[0].type).toBe(LineType.chord);
void expect(sections[2].lines[0].text).toBe('c c♯ d♭ c7 cmaj7 c/e');
// c c# db c7 cmaj7 c/e
void expect(sections[2].lines[0].chords).toEqual([
{chord: 'c', length: 1, position: 0, add: null, slashChord: null},
{chord: 'c#', length: 2, position: 2, add: null, slashChord: null},
{chord: 'db', length: 2, position: 5, add: null, slashChord: null},
{chord: 'c', length: 2, position: 8, add: '7', slashChord: null},
{chord: 'c', length: 5, position: 13, add: 'maj7', slashChord: null},
{chord: 'c', length: 3, position: 22, add: null, slashChord: 'e'},
{chord: 'c', length: 1, position: 0, add: null, slashChord: null, addDescriptor: null},
{chord: 'c#', length: 2, position: 2, add: null, slashChord: null, addDescriptor: null},
{chord: 'db', length: 2, position: 5, add: null, slashChord: null, addDescriptor: null},
{chord: 'c', length: 2, position: 8, add: '7', slashChord: null, addDescriptor: descriptor('7', {extensions: ['7']})},
{chord: 'c', length: 5, position: 13, add: 'maj7', slashChord: null, addDescriptor: descriptor('maj7', {quality: 'major', extensions: ['7']})},
{chord: 'c', length: 3, position: 22, add: null, slashChord: 'e', addDescriptor: null},
]);
});
@@ -97,4 +218,284 @@ text`;
void expect(sections[0].lines[1].type).toBe(LineType.text);
void expect(sections[0].lines[1].text).toBe('text');
});
it('should preserve exact chord positions for spaced chord lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
C G/B Am
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].chords).toEqual([
{chord: 'C', length: 1, position: 0, add: null, slashChord: null, addDescriptor: null},
{chord: 'G', length: 3, position: 8, add: null, slashChord: 'B', addDescriptor: null},
{chord: 'A', length: 2, position: 17, add: 'm', slashChord: null, addDescriptor: descriptor('m', {quality: 'minor'})},
]);
});
it('should parse common international chord suffixes and slash chords after the suffix', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Cmaj7 Dm7 Gsus4 Aadd9 Cmaj7/E
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].type).toBe(LineType.chord);
void expect(sections[0].lines[0].chords).toEqual([
{chord: 'C', length: 5, position: 0, add: 'maj7', slashChord: null, addDescriptor: descriptor('maj7', {quality: 'major', extensions: ['7']})},
{chord: 'D', length: 3, position: 6, add: 'm7', slashChord: null, addDescriptor: descriptor('m7', {quality: 'minor', extensions: ['7']})},
{chord: 'G', length: 5, position: 10, add: 'sus4', slashChord: null, addDescriptor: descriptor('sus4', {suspensions: ['4']})},
{chord: 'A', length: 5, position: 16, add: 'add9', slashChord: null, addDescriptor: descriptor('add9', {additions: ['9']})},
{chord: 'C', length: 7, position: 22, add: 'maj7', slashChord: 'E', addDescriptor: descriptor('maj7', {quality: 'major', extensions: ['7']})},
]);
});
it('should parse german chord suffixes', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Hmoll Edur Cverm Faug
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].type).toBe(LineType.chord);
void expect(sections[0].lines[0].chords).toEqual([
{chord: 'H', length: 5, position: 0, add: 'moll', slashChord: null, addDescriptor: descriptor('moll', {quality: 'minor'})},
{chord: 'E', length: 4, position: 6, add: 'dur', slashChord: null, addDescriptor: descriptor('dur', {quality: 'major'})},
{chord: 'C', length: 5, position: 11, add: 'verm', slashChord: null, addDescriptor: descriptor('verm', {quality: 'diminished'})},
{chord: 'F', length: 4, position: 17, add: 'aug', slashChord: null, addDescriptor: descriptor('aug', {quality: 'augmented'})},
]);
});
it('should parse numeric and altered chord suffixes', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
C7 D9 E11 F13 Gadd#9 A7-5
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].chords).toEqual([
{chord: 'C', length: 2, position: 0, add: '7', slashChord: null, addDescriptor: descriptor('7', {extensions: ['7']})},
{chord: 'D', length: 2, position: 3, add: '9', slashChord: null, addDescriptor: descriptor('9', {extensions: ['9']})},
{chord: 'E', length: 3, position: 6, add: '11', slashChord: null, addDescriptor: descriptor('11', {extensions: ['11']})},
{chord: 'F', length: 3, position: 10, add: '13', slashChord: null, addDescriptor: descriptor('13', {extensions: ['13']})},
{chord: 'G', length: 6, position: 14, add: 'add#9', slashChord: null, addDescriptor: descriptor('add#9', {additions: ['#9']})},
{chord: 'A', length: 4, position: 21, add: '7-5', slashChord: null, addDescriptor: descriptor('7-5', {extensions: ['7'], alterations: ['-5']})},
]);
});
it('should parse lowercase roots with suffixes and slash chords', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
emoll d/F# cmaj7/e
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].chords).toEqual([
{chord: 'e', length: 5, position: 0, add: 'moll', slashChord: null, addDescriptor: descriptor('moll', {quality: 'minor'})},
{chord: 'd', length: 4, position: 6, add: null, slashChord: 'F#', addDescriptor: null},
{chord: 'c', length: 7, position: 11, add: 'maj7', slashChord: 'e', addDescriptor: descriptor('maj7', {quality: 'major', extensions: ['7']})},
]);
});
it('should expose semantic descriptors for complex chord additions', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Cmaj7(add9) Dm7 Gsus4 A7-5
Text`;
const sections = service.parse(text, null);
const chords = sections[0].lines[0].chords ?? [];
void expect(chords[0].addDescriptor).toEqual(
descriptor('maj7(add9)', {
quality: 'major',
extensions: ['7'],
modifiers: ['(add9)'],
})
);
void expect(chords[1].addDescriptor).toEqual(descriptor('m7', {quality: 'minor', extensions: ['7']}));
void expect(chords[2].addDescriptor).toEqual(descriptor('sus4', {suspensions: ['4']}));
void expect(chords[3].addDescriptor).toEqual(descriptor('7-5', {extensions: ['7'], alterations: ['-5']}));
});
it('should not misinterpret modifier parentheses as group wrappers', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Cmaj7(add9)
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].text).toBe('Cmaj7(add9)');
void expect(sections[0].lines[0].chords).toEqual([
{
chord: 'C',
length: 11,
position: 0,
add: 'maj7(add9)',
slashChord: null,
addDescriptor: descriptor('maj7(add9)', {
quality: 'major',
extensions: ['7'],
modifiers: ['(add9)'],
}),
},
]);
void expect(service.validateChordNotation(text)).toEqual([]);
});
});
describe('parenthesized groups', () => {
it('should keep parentheses around alternative chord groups', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
C F G e C (F G)
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].type).toBe(LineType.chord);
void expect(sections[0].lines[0].text).toBe('C F G e C (F G)');
void expect(sections[0].lines[0].chords).toEqual([
{chord: 'C', length: 1, position: 0, add: null, slashChord: null, addDescriptor: null},
{chord: 'F', length: 1, position: 2, add: null, slashChord: null, addDescriptor: null},
{chord: 'G', length: 1, position: 4, add: null, slashChord: null, addDescriptor: null},
{chord: 'e', length: 1, position: 6, add: null, slashChord: null, addDescriptor: null},
{chord: 'C', length: 1, position: 8, add: null, slashChord: null, addDescriptor: null},
{chord: 'F', length: 2, position: 11, add: null, slashChord: null, addDescriptor: null, prefix: '('},
{chord: 'G', length: 2, position: 14, add: null, slashChord: null, addDescriptor: null, suffix: ')'},
]);
});
it('should transpose multiple chords inside a parenthesized group', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
C F G e C (F G)
Text`;
const sections = service.parse(text, {baseKey: 'C', targetKey: 'D'});
void expect(sections[0].lines[0].type).toBe(LineType.chord);
void expect(sections[0].lines[0].text).toBe('D G A f♯ D (G A)');
});
});
describe('transpose integration', () => {
it('should call the transpose service when a transpose mode is provided', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const transposeService = TestBed.inject(TransposeService);
const transposeSpy = spyOn(transposeService, 'transpose').and.callThrough();
const renderSpy = spyOn(transposeService, 'renderChords').and.callThrough();
const text = `Strophe
C D E
Text`;
service.parse(text, {baseKey: 'C', targetKey: 'D'});
void expect(transposeSpy).toHaveBeenCalledTimes(2);
void expect(renderSpy).not.toHaveBeenCalled();
});
it('should use renderChords when no transpose mode is provided', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const transposeService = TestBed.inject(TransposeService);
const transposeSpy = spyOn(transposeService, 'transpose').and.callThrough();
const renderSpy = spyOn(transposeService, 'renderChords').and.callThrough();
const text = `Strophe
C D E
Text`;
service.parse(text, null);
void expect(renderSpy).toHaveBeenCalledTimes(2);
void expect(transposeSpy).not.toHaveBeenCalled();
});
});
describe('notation validation', () => {
it('should report non-canonical sharp and flat aliases on chord lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Fis Hmoll Des/Fis
Text`;
void expect(service.validateChordNotation(text)).toEqual([
jasmine.objectContaining({lineNumber: 2, token: 'Fis', suggestion: 'F#', reason: 'alias'}),
jasmine.objectContaining({lineNumber: 2, token: 'Hmoll', suggestion: 'h', reason: 'minor_format'}),
jasmine.objectContaining({lineNumber: 2, token: 'Des/Fis', suggestion: 'Db/F#', reason: 'alias'}),
]);
});
it('should report uppercase minor and lowercase major chord notation', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Am Dm7 cdur C
Text`;
void expect(service.validateChordNotation(text)).toEqual([
jasmine.objectContaining({lineNumber: 2, token: 'Am', suggestion: 'a', reason: 'minor_format'}),
jasmine.objectContaining({lineNumber: 2, token: 'Dm7', suggestion: 'd7', reason: 'minor_format'}),
jasmine.objectContaining({lineNumber: 2, token: 'cdur', suggestion: 'C', reason: 'major_format'}),
]);
});
it('should keep slash bass notes uppercase in canonical minor suggestions', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
Am/C# Dm7/F#
Text`;
void expect(service.validateChordNotation(text)).toEqual([
jasmine.objectContaining({lineNumber: 2, token: 'Am/C#', suggestion: 'a/C#', reason: 'minor_format'}),
jasmine.objectContaining({lineNumber: 2, token: 'Dm7/F#', suggestion: 'd7/F#', reason: 'minor_format'}),
]);
});
it('should keep mostly-chord lines with unknown tokens in chord mode', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
C Es G
Text`;
const sections = service.parse(text, null);
void expect(sections[0].lines[0].type).toBe(LineType.chord);
void expect(sections[0].lines[0].text).toBe('C Es G');
void expect(service.validateChordNotation(text)).toEqual([jasmine.objectContaining({lineNumber: 2, token: 'Es', reason: 'alias', suggestion: 'Eb'})]);
});
it('should flag unknown tokens on mostly chord lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = `Strophe
C Foo G a
Text`;
void expect(service.validateChordNotation(text)).toEqual([jasmine.objectContaining({lineNumber: 2, token: 'Foo', reason: 'unknown_token', suggestion: null})]);
});
it('should reject tabs on chord lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = 'Strophe\nC\tG\ta\nText';
void expect(service.validateChordNotation(text)).toContain(
jasmine.objectContaining({
lineNumber: 2,
token: '\t',
reason: 'tab_character',
})
);
});
it('should not flag tabs on non chord lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService);
const text = 'Strophe\nDas\tist normaler Text\nText';
void expect(service.validateChordNotation(text)).toEqual([]);
});
});
});

View File

@@ -4,52 +4,167 @@ import {TransposeMode} from './transpose-mode';
import {SectionType} from './section-type';
import {Section} from './section';
import {LineType} from './line-type';
import {Chord} from './chord';
import {Chord, ChordAddDescriptor, ChordValidationIssue} from './chord';
import {Line} from './line';
type ChordRootDefinition = {
canonical: string;
aliases: string[];
};
const CHORD_ROOT_DEFINITIONS: readonly ChordRootDefinition[] = [
{canonical: 'C#', aliases: ['Cis']},
{canonical: 'Db', aliases: ['Des']},
{canonical: 'D#', aliases: ['Dis']},
{canonical: 'Eb', aliases: ['Es']},
{canonical: 'F#', aliases: ['Fis']},
{canonical: 'Gb', aliases: ['Ges']},
{canonical: 'G#', aliases: ['Gis']},
{canonical: 'Ab', aliases: ['As']},
{canonical: 'A#', aliases: ['Ais']},
{canonical: 'C', aliases: []},
{canonical: 'D', aliases: []},
{canonical: 'E', aliases: []},
{canonical: 'F', aliases: []},
{canonical: 'G', aliases: []},
{canonical: 'A', aliases: []},
{canonical: 'B', aliases: ['Hb']},
{canonical: 'H', aliases: []},
{canonical: 'c#', aliases: ['cis']},
{canonical: 'db', aliases: ['des']},
{canonical: 'd#', aliases: ['dis']},
{canonical: 'eb', aliases: ['es']},
{canonical: 'f#', aliases: ['fis']},
{canonical: 'gb', aliases: ['ges']},
{canonical: 'g#', aliases: ['gis']},
{canonical: 'ab', aliases: ['as']},
{canonical: 'a#', aliases: ['ais']},
{canonical: 'c', aliases: []},
{canonical: 'd', aliases: []},
{canonical: 'e', aliases: []},
{canonical: 'f', aliases: []},
{canonical: 'g', aliases: []},
{canonical: 'a', aliases: []},
{canonical: 'b', aliases: ['hb']},
{canonical: 'h', aliases: []},
] as const;
const CANONICAL_CHORD_ROOTS = CHORD_ROOT_DEFINITIONS.map(entry => entry.canonical);
const ALTERNATIVE_CHORD_ROOTS = CHORD_ROOT_DEFINITIONS.reduce<Record<string, string>>((aliases, entry) => {
entry.aliases.forEach(alias => {
aliases[alias] = entry.canonical;
});
return aliases;
}, {});
interface ParsedValidationToken {
prefix: string;
root: string;
suffix: string;
slashChord: string | null;
rootWasAlias: boolean;
slashWasAlias: boolean;
tokenSuffix: string;
}
interface ChordLineValidationResult {
chords: Chord[];
issues: ChordValidationIssue[];
isStrictChordLine: boolean;
isChordLike: boolean;
}
interface ParsedTokenCandidate {
token: string;
parsed: ParsedValidationToken | null;
}
@Injectable({
providedIn: 'root',
})
export class TextRenderingService {
private transposeService = inject(TransposeService);
private regexSection = /(Strophe|Refrain|Bridge)/;
private readonly regexSection = /^\s*(Strophe|Refrain|Bridge)\b/i;
private readonly chordRoots = CANONICAL_CHORD_ROOTS;
private readonly suffixKeywords = ['moll', 'verm', 'maj', 'min', 'dur', 'dim', 'aug', 'sus', 'add', 'm'] as const;
private readonly suffixChars = new Set(['#', 'b', '+', '-', '(', ')']);
private readonly alternativeChordRoots = ALTERNATIVE_CHORD_ROOTS;
public parse(text: string, transpose: TransposeMode | null, withComments = true): Section[] {
if (!text) {
return [];
}
const arrayOfLines = text.split(/\r?\n/).filter(_ => _ && (!_.startsWith('#') || withComments));
const indices = {
[SectionType.Bridge]: 0,
[SectionType.Chorus]: 0,
[SectionType.Verse]: 0,
};
return arrayOfLines.reduce((array, line) => {
const sections: Section[] = [];
for (const [lineIndex, line] of text.split(/\r?\n/).entries()) {
if (!line || this.isCommentLine(line, withComments)) {
continue;
}
const type = this.getSectionTypeOfLine(line);
if (this.regexSection.exec(line) && type !== null) {
const section: Section = {
if (type !== null) {
sections.push({
type,
number: indices[type]++,
lines: [],
};
return [...array, section];
}
const lineOfLineText = this.getLineOfLineText(line, transpose);
if (array.length === 0) return array;
if (lineOfLineText) array[array.length - 1].lines.push(lineOfLineText);
return array;
}, [] as Section[]);
});
continue;
}
private getLineOfLineText(text: string, transpose: TransposeMode | null): Line | null {
if (sections.length === 0) {
continue;
}
const renderedLine = this.getLineOfLineText(line, transpose, lineIndex + 1);
if (renderedLine) {
sections[sections.length - 1].lines.push(renderedLine);
}
}
return sections;
}
public validateChordNotation(text: string, withComments = true): ChordValidationIssue[] {
if (!text) {
return [];
}
const issues: ChordValidationIssue[] = [];
const lines = text.split(/\r?\n/);
lines.forEach((line, lineIndex) => {
if (!line || this.isCommentLine(line, withComments) || this.getSectionTypeOfLine(line) !== null) {
return;
}
const validationResult = this.getChordLineValidationResult(line, lineIndex + 1);
issues.push(...validationResult.issues);
});
return issues;
}
private getLineOfLineText(text: string, transpose: TransposeMode | null, lineNumber?: number): Line | null {
if (!text) return null;
const cords = this.readChords(text);
const hasMatches = cords.length > 0;
const type = hasMatches ? LineType.chord : LineType.text;
const validationResult = lineNumber ? this.getChordLineValidationResult(text, lineNumber) : {chords: [], issues: [], isStrictChordLine: false, isChordLike: false};
const validationIssues = validationResult.issues;
const hasMatches = validationResult.isStrictChordLine;
const isChordLikeLine = hasMatches || validationResult.isChordLike;
const type = isChordLikeLine ? LineType.chord : LineType.text;
const line: Line = {type, text, chords: hasMatches ? validationResult.chords : null, lineNumber};
if (validationIssues.length > 0 || (!hasMatches && isChordLikeLine)) {
return line;
}
const line: Line = {type, text, chords: hasMatches ? cords : null};
return transpose !== null && transpose !== undefined ? this.transposeService.transpose(line, transpose.baseKey, transpose.targetKey) : this.transposeService.renderChords(line);
}
@@ -61,48 +176,548 @@ export class TextRenderingService {
if (!match || match.length < 2) {
return null;
}
const typeString = match[1];
const typeString = match[1].toLowerCase();
switch (typeString) {
case 'Strophe':
case 'strophe':
return SectionType.Verse;
case 'Refrain':
case 'refrain':
return SectionType.Chorus;
case 'Bridge':
case 'bridge':
return SectionType.Bridge;
}
return null;
}
private readChords(chordLine: string): Chord[] {
let match: string[] | null;
private getParsedChords(chordLine: string): Chord[] {
const chords: Chord[] = [];
const tokens = chordLine.match(/\S+/g) ?? [];
// https://regex101.com/r/68jMB8/5
const regex =
/(C#|C|Db|D#|D|Eb|E|F#|F|Gb|G#|G|Ab|A#|A|B|H|c#|c|db|d#|d|eb|e|f#|f|gb|g#|g|ab|a#|a|b|h)(\/(C#|C|Db|D#|D|Eb|E|F#|F|Gb|G#|G|Ab|A#|A|B|H|c#|c|db|d#|d|eb|e|f#|f|gb|g#|g|ab|a#|a|b|h))?(\d+|maj7)?/gm;
while ((match = regex.exec(chordLine)) !== null) {
const chord: Chord = {
chord: match[1],
length: match[0].length,
position: regex.lastIndex - match[0].length,
slashChord: null,
add: null,
};
if (match[3]) {
chord.slashChord = match[3];
}
if (match[4]) {
chord.add = match[4];
}
for (const token of tokens) {
const position = chordLine.indexOf(token, chords.length > 0 ? chords[chords.length - 1].position + chords[chords.length - 1].length : 0);
const chord = this.parseChordToken(token, position);
if (chord) {
chords.push(chord);
}
}
const chordCount = chords.reduce((acc: number, cur: Chord) => acc + cur.length, 0);
const lineCount = chordLine.replace(/\s/g, '').length;
const isChrod = chordCount * 1.2 > lineCount;
return isChrod ? chords : [];
return chords;
}
private getChordLineValidationResult(line: string, lineNumber: number): ChordLineValidationResult {
const tokens: string[] = line.match(/\S+/g) ?? [];
const chords = this.getParsedChords(line);
const parsedTokens: ParsedTokenCandidate[] = tokens.map(token => ({
token,
parsed: this.parseValidationToken(token),
}));
const recognizedTokens = parsedTokens.filter((entry): entry is {token: string; parsed: ParsedValidationToken} => entry.parsed !== null);
const strictChordCount = chords.reduce((sum, chord) => sum + chord.length, 0);
const parsedLength = recognizedTokens.reduce((sum, entry) => sum + entry.token.length, 0);
const compactLineLength = line.replace(/\s/g, '').length;
const isStrictChordLine = compactLineLength > 0 && strictChordCount * 1.2 > compactLineLength;
const strictlyChordLike = compactLineLength > 0 && parsedLength * 1.2 > compactLineLength;
const heuristicallyChordLike = tokens.length >= 2 && recognizedTokens.length >= Math.ceil(tokens.length * 0.6);
const isChordLike = strictlyChordLike || heuristicallyChordLike;
if (!isChordLike) {
return {chords, issues: [], isStrictChordLine, isChordLike: false};
}
const issues: ChordValidationIssue[] = [];
if (line.includes('\t')) {
issues.push(this.createTabCharacterIssue(line, lineNumber));
}
return {
chords,
issues: [
...issues,
...parsedTokens
.map(entry => {
if (!entry.parsed) {
return this.createUnknownTokenIssue(line, lineNumber, entry.token);
}
return this.createValidationIssue(line, lineNumber, entry.token, entry.parsed);
})
.filter((issue): issue is ChordValidationIssue => issue !== null),
],
isStrictChordLine,
isChordLike: true,
};
}
private isCommentLine(line: string, withComments: boolean): boolean {
return !withComments && line.trimStart().startsWith('#');
}
private parseChordToken(token: string, position: number): Chord | null {
const decoratedToken = this.splitTokenDecorators(token);
const root = this.readChordRoot(decoratedToken.core, 0);
if (!root) {
return null;
}
let cursor = root.length;
const suffix = this.readChordSuffix(decoratedToken.core, cursor);
cursor += suffix.length;
let slashChord: string | null = null;
if (decoratedToken.core[cursor] === '/') {
const slash = this.readChordRoot(decoratedToken.core, cursor + 1);
if (!slash) {
return null;
}
slashChord = slash;
cursor += 1 + slash.length;
}
if (cursor !== decoratedToken.core.length) {
return null;
}
return {
chord: root,
length: token.length,
position,
slashChord,
add: suffix || null,
addDescriptor: this.parseChordAddDescriptor(suffix || null),
prefix: decoratedToken.prefix || undefined,
suffix: decoratedToken.suffix || undefined,
};
}
private readChordRoot(token: string, start: number): string | null {
return this.chordRoots.find(root => token.startsWith(root, start)) ?? null;
}
private readValidationChordRoot(token: string, start: number): {root: string; length: number; wasAlias: boolean} | null {
const directMatch = this.readChordRoot(token, start);
if (directMatch) {
return {root: directMatch, length: directMatch.length, wasAlias: false};
}
const aliasMatch = Object.entries(this.alternativeChordRoots).find(([alias]) => token.startsWith(alias, start));
if (!aliasMatch) {
return null;
}
return {root: aliasMatch[1], length: aliasMatch[0].length, wasAlias: true};
}
private readChordSuffix(token: string, start: number): string {
let cursor = start;
let suffix = '';
while (cursor < token.length) {
const keyword = this.suffixKeywords.find(entry => token.startsWith(entry, cursor));
if (keyword) {
suffix += keyword;
cursor += keyword.length;
continue;
}
const char = token[cursor];
if (this.isDigit(char) || this.suffixChars.has(char)) {
suffix += char;
cursor += 1;
continue;
}
break;
}
return suffix;
}
private readValidationChordSuffix(token: string, start: number): string {
let cursor = start;
let suffix = '';
while (cursor < token.length) {
const keyword = this.suffixKeywords.find(entry => token.slice(cursor, cursor + entry.length).toLowerCase() === entry);
if (keyword) {
suffix += token.slice(cursor, cursor + keyword.length);
cursor += keyword.length;
continue;
}
const char = token[cursor];
if (this.isDigit(char) || this.suffixChars.has(char)) {
suffix += char;
cursor += 1;
continue;
}
break;
}
return suffix;
}
private isDigit(char: string | undefined): boolean {
return !!char && char >= '0' && char <= '9';
}
private parseValidationToken(token: string): ParsedValidationToken | null {
const decoratedToken = this.splitTokenDecorators(token);
const root = this.readValidationChordRoot(decoratedToken.core, 0);
if (!root) {
return null;
}
let cursor = root.length;
const suffix = this.readValidationChordSuffix(decoratedToken.core, cursor);
cursor += suffix.length;
let slashChord: string | null = null;
let slashWasAlias = false;
if (decoratedToken.core[cursor] === '/') {
const slash = this.readValidationChordRoot(decoratedToken.core, cursor + 1);
if (!slash) {
return null;
}
slashChord = slash.root;
slashWasAlias = slash.wasAlias;
cursor += 1 + slash.length;
}
if (cursor !== decoratedToken.core.length) {
return null;
}
return {
prefix: decoratedToken.prefix,
root: root.root,
suffix,
slashChord,
rootWasAlias: root.wasAlias,
slashWasAlias,
tokenSuffix: decoratedToken.suffix,
};
}
private createValidationIssue(line: string, lineNumber: number, token: string, parsed: ParsedValidationToken): ChordValidationIssue | null {
const suggestion = this.getCanonicalChordToken(parsed);
if (suggestion === token) {
return null;
}
if (parsed.rootWasAlias || parsed.slashWasAlias) {
return {
lineNumber,
lineText: line,
token,
suggestion,
reason: 'alias',
message: `Bitte #/b statt is/es verwenden: ${suggestion}`,
};
}
const descriptor = this.parseChordAddDescriptor(parsed.suffix);
if (descriptor?.quality === 'minor' && this.isMajorRoot(parsed.root)) {
return {
lineNumber,
lineText: line,
token,
suggestion,
reason: 'minor_format',
message: `Mollakkorde bitte mit kleinem Grundton schreiben: ${suggestion}`,
};
}
if (this.isMinorRoot(parsed.root) && descriptor?.quality === 'major') {
return {
lineNumber,
lineText: line,
token,
suggestion,
reason: 'major_format',
message: `Durakkorde bitte mit grossem Grundton schreiben: ${suggestion}`,
};
}
if (parsed.suffix !== this.normalizeSuffix(parsed.suffix)) {
return {
lineNumber,
lineText: line,
token,
suggestion,
reason: 'invalid_suffix',
message: `Bitte die vorgegebene Akkordschreibweise verwenden: ${suggestion}`,
};
}
return null;
}
private createUnknownTokenIssue(line: string, lineNumber: number, token: string): ChordValidationIssue {
return {
lineNumber,
lineText: line,
token,
suggestion: null,
reason: 'unknown_token',
message: 'Unbekannter Akkord oder falsche Schreibweise',
};
}
private createTabCharacterIssue(line: string, lineNumber: number): ChordValidationIssue {
return {
lineNumber,
lineText: line,
token: '\t',
suggestion: null,
reason: 'tab_character',
message: 'Tabulatoren sind in Akkordzeilen nicht erlaubt, bitte Leerzeichen verwenden',
};
}
private getCanonicalChordToken(parsed: ParsedValidationToken): string {
const descriptor = this.parseChordAddDescriptor(parsed.suffix);
const normalizedSuffix = this.normalizeSuffix(parsed.suffix);
let root = parsed.root;
let suffix = normalizedSuffix;
if (descriptor?.quality === 'minor') {
root = this.toMinorRoot(root);
suffix = this.stripLeadingMinorMarker(normalizedSuffix);
} else if (descriptor?.quality === 'major') {
root = this.toMajorRoot(root);
suffix = this.stripLeadingDurMarker(normalizedSuffix);
}
const slashChord = parsed.slashChord ? this.toMajorRoot(parsed.slashChord) : null;
return parsed.prefix + root + suffix + (slashChord ? `/${slashChord}` : '') + parsed.tokenSuffix;
}
private normalizeSuffix(suffix: string): string {
if (!suffix) {
return suffix;
}
let rest = suffix;
let normalized = '';
const prefixMap: Array<[string, string]> = [
['moll', 'moll'],
['min', 'min'],
['maj', 'maj'],
['dur', 'dur'],
['dim', 'dim'],
['verm', 'verm'],
['aug', 'aug'],
['sus', 'sus'],
['add', 'add'],
['m', 'm'],
];
while (rest.length > 0) {
const keyword = prefixMap.find(([key]) => rest.slice(0, key.length).toLowerCase() === key);
if (keyword) {
normalized += keyword[1];
rest = rest.slice(keyword[0].length);
continue;
}
normalized += rest[0];
rest = rest.slice(1);
}
return normalized;
}
private stripLeadingMinorMarker(suffix: string): string {
return suffix.replace(/^(moll|min|m)/, '');
}
private stripLeadingDurMarker(suffix: string): string {
return suffix.replace(/^dur/, '');
}
private isMajorRoot(root: string): boolean {
return root[0] === root[0].toUpperCase();
}
private isMinorRoot(root: string): boolean {
return root[0] === root[0].toLowerCase();
}
private toMinorRoot(root: string): string {
return root[0].toLowerCase() + root.slice(1);
}
private toMajorRoot(root: string): string {
return root[0].toUpperCase() + root.slice(1);
}
private splitTokenDecorators(token: string): {prefix: string; core: string; suffix: string} {
let prefix = '';
let suffix = '';
let core = token;
while (core.startsWith('(') && !this.isFullyWrappedByOuterParentheses(core)) {
const matchingClosingParen = this.findMatchingClosingParen(core, 0);
if (matchingClosingParen !== -1) {
break;
}
prefix += '(';
core = core.slice(1);
}
while (core.endsWith(')') && !this.isFullyWrappedByOuterParentheses(core)) {
const matchingOpeningParen = this.findMatchingOpeningParen(core, core.length - 1);
if (matchingOpeningParen !== -1) {
break;
}
suffix = ')' + suffix;
core = core.slice(0, -1);
}
while (this.isFullyWrappedByOuterParentheses(core)) {
prefix += '(';
suffix = ')' + suffix;
core = core.slice(1, -1);
}
return {
prefix,
core,
suffix,
};
}
private isFullyWrappedByOuterParentheses(value: string): boolean {
if (!value.startsWith('(') || !value.endsWith(')')) {
return false;
}
return this.findMatchingClosingParen(value, 0) === value.length - 1;
}
private findMatchingClosingParen(value: string, start: number): number {
let depth = 0;
for (let i = start; i < value.length; i++) {
if (value[i] === '(') {
depth++;
} else if (value[i] === ')') {
depth--;
if (depth === 0) {
return i;
}
if (depth < 0) {
return -1;
}
}
}
return -1;
}
private findMatchingOpeningParen(value: string, end: number): number {
let depth = 0;
for (let i = end; i >= 0; i--) {
if (value[i] === ')') {
depth++;
} else if (value[i] === '(') {
depth--;
if (depth === 0) {
return i;
}
if (depth < 0) {
return -1;
}
}
}
return -1;
}
private parseChordAddDescriptor(suffix: string | null): ChordAddDescriptor | null {
if (!suffix) {
return null;
}
let rest = suffix;
let quality: ChordAddDescriptor['quality'] = null;
const qualityMatchers: Array<[string, NonNullable<ChordAddDescriptor['quality']>]> = [
['moll', 'minor'],
['min', 'minor'],
['maj', 'major'],
['dur', 'major'],
['dim', 'diminished'],
['verm', 'diminished'],
['aug', 'augmented'],
['m', 'minor'],
];
for (const [prefix, normalized] of qualityMatchers) {
if (rest.startsWith(prefix)) {
quality = normalized;
rest = rest.slice(prefix.length);
break;
}
}
const descriptor: ChordAddDescriptor = {
raw: suffix,
quality,
extensions: [],
additions: [],
suspensions: [],
alterations: [],
modifiers: [],
};
while (rest.length > 0) {
const additionMatch = rest.match(/^add([#b+-]?\d+)/);
if (additionMatch) {
descriptor.additions.push(additionMatch[1]);
rest = rest.slice(additionMatch[0].length);
continue;
}
const suspensionMatch = rest.match(/^sus(\d*)/);
if (suspensionMatch) {
descriptor.suspensions.push(suspensionMatch[1] || 'sus');
rest = rest.slice(suspensionMatch[0].length);
continue;
}
const extensionMatch = rest.match(/^\d+/);
if (extensionMatch) {
descriptor.extensions.push(extensionMatch[0]);
rest = rest.slice(extensionMatch[0].length);
continue;
}
const alterationMatch = rest.match(/^[#b+-]\d+/);
if (alterationMatch) {
descriptor.alterations.push(alterationMatch[0]);
rest = rest.slice(alterationMatch[0].length);
continue;
}
const modifierMatch = rest.match(/^\([^)]*\)/);
if (modifierMatch) {
descriptor.modifiers.push(modifierMatch[0]);
rest = rest.slice(modifierMatch[0].length);
continue;
}
descriptor.modifiers.push(rest);
break;
}
return descriptor;
}
}

View File

@@ -13,8 +13,7 @@ describe('TransposeService', () => {
});
it('should create map upwards', () => {
const distance = service.getDistance('D', 'G');
const map = service.getMap('D', 'G', distance);
const map = service.getMap('D', 'G');
if (map) {
void expect(map['D']).toBe('G');
@@ -22,8 +21,7 @@ describe('TransposeService', () => {
});
it('should create map downwards', () => {
const distance = service.getDistance('G', 'D');
const map = service.getMap('G', 'D', distance);
const map = service.getMap('G', 'D');
if (map) {
void expect(map['G']).toBe('D');
@@ -32,7 +30,7 @@ describe('TransposeService', () => {
it('should transpose enharmonic targets by semitone distance', () => {
const distance = service.getDistance('C', 'Db');
const map = service.getMap('C', 'Db', distance);
const map = service.getMap('C', 'Db');
void expect(distance).toBe(1);
void expect(map?.['C']).toBe('Db');
@@ -41,7 +39,7 @@ describe('TransposeService', () => {
it('should keep german B/H notation consistent', () => {
const distance = service.getDistance('H', 'C');
const map = service.getMap('H', 'C', distance);
const map = service.getMap('H', 'C');
void expect(distance).toBe(1);
void expect(map?.['H']).toBe('C');

View File

@@ -67,7 +67,7 @@ export class TransposeService {
if (line.type !== LineType.chord || !line.chords) return line;
const difference = this.getDistance(baseKey, targetKey);
const map = this.getMap(baseKey, targetKey, difference);
const map = this.getMap(baseKey, targetKey);
const chords = difference !== 0 && map ? line.chords.map(chord => this.transposeChord(chord, map)) : line.chords;
const renderedLine = this.renderLine(chords);
@@ -85,8 +85,8 @@ export class TransposeService {
}
public getDistance(baseKey: string, targetKey: string): number {
const baseSemitone = this.keyToSemitone[baseKey];
const targetSemitone = this.keyToSemitone[targetKey];
const baseSemitone = this.getSemitone(baseKey);
const targetSemitone = this.getSemitone(targetKey);
if (baseSemitone === undefined || targetSemitone === undefined) {
return 0;
@@ -95,8 +95,8 @@ export class TransposeService {
return (targetSemitone - baseSemitone + 12) % 12;
}
public getMap(baseKey: string, targetKey: string, difference: number): TransposeMap | null {
const cacheKey = `${baseKey}:${targetKey}:${difference}`;
public getMap(baseKey: string, targetKey: string): TransposeMap | null {
const cacheKey = `${baseKey}:${targetKey}`;
const cachedMap = this.mapCache.get(cacheKey);
if (cachedMap) {
return cachedMap;
@@ -108,6 +108,7 @@ export class TransposeService {
return null;
}
const difference = this.getDistance(baseKey, targetKey);
const map: TransposeMap = {};
sourceScales.forEach((sourceScale, scaleIndex) => {
const targetScale = targetScales[scaleIndex];
@@ -132,6 +133,8 @@ export class TransposeService {
}
private transposeChord(chord: Chord, map: TransposeMap): Chord {
// Intentional fallback: unknown chord tokens must stay visibly invalid as "X".
// Do not replace this with the original token without explicit product approval.
const translatedChord = map[chord.chord] ?? 'X';
const translatedSlashChord = chord.slashChord ? (map[chord.slashChord] ?? 'X') : null;
@@ -147,31 +150,38 @@ export class TransposeService {
return Math.max(max, chord.position + this.renderChord(chord).length);
}, 0);
let template = ''.padEnd(width, ' ');
const buffer = Array.from({length: width}, () => ' ');
chords.forEach(chord => {
const pos = chord.position;
const renderedChord = this.renderChord(chord);
const newLength = renderedChord.length;
const requiredLength = pos + renderedChord.length;
if (template.length < pos + newLength) {
template = template.padEnd(pos + newLength, ' ');
while (buffer.length < requiredLength) {
buffer.push(' ');
}
const pre = template.slice(0, pos);
const post = template.slice(pos + newLength);
template = pre + renderedChord + post;
for (let i = 0; i < renderedChord.length; i++) {
buffer[pos + i] = renderedChord[i];
}
});
return template.trimEnd();
return buffer.join('').trimEnd();
}
private renderChord(chord: Chord): string {
// Intentional fallback: unknown chord tokens must stay visibly invalid as "X".
// Do not replace this with the original token without explicit product approval.
const renderedChord = scaleMapping[chord.chord] ?? 'X';
const renderedSlashChord = chord.slashChord ? (scaleMapping[chord.slashChord] ?? 'X') : '';
const prefix = chord.prefix ?? '';
const suffix = chord.suffix ?? '';
return renderedChord + (chord.add ?? '') + (renderedSlashChord ? '/' + renderedSlashChord : '');
return prefix + renderedChord + (chord.add ?? '') + (renderedSlashChord ? '/' + renderedSlashChord : '') + suffix;
}
private getSemitone(key: string): number | undefined {
return this.keyToSemitone[key];
}
private getScaleVariants(key: string): ScaleVariants | null {

View File

@@ -1,22 +1,59 @@
import {TestBed} from '@angular/core/testing';
import {Storage} from '@angular/fire/storage';
import {UploadService} from './upload.service';
import {FileDataService} from './file-data.service';
import {Upload} from './upload';
import {UploadService} from './upload.service';
describe('UploadServiceService', () => {
beforeEach(
() =>
void TestBed.configureTestingModule({
describe('UploadService', () => {
let service: UploadService;
let fileDataServiceSpy: jasmine.SpyObj<FileDataService>;
type UploadTaskLike = {
on: (event: string, progress: (snapshot: {bytesTransferred: number; totalBytes: number}) => void, error: () => void, success: () => void) => void;
};
type UploadServiceInternals = UploadService & {
startUpload: (path: string, file: File) => UploadTaskLike;
};
beforeEach(async () => {
fileDataServiceSpy = jasmine.createSpyObj<FileDataService>('FileDataService', ['set']);
fileDataServiceSpy.set.and.resolveTo('file-1');
await TestBed.configureTestingModule({
providers: [
{provide: Storage, useValue: {}},
{provide: FileDataService, useValue: {set: () => Promise.resolve('')}},
{provide: Storage, useValue: {app: 'test-storage'}},
{provide: FileDataService, useValue: fileDataServiceSpy},
],
})
);
});
service = TestBed.inject(UploadService);
});
it('should be created', () => {
const service: UploadService = TestBed.inject(UploadService);
void expect(service).toBeTruthy();
expect(service).toBeTruthy();
});
it('should upload the file, update progress and persist file metadata on success', async () => {
const task: UploadTaskLike = {
on: (event: string, progress: (snapshot: {bytesTransferred: number; totalBytes: number}) => void, error: () => void, success: () => void) => {
progress({bytesTransferred: 50, totalBytes: 100});
success();
},
};
const uploadSpy = spyOn(service as UploadServiceInternals, 'startUpload').and.returnValue(task);
const upload = new Upload(new File(['content'], 'test.pdf', {type: 'application/pdf'}));
await service.pushUpload('song-1', upload);
expect(uploadSpy).toHaveBeenCalledWith('/attachments/song-1/test.pdf', upload.file);
expect(upload.progress).toBe(50);
expect(upload.path).toBe('/attachments/song-1');
expect(fileDataServiceSpy.set).toHaveBeenCalledWith(
'song-1',
jasmine.objectContaining({
name: 'test.pdf',
path: '/attachments/song-1',
createdAt: jasmine.any(Date),
})
);
});
});

View File

@@ -18,12 +18,7 @@ export class UploadService extends FileBase {
const filePath = `${directory}/${upload.file.name}`;
upload.path = directory;
const {task} = runInInjectionContext(this.environmentInjector, () => {
const storageRef = ref(this.storage, filePath);
return {
task: uploadBytesResumable(storageRef, upload.file),
};
});
const task = runInInjectionContext(this.environmentInjector, () => this.startUpload(filePath, upload.file));
task.on(
'state_changed',
@@ -45,4 +40,9 @@ export class UploadService extends FileBase {
};
await this.fileDataService.set(songId, file);
}
private startUpload(filePath: string, file: File) {
const storageRef = ref(this.storage, filePath);
return uploadBytesResumable(storageRef, file);
}
}

View File

@@ -1,10 +1,10 @@
import {Component, Input, inject} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup} from '@angular/forms';
import {SongService} from '../../services/song.service';
import {FilterValues} from './filter-values';
import {Song} from '../../services/song';
import {KEYS} from '../../services/key.helper';
import {FilterStoreService} from '../../../../services/filter-store.service';
import {MatFormField, MatLabel} from '@angular/material/form-field';
import {MatInput} from '@angular/material/input';
import {MatSelect} from '@angular/material/select';
@@ -21,17 +21,15 @@ import {SongTypePipe} from '../../../../widget-modules/pipes/song-type-translate
imports: [ReactiveFormsModule, MatFormField, MatLabel, MatInput, MatSelect, MatOption, LegalTypePipe, KeyPipe, SongTypePipe],
})
export class FilterComponent {
private router = inject(Router);
private filterStore = inject(FilterStoreService);
public filterFormGroup: UntypedFormGroup;
@Input() public route = '/';
@Input() public songs: Song[] = [];
public types = SongService.TYPES;
public legalType = SongService.LEGAL_TYPE;
public keys = KEYS;
public constructor() {
const activatedRoute = inject(ActivatedRoute);
const fb = inject(UntypedFormBuilder);
this.filterFormGroup = fb.group({
@@ -42,20 +40,15 @@ export class FilterComponent {
flag: '',
});
activatedRoute.queryParams.subscribe(params => {
const filterValues = params as FilterValues;
if (filterValues.q) this.filterFormGroup.controls.q.setValue(filterValues.q);
if (filterValues.type) this.filterFormGroup.controls.type.setValue(filterValues.type);
if (filterValues.key) this.filterFormGroup.controls.key.setValue(filterValues.key);
if (filterValues.legalType) this.filterFormGroup.controls.legalType.setValue(filterValues.legalType);
if (filterValues.flag) this.filterFormGroup.controls.flag.setValue(filterValues.flag);
this.filterStore.songFilter$.subscribe(filterValues => {
this.filterFormGroup.patchValue(filterValues, {emitEvent: false});
});
this.filterFormGroup.controls.q.valueChanges.subscribe(_ => void this.filerValueChanged('q', _ as string));
this.filterFormGroup.controls.key.valueChanges.subscribe(_ => void this.filerValueChanged('key', _ as string));
this.filterFormGroup.controls.type.valueChanges.subscribe(_ => void this.filerValueChanged('type', _ as string));
this.filterFormGroup.controls.legalType.valueChanges.subscribe(_ => void this.filerValueChanged('legalType', _ as string));
this.filterFormGroup.controls.flag.valueChanges.subscribe(_ => void this.filerValueChanged('flag', _ as string));
this.filterFormGroup.controls.q.valueChanges.subscribe(_ => this.filterValueChanged('q', (_ as string) ?? ''));
this.filterFormGroup.controls.key.valueChanges.subscribe(_ => this.filterValueChanged('key', (_ as string) ?? ''));
this.filterFormGroup.controls.type.valueChanges.subscribe(_ => this.filterValueChanged('type', (_ as string) ?? ''));
this.filterFormGroup.controls.legalType.valueChanges.subscribe(_ => this.filterValueChanged('legalType', (_ as string) ?? ''));
this.filterFormGroup.controls.flag.valueChanges.subscribe(_ => this.filterValueChanged('flag', (_ as string) ?? ''));
}
public getFlags(): string[] {
@@ -69,11 +62,7 @@ export class FilterComponent {
return flags.filter((n, i) => flags.indexOf(n) === i);
}
private async filerValueChanged(key: string, value: string): Promise<void> {
const route = this.router.createUrlTree([this.route], {
queryParams: {[key]: value},
queryParamsHandling: 'merge',
});
await this.router.navigateByUrl(route);
private filterValueChanged(key: keyof FilterValues, value: string): void {
this.filterStore.updateSongFilter({[key]: value} as Partial<FilterValues>);
}
}

View File

@@ -1,13 +1,18 @@
@if (songs$ | async; as songs) {
<div>
<app-list-header [anyFilterActive]="anyFilterActive">
<app-filter [songs]="songs" route="songs"></app-filter>
<app-filter [songs]="songs"></app-filter>
</app-list-header>
<app-card [padding]="false">
@for (song of songs; track trackBy($index, song)) {
<div [routerLink]="song.id" class="list-item">
<div class="number">{{ song.number }}</div>
<div>{{ song.title }}</div>
<div class="title">
<span>{{ song.title }}</span>
@if (song.hasChordValidationIssues) {
<span class="validation-star" title="Akkord-Validierungsfehler vorhanden">*</span>
}
</div>
<div>
<ng-container *appRole="['contributor']">
@if (song.status === 'draft') {

View File

@@ -27,6 +27,15 @@
text-align: right;
}
.title {
gap: 6px;
}
.validation-star {
color: var(--danger);
font-weight: bold;
}
.neutral, .warning, .success {
width: 30px;
}

View File

@@ -1,5 +1,4 @@
import {ChangeDetectionStrategy, Component, OnDestroy, OnInit, inject} from '@angular/core';
import {SongService} from '../services/song.service';
import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
import {Song} from '../services/song';
import {map} from 'rxjs/operators';
import {combineLatest, Observable} from 'rxjs';
@@ -7,8 +6,9 @@ import {fade} from '../../../animations';
import {ActivatedRoute, RouterLink} from '@angular/router';
import {filterSong} from '../../../services/filter.helper';
import {FilterValues} from './filter/filter-values';
import {ScrollService} from '../../../services/scroll.service';
import {faBalanceScaleRight, faCheck, faPencilRuler} from '@fortawesome/free-solid-svg-icons';
import {TextRenderingService} from '../services/text-rendering.service';
import {FilterStoreService} from '../../../services/filter-store.service';
import {AsyncPipe} from '@angular/common';
import {ListHeaderComponent} from '../../../widget-modules/components/list-header/list-header.component';
import {FilterComponent} from './filter/filter.component';
@@ -16,6 +16,10 @@ import {CardComponent} from '../../../widget-modules/components/card/card.compon
import {RoleDirective} from '../../../services/user/role.directive';
import {FaIconComponent} from '@fortawesome/angular-fontawesome';
interface SongListItem extends Song {
hasChordValidationIssues: boolean;
}
@Component({
selector: 'app-songs',
templateUrl: './song-list.component.html',
@@ -24,35 +28,32 @@ import {FaIconComponent} from '@fortawesome/angular-fontawesome';
animations: [fade],
imports: [ListHeaderComponent, FilterComponent, CardComponent, RouterLink, RoleDirective, FaIconComponent, AsyncPipe],
})
export class SongListComponent implements OnInit, OnDestroy {
private songService = inject(SongService);
private activatedRoute = inject(ActivatedRoute);
private scrollService = inject(ScrollService);
export class SongListComponent {
private route = inject(ActivatedRoute);
private textRenderingService = inject(TextRenderingService);
private filterStore = inject(FilterStoreService);
public anyFilterActive = false;
public songs$: Observable<Song[]> = combineLatest([
this.activatedRoute.queryParams.pipe(map(_ => _ as FilterValues)),
this.songService.list$().pipe(map(songs => [...songs].sort((a, b) => a.number - b.number))),
public songs$: Observable<SongListItem[]> = combineLatest([
this.filterStore.songFilter$,
this.route.data.pipe(map(data => (data['songs'] as Song[]).slice().sort((a, b) => a.number - b.number))),
]).pipe(
map(([filter, songs]) => {
this.anyFilterActive = this.checkIfFilterActive(filter);
return songs.filter(song => this.filter(song, filter)).sort((a, b) => a.title?.localeCompare(b.title));
return songs
.filter(song => this.filter(song, filter))
.map(song => ({
...song,
hasChordValidationIssues: this.textRenderingService.validateChordNotation(song.text ?? '').length > 0,
}))
.sort((a, b) => a.title?.localeCompare(b.title));
})
);
public faLegal = faBalanceScaleRight;
public faDraft = faPencilRuler;
public faFinal = faCheck;
public ngOnInit(): void {
setTimeout(() => this.scrollService.restoreScrollPositionFor('songlist'), 100);
setTimeout(() => this.scrollService.restoreScrollPositionFor('songlist'), 300);
}
public ngOnDestroy(): void {
this.scrollService.storeScrollPositionFor('songlist');
}
public trackBy = (index: number, show: Song) => show.id;
public trackBy = (index: number, show: SongListItem) => show.id;
private filter(song: Song, filter: FilterValues): boolean {
let baseFilter = filterSong(song, filter.q);

View File

@@ -1,5 +1,4 @@
import {TestBed} from '@angular/core/testing';
import {EditSongGuard} from './edit-song.guard';
describe('EditSongGuard', () => {
@@ -11,6 +10,22 @@ describe('EditSongGuard', () => {
});
it('should be created', () => {
void expect(guard).toBeTruthy();
expect(guard).toBeTruthy();
});
it('should allow navigation when there is no nested editSongComponent', () => {
const result = guard.canDeactivate({editSongComponent: null} as never, {} as never, {} as never, {} as never);
expect(result).toBeTrue();
});
it('should delegate to askForSave on the nested editSongComponent', async () => {
const nextState = {url: '/songs'} as never;
const askForSave = jasmine.createSpy('askForSave').and.resolveTo(true);
const result = await guard.canDeactivate({editSongComponent: {askForSave}} as never, {} as never, {} as never, nextState);
expect(askForSave).toHaveBeenCalledWith(nextState);
expect(result).toBeTrue();
});
});

View File

@@ -54,10 +54,26 @@
matInput
></textarea>
</mat-form-field>
@if (chordValidationIssues.length > 0) {
<div class="song-text-validation">
<h3>Akkordschreibweise korrigieren</h3>
@for (issue of chordValidationIssues; track issue.lineNumber + '-' + issue.token) {
<div class="issue">
<strong>Zeile {{ issue.lineNumber }}:</strong>
<span>{{ issue.message }}</span>
<code>{{ issue.token }}</code>
@if (issue.suggestion) {
<span>-></span>
<code>{{ issue.suggestion }}</code>
}
</div>
}
</div>
}
@if (songtextFocus) {
<div class="song-text-help">
<h3>Vorschau</h3>
<app-song-text [text]="form.value.text" chordMode="show"></app-song-text>
<app-song-text [text]="form.value.text" [validateChordNotation]="true" chordMode="show"></app-song-text>
<h3>Hinweise zur Bearbeitung</h3>
<h4>Aufbau</h4>
Der Liedtext wird hintereinander weg geschrieben. Dabei werden Strophen,
@@ -180,7 +196,7 @@
</div>
</form>
<app-button-row>
<app-button (click)="onSave()" [icon]="faSave">Speichern</app-button>
<app-button (click)="onSave()" [disabled]="form.invalid" [icon]="faSave">Speichern</app-button>
</app-button-row>
</app-card>
}

View File

@@ -4,6 +4,7 @@
> * {
width: 100%;
box-sizing: border-box;
}
.fourth {
@@ -43,3 +44,30 @@ h4 {
.song-text-help {
font-size: 11px;
}
.song-text-validation {
margin: -8px 0 12px;
padding: 12px 14px;
border-radius: 6px;
background: rgba(166, 32, 32, 0.08);
border: 1px solid rgba(166, 32, 32, 0.22);
color: #7d1919;
.issue {
display: flex;
gap: 8px;
align-items: baseline;
flex-wrap: wrap;
margin-top: 6px;
}
code {
padding: 1px 4px;
border-radius: 4px;
background: rgba(125, 25, 25, 0.08);
}
h3 {
margin: 0;
}
}

View File

@@ -5,12 +5,15 @@ import {ActivatedRoute, Router, RouterStateSnapshot} from '@angular/router';
import {SongService} from '../../../services/song.service';
import {EditService} from '../edit.service';
import {first, map, switchMap} from 'rxjs/operators';
import {startWith} from 'rxjs';
import {KEYS} from '../../../services/key.helper';
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {MatChipGrid, MatChipInput, MatChipInputEvent, MatChipRow} from '@angular/material/chips';
import {faExternalLinkAlt, faSave, faTimesCircle} from '@fortawesome/free-solid-svg-icons';
import {MatDialog} from '@angular/material/dialog';
import {SaveDialogComponent} from './save-dialog/save-dialog.component';
import {TextRenderingService} from '../../../services/text-rendering.service';
import {ChordValidationIssue} from '../../../services/chord';
import {CardComponent} from '../../../../../widget-modules/components/card/card.component';
import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field';
@@ -63,6 +66,7 @@ export class EditSongComponent implements OnInit {
private songService = inject(SongService);
private editService = inject(EditService);
private router = inject(Router);
private textRenderingService = inject(TextRenderingService);
public dialog = inject(MatDialog);
public song: Song | null = null;
@@ -78,6 +82,7 @@ export class EditSongComponent implements OnInit {
public faSave = faSave;
public faLink = faExternalLinkAlt;
public songtextFocus = false;
public chordValidationIssues: ChordValidationIssue[] = [];
public ngOnInit(): void {
this.activatedRoute.params
@@ -92,12 +97,15 @@ export class EditSongComponent implements OnInit {
if (!song) return;
this.form = this.editService.createSongForm(song);
this.form.controls.flags.valueChanges.subscribe(_ => this.onFlagsChanged(_ as string));
this.form.controls.text.valueChanges.pipe(startWith(this.form.controls.text.value)).subscribe(text => {
this.updateChordValidation(text as string);
});
this.onFlagsChanged(this.form.controls.flags.value as string);
});
}
public async onSave(): Promise<void> {
if (!this.song) return;
if (!this.song || this.form.invalid) return;
const data = this.form.value as Partial<Song>;
await this.songService.update$(this.song.id, data);
this.form.markAsPristine();
@@ -149,8 +157,23 @@ export class EditSongComponent implements OnInit {
this.flags = flagArray.split(';').filter(_ => !!_);
}
private updateChordValidation(text: string): void {
const control = this.form.controls.text;
this.chordValidationIssues = this.textRenderingService.validateChordNotation(text ?? '');
const errors = {...(control.errors ?? {})};
if (this.chordValidationIssues.length > 0) {
errors.chordNotation = this.chordValidationIssues;
control.setErrors(errors);
return;
}
delete errors.chordNotation;
control.setErrors(Object.keys(errors).length > 0 ? errors : null);
}
private async onSaveDialogAfterClosed(save: boolean, url: string) {
if (save && this.song) {
if (save && this.song && !this.form.invalid) {
const data = this.form.value as Partial<Song>;
await this.songService.update$(this.song.id, data);
}

View File

@@ -1,12 +1,74 @@
import {TestBed} from '@angular/core/testing';
import {EditService} from './edit.service';
describe('EditService', () => {
beforeEach(() => void TestBed.configureTestingModule({}));
let service: EditService;
beforeEach(() => {
void TestBed.configureTestingModule({});
service = TestBed.inject(EditService);
});
it('should be created', () => {
const service: EditService = TestBed.inject(EditService);
void expect(service).toBeTruthy();
expect(service).toBeTruthy();
});
it('should create a form with all editable song fields populated', () => {
const form = service.createSongForm({
text: 'Line 1',
title: 'Amazing Grace',
comment: 'Comment',
flags: 'fast',
key: 'G',
tempo: 90,
type: 'Praise',
status: 'final',
legalType: 'allowed',
legalOwner: 'CCLI',
legalOwnerId: '123',
artist: 'Artist',
label: 'Label',
termsOfUse: 'Use it',
origin: 'Origin',
} as never);
expect(form.getRawValue()).toEqual({
text: 'Line 1',
title: 'Amazing Grace',
comment: 'Comment',
flags: 'fast',
key: 'G',
tempo: 90,
type: 'Praise',
status: 'final',
legalType: 'allowed',
legalOwner: 'CCLI',
legalOwnerId: '123',
artist: 'Artist',
label: 'Label',
termsOfUse: 'Use it',
origin: 'Origin',
});
});
it('should default the status control to draft when the song has no status', () => {
const form = service.createSongForm({
text: '',
title: 'Untitled',
comment: '',
flags: '',
key: 'C',
tempo: 80,
type: 'Misc',
legalType: 'open',
legalOwner: 'other',
legalOwnerId: '',
artist: '',
label: '',
termsOfUse: '',
origin: '',
} as never);
expect(form.get('status')?.value).toBe('draft');
});
});

View File

@@ -48,6 +48,7 @@
[chordMode]="user.chordMode"
[showSwitch]="true"
[text]="song.text"
[validateChordNotation]="true"
></app-song-text>
}
<mat-chip-listbox

View File

@@ -5,12 +5,16 @@ import {SongListComponent} from './song-list/song-list.component';
import {EditComponent} from './song/edit/edit.component';
import {NewComponent} from './song/new/new.component';
import {EditSongGuard} from './song/edit/edit-song.guard';
import {SongListResolver} from './services/song-list.resolver';
const routes: Routes = [
{
path: '',
component: SongListComponent,
pathMatch: 'full',
resolve: {
songs: SongListResolver,
},
},
{
path: 'new',

View File

@@ -1,16 +1,40 @@
import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {DbService} from './db.service';
import {ConfigService} from './config.service';
describe('ConfigService', () => {
let service: ConfigService;
let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(async () => {
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['doc$']);
dbServiceSpy.doc$.and.returnValue(of({copyright: 'CCLI'}) as never);
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});
beforeEach(() => {
void TestBed.configureTestingModule({});
service = TestBed.inject(ConfigService);
});
it('should be created', () => {
void expect(service).toBeTruthy();
expect(service).toBeTruthy();
});
it('should read the global config document once on creation', () => {
expect(dbServiceSpy.doc$).toHaveBeenCalledTimes(1);
expect(dbServiceSpy.doc$).toHaveBeenCalledWith('global/config');
});
it('should expose the shared config stream via get$', done => {
service.get$().subscribe(config => {
expect(config).toEqual({copyright: 'CCLI'} as never);
done();
});
});
it('should resolve the current config via get()', async () => {
await expectAsync(service.get()).toBeResolvedTo({copyright: 'CCLI'} as never);
});
});

View File

@@ -0,0 +1,51 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {FilterValues as SongFilterValues} from '../modules/songs/song-list/filter/filter-values';
import {FilterValues as ShowFilterValues} from '../modules/shows/list/filter/filter-values';
const DEFAULT_SONG_FILTER: SongFilterValues = {
q: '',
type: '',
key: '',
legalType: '',
flag: '',
};
const DEFAULT_SHOW_FILTER: ShowFilterValues = {
time: 1,
owner: '',
showType: '',
};
@Injectable({
providedIn: 'root',
})
export class FilterStoreService {
private readonly songFilterSubject = new BehaviorSubject<SongFilterValues>(DEFAULT_SONG_FILTER);
private readonly showFilterSubject = new BehaviorSubject<ShowFilterValues>(DEFAULT_SHOW_FILTER);
public readonly songFilter$: Observable<SongFilterValues> = this.songFilterSubject.asObservable();
public readonly showFilter$: Observable<ShowFilterValues> = this.showFilterSubject.asObservable();
public updateSongFilter(filter: Partial<SongFilterValues>): void {
this.songFilterSubject.next({
...this.songFilterSubject.value,
...filter,
});
}
public updateShowFilter(filter: Partial<ShowFilterValues>): void {
this.showFilterSubject.next({
...this.showFilterSubject.value,
...filter,
});
}
public resetSongFilter(): void {
this.songFilterSubject.next(DEFAULT_SONG_FILTER);
}
public resetShowFilter(): void {
this.showFilterSubject.next(DEFAULT_SHOW_FILTER);
}
}

View File

@@ -1,16 +1,46 @@
import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {DbService} from './db.service';
import {GlobalSettingsService} from './global-settings.service';
describe('GlobalSettingsService', () => {
let service: GlobalSettingsService;
let dbServiceSpy: jasmine.SpyObj<DbService>;
let updateSpy: jasmine.Spy;
beforeEach(async () => {
updateSpy = jasmine.createSpy('update').and.resolveTo();
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['doc$', 'doc']);
dbServiceSpy.doc$.and.returnValue(of({churchName: 'ICF'}) as never);
dbServiceSpy.doc.and.returnValue({update: updateSpy} as never);
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});
beforeEach(() => {
void TestBed.configureTestingModule({});
service = TestBed.inject(GlobalSettingsService);
});
it('should be created', () => {
void expect(service).toBeTruthy();
expect(service).toBeTruthy();
});
it('should read the static global settings document once on creation', () => {
expect(dbServiceSpy.doc$).toHaveBeenCalledTimes(1);
expect(dbServiceSpy.doc$).toHaveBeenCalledWith('global/static');
});
it('should expose the shared settings stream via the getter', done => {
service.get$.subscribe(settings => {
expect(settings).toEqual({churchName: 'ICF'} as never);
done();
});
});
it('should update the static global settings document', async () => {
await service.set({churchName: 'New Name'} as never);
expect(dbServiceSpy.doc).toHaveBeenCalledWith('global/static');
expect(updateSpy).toHaveBeenCalledWith({churchName: 'New Name'} as never);
});
});

View File

@@ -1,14 +1,20 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {of} from 'rxjs';
import {UserService} from '../user.service';
import {UserNameComponent} from './user-name.component';
describe('UserNameComponent', () => {
let component: UserNameComponent;
let fixture: ComponentFixture<UserNameComponent>;
let userServiceSpy: jasmine.SpyObj<UserService>;
beforeEach(waitForAsync(() => {
userServiceSpy = jasmine.createSpyObj<UserService>('UserService', ['getUserbyId$']);
userServiceSpy.getUserbyId$.and.returnValue(of({name: 'Benjamin'} as never));
void TestBed.configureTestingModule({
imports: [UserNameComponent],
providers: [{provide: UserService, useValue: userServiceSpy}],
}).compileComponents();
}));
@@ -19,6 +25,27 @@ describe('UserNameComponent', () => {
});
it('should create', () => {
void expect(component).toBeTruthy();
expect(component).toBeTruthy();
});
it('should resolve the user name when the userId input changes', done => {
component.userId = 'user-1';
component.name$?.subscribe(name => {
expect(userServiceSpy.getUserbyId$).toHaveBeenCalledWith('user-1');
expect(name).toBe('Benjamin');
done();
});
});
it('should map missing users to null names', done => {
userServiceSpy.getUserbyId$.and.returnValue(of(null));
component.userId = 'missing-user';
component.name$?.subscribe(name => {
expect(name).toBeNull();
done();
});
});
});

View File

@@ -0,0 +1,122 @@
import {TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {BehaviorSubject, firstValueFrom, of} from 'rxjs';
import {Auth} from '@angular/fire/auth';
import {DbService} from '../db.service';
import {UserSessionService} from './user-session.service';
describe('UserSessionService', () => {
let service: UserSessionService;
let dbServiceSpy: jasmine.SpyObj<DbService>;
let routerSpy: jasmine.SpyObj<Router>;
let authStateSubject: BehaviorSubject<unknown>;
let createAuthStateSpy: jasmine.Spy<() => ReturnType<UserSessionService['createAuthState$']>>;
let runInFirebaseContextSpy: jasmine.Spy;
beforeEach(async () => {
authStateSubject = new BehaviorSubject<unknown>(null);
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['col$', 'doc$', 'doc']);
routerSpy = jasmine.createSpyObj<Router>('Router', ['navigateByUrl']);
dbServiceSpy.col$.and.returnValue(of([{id: 'user-1'}]) as never);
dbServiceSpy.doc$.and.callFake((path: string) => {
if (path === 'users/user-1') {
return of({id: 'user-1', name: 'Benjamin', role: 'leader', chordMode: 'letters', songUsage: {}}) as never;
}
if (path === 'users/user-2') {
return of({id: 'user-2', name: 'Paula', role: 'user', chordMode: 'letters', songUsage: {}}) as never;
}
return of(null) as never;
});
dbServiceSpy.doc.and.returnValue({
update: jasmine.createSpy('update').and.resolveTo(),
set: jasmine.createSpy('set').and.resolveTo(),
} as never);
routerSpy.navigateByUrl.and.resolveTo(true);
createAuthStateSpy = spyOn(UserSessionService.prototype, 'createAuthState$').and.returnValue(authStateSubject.asObservable() as never);
await TestBed.configureTestingModule({
providers: [
{provide: DbService, useValue: dbServiceSpy},
{provide: Router, useValue: routerSpy},
{provide: Auth, useValue: {}},
],
});
service = TestBed.inject(UserSessionService);
runInFirebaseContextSpy = spyOn(service as UserSessionService & {runInFirebaseContext: (...args: unknown[]) => Promise<unknown>}, 'runInFirebaseContext');
});
it('should be created', () => {
expect(service).toBeTruthy();
expect(createAuthStateSpy).toHaveBeenCalled();
});
it('should derive userId$ and loggedIn$ from authState', async () => {
authStateSubject.next({uid: 'user-1'});
await expectAsync(firstValueFrom(service.userId$)).toBeResolvedTo('user-1');
await expectAsync(firstValueFrom(service.loggedIn$())).toBeResolvedTo(true);
});
it('should resolve the current user document from auth state', async () => {
authStateSubject.next({uid: 'user-1'});
await expectAsync(firstValueFrom(service.user$)).toBeResolvedTo(jasmine.objectContaining({id: 'user-1', name: 'Benjamin'}) as never);
});
it('should cache user lookups by id', async () => {
const first$ = service.getUserbyId$('user-2');
const second$ = service.getUserbyId$('user-2');
expect(first$).toBe(second$);
await expectAsync(firstValueFrom(first$)).toBeResolvedTo(jasmine.objectContaining({id: 'user-2'}) as never);
});
it('should login and initialize songUsage when missing', async () => {
dbServiceSpy.doc$.and.callFake((path: string) => {
if (path === 'users/user-1') {
return of({id: 'user-1', name: 'Benjamin', role: 'leader', chordMode: 'letters'}) as never;
}
return of(null) as never;
});
const updateSpy = jasmine.createSpy('update').and.resolveTo();
dbServiceSpy.doc.and.returnValue({update: updateSpy} as never);
runInFirebaseContextSpy.and.resolveTo({user: {uid: 'user-1'}});
await expectAsync(service.login('mail', 'secret')).toBeResolvedTo('user-1');
expect(runInFirebaseContextSpy).toHaveBeenCalledTimes(1);
expect(updateSpy).toHaveBeenCalledWith({songUsage: {}});
});
it('should delegate logout and password reset to AngularFire auth APIs', async () => {
runInFirebaseContextSpy.and.resolveTo();
await service.logout();
await service.changePassword('mail@example.com');
expect(runInFirebaseContextSpy).toHaveBeenCalledTimes(2);
});
it('should create a new user document and navigate afterwards', async () => {
dbServiceSpy.doc$.and.callFake((path: string) => {
if (path === 'users/user-3') {
return of({id: 'user-3', name: 'New User', role: 'user', chordMode: 'onlyFirst', songUsage: {}}) as never;
}
return of(null) as never;
});
const setSpy = jasmine.createSpy('set').and.resolveTo();
dbServiceSpy.doc.and.returnValue({set: setSpy} as never);
runInFirebaseContextSpy.and.resolveTo({user: {uid: 'user-3'}});
await service.createNewUser('mail@example.com', 'New User', 'secret');
expect(runInFirebaseContextSpy).toHaveBeenCalledTimes(1);
expect(setSpy).toHaveBeenCalledWith({name: 'New User', chordMode: 'onlyFirst', songUsage: {}});
expect(routerSpy.navigateByUrl).toHaveBeenCalledWith('/brand/new-user');
});
});

View File

@@ -0,0 +1,81 @@
import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {DbService} from '../db.service';
import {ShowDataService} from '../../modules/shows/services/show-data.service';
import {ShowSongDataService} from '../../modules/shows/services/show-song-data.service';
import {UserSessionService} from './user-session.service';
import {UserSongUsageService} from './user-song-usage.service';
describe('UserSongUsageService', () => {
let service: UserSongUsageService;
let dbServiceSpy: jasmine.SpyObj<DbService>;
let sessionSpy: jasmine.SpyObj<UserSessionService>;
let showDataServiceSpy: jasmine.SpyObj<ShowDataService>;
let showSongDataServiceSpy: jasmine.SpyObj<ShowSongDataService>;
beforeEach(async () => {
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['doc']);
sessionSpy = jasmine.createSpyObj<UserSessionService>('UserSessionService', ['update$'], {
user$: of({id: 'user-1', role: 'admin', songUsage: {}}) as never,
users$: of([{id: 'user-1'}, {id: 'user-2'}]) as never,
});
showDataServiceSpy = jasmine.createSpyObj<ShowDataService>('ShowDataService', ['listRaw$']);
showSongDataServiceSpy = jasmine.createSpyObj<ShowSongDataService>('ShowSongDataService', ['list$']);
sessionSpy.update$.and.resolveTo();
showDataServiceSpy.listRaw$.and.returnValue(
of([
{id: 'show-1', owner: 'user-1'},
{id: 'show-2', owner: 'user-2'},
] as never)
);
showSongDataServiceSpy.list$.and.callFake((showId: string) =>
of(showId === 'show-1' ? ([{songId: 'song-1'}, {songId: 'song-1'}, {songId: 'song-2'}] as never) : ([{songId: 'song-3'}] as never))
);
dbServiceSpy.doc.and.returnValue({update: jasmine.createSpy('update').and.resolveTo()} as never);
await TestBed.configureTestingModule({
providers: [
{provide: DbService, useValue: dbServiceSpy},
{provide: UserSessionService, useValue: sessionSpy},
{provide: ShowDataService, useValue: showDataServiceSpy},
{provide: ShowSongDataService, useValue: showSongDataServiceSpy},
],
});
service = TestBed.inject(UserSongUsageService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should increment and decrement song usage for the current user', async () => {
const updateSpy = jasmine.createSpy('update').and.resolveTo();
dbServiceSpy.doc.and.returnValue({update: updateSpy} as never);
await service.incSongCount('song-1');
await service.decSongCount('song-2');
expect(dbServiceSpy.doc).toHaveBeenCalledWith('users/user-1');
expect(updateSpy.calls.argsFor(0)[0]).toEqual({'songUsage.song-1': jasmine.anything()});
expect(updateSpy.calls.argsFor(1)[0]).toEqual({'songUsage.song-2': jasmine.anything()});
});
it('should rebuild song usage for all users based on owned show songs', async () => {
await expectAsync(service.rebuildSongUsage()).toBeResolvedTo({
usersProcessed: 2,
showsProcessed: 2,
showSongsProcessed: 4,
});
expect(sessionSpy.update$).toHaveBeenCalledWith('user-1', {songUsage: {'song-1': 2, 'song-2': 1}});
expect(sessionSpy.update$).toHaveBeenCalledWith('user-2', {songUsage: {'song-3': 1}});
});
it('should reject song usage rebuilds for non-admin users', async () => {
Object.defineProperty(sessionSpy, 'user$', {value: of({id: 'user-1', role: 'leader'})});
await expectAsync(service.rebuildSongUsage()).toBeRejectedWithError('Admin role required to rebuild songUsage.');
});
});

View File

@@ -1,12 +1,108 @@
import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {UserService} from './user.service';
import {UserSessionService} from './user-session.service';
import {UserSongUsageService} from './user-song-usage.service';
describe('UserService', () => {
beforeEach(() => void TestBed.configureTestingModule({}));
let service: UserService;
let sessionSpy: jasmine.SpyObj<UserSessionService>;
let songUsageSpy: jasmine.SpyObj<UserSongUsageService>;
beforeEach(async () => {
sessionSpy = jasmine.createSpyObj<UserSessionService>(
'UserSessionService',
['currentUser', 'getUserbyId', 'getUserbyId$', 'login', 'loggedIn$', 'list$', 'logout', 'update$', 'changePassword', 'createNewUser'],
{
users$: of([{id: 'user-1'}]) as never,
userId$: of('user-1'),
user$: of({id: 'user-1'}) as never,
}
);
songUsageSpy = jasmine.createSpyObj<UserSongUsageService>('UserSongUsageService', ['incSongCount', 'decSongCount', 'rebuildSongUsage']);
sessionSpy.currentUser.and.resolveTo({id: 'user-1'} as never);
sessionSpy.getUserbyId.and.resolveTo({id: 'user-2'} as never);
sessionSpy.getUserbyId$.and.returnValue(of({id: 'user-2'}) as never);
sessionSpy.login.and.resolveTo('user-1');
sessionSpy.loggedIn$.and.returnValue(of(true));
sessionSpy.list$.and.returnValue(of([{id: 'user-1'}]) as never);
sessionSpy.logout.and.resolveTo();
sessionSpy.update$.and.resolveTo();
sessionSpy.changePassword.and.resolveTo();
sessionSpy.createNewUser.and.resolveTo();
songUsageSpy.incSongCount.and.resolveTo();
songUsageSpy.decSongCount.and.resolveTo();
songUsageSpy.rebuildSongUsage.and.resolveTo({usersProcessed: 1, showsProcessed: 2, showSongsProcessed: 3});
await TestBed.configureTestingModule({
providers: [
{provide: UserSessionService, useValue: sessionSpy},
{provide: UserSongUsageService, useValue: songUsageSpy},
],
});
service = TestBed.inject(UserService);
});
it('should be created', () => {
const service: UserService = TestBed.inject(UserService);
void expect(service).toBeTruthy();
expect(service).toBeTruthy();
});
it('should expose the session streams directly', done => {
service.userId$.subscribe(userId => {
expect(userId).toBe('user-1');
service.user$.subscribe(user => {
expect(user).toEqual({id: 'user-1'} as never);
service.users$.subscribe(users => {
expect(users).toEqual([{id: 'user-1'}] as never);
done();
});
});
});
});
it('should delegate session operations to UserSessionService', async () => {
await expectAsync(service.currentUser()).toBeResolvedTo({id: 'user-1'} as never);
await expectAsync(service.getUserbyId('user-2')).toBeResolvedTo({id: 'user-2'} as never);
await expectAsync(service.login('mail', 'secret')).toBeResolvedTo('user-1');
await service.logout();
await service.update$('user-1', {name: 'Benjamin'} as never);
await service.changePassword('mail');
await service.createNewUser('mail', 'Benjamin', 'secret');
expect(sessionSpy.currentUser).toHaveBeenCalled();
expect(sessionSpy.getUserbyId).toHaveBeenCalledWith('user-2');
expect(sessionSpy.login).toHaveBeenCalledWith('mail', 'secret');
expect(sessionSpy.logout).toHaveBeenCalled();
expect(sessionSpy.update$).toHaveBeenCalledWith('user-1', {name: 'Benjamin'} as never);
expect(sessionSpy.changePassword).toHaveBeenCalledWith('mail');
expect(sessionSpy.createNewUser).toHaveBeenCalledWith('mail', 'Benjamin', 'secret');
});
it('should delegate user lookup and loggedIn/list streams to UserSessionService', done => {
service.getUserbyId$('user-2').subscribe(user => {
expect(user).toEqual({id: 'user-2'} as never);
service.loggedIn$().subscribe(loggedIn => {
expect(loggedIn).toBeTrue();
service.list$().subscribe(users => {
expect(users).toEqual([{id: 'user-1'}] as never);
expect(sessionSpy.getUserbyId$).toHaveBeenCalledWith('user-2');
expect(sessionSpy.loggedIn$).toHaveBeenCalled();
expect(sessionSpy.list$).toHaveBeenCalled();
done();
});
});
});
});
it('should delegate song usage operations to UserSongUsageService', async () => {
await service.incSongCount('song-1');
await service.decSongCount('song-2');
await expectAsync(service.rebuildSongUsage()).toBeResolvedTo({usersProcessed: 1, showsProcessed: 2, showSongsProcessed: 3});
expect(songUsageSpy.incSongCount).toHaveBeenCalledWith('song-1');
expect(songUsageSpy.decSongCount).toHaveBeenCalledWith('song-2');
expect(songUsageSpy.rebuildSongUsage).toHaveBeenCalled();
});
});

View File

@@ -1,4 +1,4 @@
<button mat-button>
<button [disabled]="disabled" mat-button>
@if (icon) {
<span
><fa-icon [icon]="icon"></fa-icon><span class="content">&nbsp;</span></span

View File

@@ -11,5 +11,6 @@ import {FaIconComponent} from '@fortawesome/angular-fontawesome';
imports: [MatButton, FaIconComponent],
})
export class ButtonComponent {
@Input() public disabled = false;
@Input() public icon: IconProp | null = null;
}

View File

@@ -10,7 +10,8 @@
width: 800px;
position: relative;
color: var(--text);
padding: 5px 0;
padding: 10px 0;
box-shadow: var(--shadow-card-3);
@media screen and (max-width: 860px) {
width: 100vw;
@@ -49,7 +50,7 @@
opacity: 0.7;
color: var(--text);
padding-left: 20px;
padding-top: 20px;
padding-top: 10px;
}
.subheading {

View File

@@ -26,7 +26,10 @@
[class.comment]="isComment(line.text)"
[class.disabled]="checkDisabled(i)"
class="line"
>{{ transform(line.text) }}
>
@for (segment of getDisplaySegments(line); track $index) {
<span [class.invalid-chord-token]="segment.invalid" [class.invalid-tab-token]="segment.isTab">{{ segment.text }}</span>
}
</div>
}
</div>
@@ -72,7 +75,10 @@
[class.chord]="line.type === 0"
[class.disabled]="checkDisabled(i)"
class="line"
>{{ line.text.trim() }}
>
@for (segment of getDisplaySegments(line, true); track $index) {
<span [class.invalid-chord-token]="segment.invalid" [class.invalid-tab-token]="segment.isTab">{{ segment.text }}</span>
}
</div>
}
</div>

View File

@@ -34,6 +34,20 @@
}
}
.invalid-chord-token {
color: #b42318;
text-shadow: none;
}
.invalid-tab-token {
display: inline-block;
min-width: 1.5ch;
text-align: center;
background: rgba(180, 35, 24, 0.12);
border-radius: 3px;
font-weight: bold;
}
.menu {
position: absolute;
right: -10px;

View File

@@ -7,12 +7,19 @@ import {SectionType} from '../../../modules/songs/services/section-type';
import {LineType} from '../../../modules/songs/services/line-type';
import {Section} from '../../../modules/songs/services/section';
import {Line} from '../../../modules/songs/services/line';
import {ChordValidationIssue} from '../../../modules/songs/services/chord';
import {MatIconButton} from '@angular/material/button';
import {FaIconComponent} from '@fortawesome/angular-fontawesome';
export type ChordMode = 'show' | 'hide' | 'onlyFirst';
interface DisplaySegment {
text: string;
invalid: boolean;
isTab: boolean;
}
@Component({
selector: 'app-song-text',
templateUrl: './song-text.component.html',
@@ -36,6 +43,8 @@ export class SongTextComponent implements OnInit {
public faLines = faGripLines;
public offset = 0;
public iChordMode: ChordMode = 'hide';
public showValidationIssues = false;
private invalidChordIssuesByLine = new Map<number, ChordValidationIssue[]>();
private iText = '';
private iTranspose: TransposeMode | null = null;
@@ -56,6 +65,13 @@ export class SongTextComponent implements OnInit {
this.render();
}
@Input()
public set validateChordNotation(value: boolean) {
this.showValidationIssues = value;
this.updateValidationIssues();
this.cRef.markForCheck();
}
public ngOnInit(): void {
setInterval(() => {
if (!this.fullscreen || this.index === -1 || !this.viewSections?.toArray()[this.index]) {
@@ -106,6 +122,54 @@ export class SongTextComponent implements OnInit {
return text;
}
public getDisplaySegments(line: Line, trim = false): DisplaySegment[] {
const text = trim ? line.text.trim() : this.transform(line.text);
const lineNumber = line.lineNumber;
if (!lineNumber) {
return [{text, invalid: false, isTab: false}];
}
const issues = this.invalidChordIssuesByLine.get(lineNumber);
if (!issues || issues.length === 0) {
return [{text, invalid: false, isTab: false}];
}
const ranges: Array<{start: number; end: number; isTab: boolean}> = [];
let searchStart = 0;
issues.forEach(issue => {
const index = text.indexOf(issue.token, searchStart);
if (index === -1) {
return;
}
ranges.push({start: index, end: index + issue.token.length, isTab: issue.reason === 'tab_character'});
searchStart = index + issue.token.length;
});
if (ranges.length === 0) {
return [{text, invalid: false, isTab: false}];
}
const segments: DisplaySegment[] = [];
let cursor = 0;
ranges.forEach(range => {
if (range.start > cursor) {
segments.push({text: text.slice(cursor, range.start), invalid: false, isTab: false});
}
segments.push({
text: range.isTab ? '⇥' : text.slice(range.start, range.end),
invalid: true,
isTab: range.isTab,
});
cursor = range.end;
});
if (cursor < text.length) {
segments.push({text: text.slice(cursor), invalid: false, isTab: false});
}
return segments;
}
public isComment(text: string) {
return text.startsWith('#');
}
@@ -113,6 +177,7 @@ export class SongTextComponent implements OnInit {
private render() {
this.offset = 0;
this.sections = [];
this.updateValidationIssues();
if (this.fullscreen) {
setTimeout(() => {
this.sections = this.textRenderingService.parse(this.iText, this.iTranspose, this.showComments);
@@ -124,6 +189,21 @@ export class SongTextComponent implements OnInit {
}
}
private updateValidationIssues(): void {
if (!this.showValidationIssues) {
this.invalidChordIssuesByLine = new Map<number, ChordValidationIssue[]>();
return;
}
const issuesByLine = new Map<number, ChordValidationIssue[]>();
this.textRenderingService.validateChordNotation(this.iText, this.showComments).forEach(issue => {
const lineIssues = issuesByLine.get(issue.lineNumber) ?? [];
lineIssues.push(issue);
issuesByLine.set(issue.lineNumber, lineIssues);
});
this.invalidChordIssuesByLine = issuesByLine;
}
private getNextChordMode(): ChordMode {
switch (this.iChordMode) {
case 'show':

View File

@@ -1,16 +1,92 @@
import {TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {of} from 'rxjs';
import {UserService} from '../../services/user/user.service';
import {RoleGuard} from './role.guard';
describe('RoleGuard', () => {
let guard: RoleGuard;
let routerSpy: jasmine.SpyObj<Router>;
beforeEach(async () => {
routerSpy = jasmine.createSpyObj<Router>('Router', ['createUrlTree']);
routerSpy.createUrlTree.and.callFake(commands => ({commands}) as never);
await TestBed.configureTestingModule({
providers: [
{provide: Router, useValue: routerSpy},
{provide: UserService, useValue: {user$: of(null)}},
],
});
beforeEach(() => {
void TestBed.configureTestingModule({});
guard = TestBed.inject(RoleGuard);
});
it('should be created', () => {
void expect(guard).toBeTruthy();
expect(guard).toBeTruthy();
});
it('should throw when requiredRoles is missing', () => {
expect(() => guard.canActivate({data: {}} as never)).toThrowError('requiredRoles is not defined!');
});
it('should deny access when there is no current user', done => {
guard.canActivate({data: {requiredRoles: ['leader']}} as never).subscribe(result => {
expect(result).toBeFalse();
done();
});
});
it('should allow admins regardless of requiredRoles', async done => {
TestBed.resetTestingModule();
routerSpy = jasmine.createSpyObj<Router>('Router', ['createUrlTree']);
await TestBed.configureTestingModule({
providers: [
{provide: Router, useValue: routerSpy},
{provide: UserService, useValue: {user$: of({role: 'user;admin'})}},
],
});
guard = TestBed.inject(RoleGuard);
guard.canActivate({data: {requiredRoles: ['leader']}} as never).subscribe(result => {
expect(result).toBeTrue();
done();
});
});
it('should allow users with a matching required role', async done => {
TestBed.resetTestingModule();
routerSpy = jasmine.createSpyObj<Router>('Router', ['createUrlTree']);
await TestBed.configureTestingModule({
providers: [
{provide: Router, useValue: routerSpy},
{provide: UserService, useValue: {user$: of({role: 'leader;user'})}},
],
});
guard = TestBed.inject(RoleGuard);
guard.canActivate({data: {requiredRoles: ['leader']}} as never).subscribe(result => {
expect(result).toBeTrue();
done();
});
});
it('should redirect users without the required role to their role default route', async done => {
TestBed.resetTestingModule();
routerSpy = jasmine.createSpyObj<Router>('Router', ['createUrlTree']);
routerSpy.createUrlTree.and.returnValue({redirect: ['presentation']} as never);
await TestBed.configureTestingModule({
providers: [
{provide: Router, useValue: routerSpy},
{provide: UserService, useValue: {user$: of({role: 'presenter'})}},
],
});
guard = TestBed.inject(RoleGuard);
guard.canActivate({data: {requiredRoles: ['leader']}} as never).subscribe(result => {
expect(routerSpy.createUrlTree).toHaveBeenCalledWith(['presentation']);
expect(result).toEqual({redirect: ['presentation']} as never);
done();
});
});
});

View File

@@ -21,7 +21,7 @@
<style>
#load-bg {
background-color: #222;
background: linear-gradient(39deg, var(--bg-deep), var(--bg-mid), var(--bg-soft));
position: fixed;
top: 0;
left: 0;
@@ -83,8 +83,8 @@
</head>
<body>
<app-root></app-root>
<script>importCCLI = {}</script>
<script>setStrophe = {}</script>
<script>importCCLI = {};</script>
<script>setStrophe = {};</script>
<noscript>Please enable JavaScript to continue using this application.</noscript>
<div id="load-bg">

View File

@@ -1,19 +1,7 @@
.card-1 {
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
}
.card-2 {
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}
.card-3 {
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
}
.card-4 {
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
}
.card-5 {
box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0, 0.22);
:root {
--shadow-card-1: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
--shadow-card-2: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
--shadow-card-3: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
--shadow-card-4: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
--shadow-card-5: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0, 0.22);
}

View File

@@ -37,8 +37,7 @@
}
html {
scroll-behavior: smooth;
overflow: hidden;
scroll-behavior: auto;
}
body {
@@ -46,9 +45,15 @@ body {
font-family: Roboto, "Helvetica Neue", sans-serif;
font-size: 14px;
color: var(--text);
position: relative;
}
body::before {
content: '';
position: fixed;
inset: 0;
background: linear-gradient(39deg, var(--bg-deep), var(--bg-mid), var(--bg-soft));
overflow: auto;
z-index: -1;
}
p {
@@ -78,6 +83,10 @@ a {
}
}
body .cdk-overlay-transparent-backdrop.cdk-overlay-backdrop-showing {
background-color: rgba(0, 0, 0);
opacity: 0.05;
}
.content > *:not(router-outlet) {
display: flex;
@@ -99,10 +108,6 @@ a {
}
}
html, body {
height: 100vh;
}
body {
margin: 0;
font-family: Roboto, "Helvetica Neue", sans-serif;

View File

@@ -17,6 +17,18 @@ import {environment} from './environments/environment';
import {DbService} from './app/services/db.service';
type req = {keys: () => {map: (context: req) => void}};
type TestingModuleDefinition = Parameters<typeof TestBed.configureTestingModule>[0];
type TestingProviderList = NonNullable<NonNullable<TestingModuleDefinition>['providers']>;
type CollectionStub = {
valueChanges: () => ReturnType<typeof of>;
add: () => Promise<{id: string}>;
};
type DocumentStub = {
set: () => Promise<void>;
update: () => Promise<void>;
delete: () => Promise<void>;
collection: () => CollectionStub;
};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
@@ -24,7 +36,7 @@ getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDyn
const routeParams$ = new BehaviorSubject<Record<string, unknown>>({});
const queryParams$ = new BehaviorSubject<Record<string, unknown>>({});
const defaultTestingProviders = [
const defaultTestingProviders: TestingProviderList = [
provideNoopAnimations(),
provideNativeDateAdapter(),
provideRouter([]),
@@ -49,26 +61,29 @@ const defaultTestingProviders = [
useValue: {
col$: () => of([]),
doc$: () => of(null),
col: () => ({
col: (): CollectionStub => ({
valueChanges: () => of([]),
add: async () => ({id: 'test-id'}),
add: () => Promise.resolve({id: 'test-id'}),
}),
doc: () => ({
set: async () => void 0,
update: async () => void 0,
delete: async () => void 0,
collection: () => ({
doc: (): DocumentStub => ({
set: () => Promise.resolve(),
update: () => Promise.resolve(),
delete: () => Promise.resolve(),
collection: (): CollectionStub => ({
valueChanges: () => of([]),
add: async () => ({id: 'test-id'}),
add: () => Promise.resolve({id: 'test-id'}),
}),
}),
},
},
];
const originalConfigureTestingModule = TestBed.configureTestingModule.bind(TestBed);
TestBed.configureTestingModule = ((moduleDef?: Parameters<typeof TestBed.configureTestingModule>[0]) =>
originalConfigureTestingModule({
...moduleDef,
providers: [...defaultTestingProviders, ...(moduleDef?.providers ?? [])],
})) as typeof TestBed.configureTestingModule;
const originalConfigureTestingModule = TestBed.configureTestingModule.bind(TestBed) as typeof TestBed.configureTestingModule;
const configureTestingModule: typeof TestBed.configureTestingModule = moduleDef => {
const extraProviders: TestingProviderList = moduleDef?.providers ?? [];
const mergedModuleDef: TestingModuleDefinition = moduleDef ? {...moduleDef} : {};
mergedModuleDef.providers = defaultTestingProviders.concat(extraProviders);
return originalConfigureTestingModule(mergedModuleDef);
};
TestBed.configureTestingModule = configureTestingModule;