37 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
db6a230696 fix user serivce 2026-03-09 23:46:04 +01:00
0d0873730a migrate angular 21 tests 2026-03-09 23:25:17 +01:00
bb08e46b0c migrate angular 21 finalize 2026-03-09 22:56:31 +01:00
26c99a0dae migrate angular 21 2026-03-09 22:43:40 +01:00
0203d4ea9d migrate firebase storage 2026-03-09 21:57:26 +01:00
b6c2fe1645 migrate firebase db 2026-03-09 21:50:49 +01:00
a569c070c5 migrate firebase auth 2026-03-09 18:57:09 +01:00
f7be5c082a optimize remote #3 2026-03-09 18:41:43 +01:00
a46eeeee04 optimize remote #2 2026-03-09 18:38:00 +01:00
6edfb7e297 codex session 2026-03-09 18:33:11 +01:00
36e1241539 optimize show filter 2026-03-09 18:29:56 +01:00
194f9ac556 fix show filter 2026-03-09 17:51:35 +01:00
ce9e5b5585 optimize firebase monitor reads 2026-03-09 17:48:59 +01:00
3e10762eaf optimize firebase remote reads 2026-03-09 17:44:45 +01:00
d81fb3743b optimize firebase reads 2026-03-09 17:41:24 +01:00
4141824b00 optimize transpose service 2026-03-09 17:18:49 +01:00
f7e11b792c fix transpose warning 2026-03-09 17:04:00 +01:00
a12e1ccb2f fix material palette warning 2026-03-09 17:02:18 +01:00
4e8a50374e color palette rework #2 2026-03-09 16:53:55 +01:00
0c2157bd0a color palette rework 2026-03-09 16:47:08 +01:00
0b831e45d5 replace less variables 2026-03-09 16:39:41 +01:00
3fb2e8b341 optimize read calls 2026-03-09 16:32:13 +01:00
ed69d9e972 optimize remote 2025-11-29 15:23:01 +01:00
f49404f8be fix key events and add time to fullscreen 2025-02-16 12:40:08 +01:00
83573fde31 fix delete show song and not deleted order song causes crash 2025-02-16 12:24:38 +01:00
174 changed files with 24324 additions and 18390 deletions

View File

@@ -1,12 +1,7 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below. # Angular 21-supported baseline to avoid unsupported-browser build warnings.
# For additional information regarding the format and rule options, please see: last 2 Chrome major versions
# https://github.com/browserslist/browserslist#queries last 2 Edge major versions
last 2 Firefox major versions
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR Firefox ESR
not dead last 2 Safari major versions
not IE 9-11 # For IE 9-11 support, remove 'not'. last 2 iOS major versions

View File

@@ -54,6 +54,21 @@
"plugin:@angular-eslint/template/recommended" "plugin:@angular-eslint/template/recommended"
], ],
"rules": {} "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,12 +1,15 @@
<component name="ProjectRunConfigurationManager"> <component name="ProjectRunConfigurationManager">
<configuration default="false" name="start" type="js.build_tools.npm" nameIsGenerated="true"> <configuration default="false" name="start" type="js.build_tools.npm" nameIsGenerated="true">
<package-json value="$PROJECT_DIR$/package.json"/> <package-json value="$PROJECT_DIR$/package.json" />
<command value="run"/> <command value="run" />
<scripts> <scripts>
<script value="start"/> <script value="start" />
</scripts> </scripts>
<node-interpreter value="project"/> <node-interpreter value="project" />
<envs/> <envs />
<method v="2"/> <EXTENSION ID="com.intellij.lang.javascript.buildTools.npm.rc.StartBrowserRunConfigurationExtension">
<browser name="98ca6316-2f89-46d9-a9e5-fa9e2b0625b3" start="true" with-js-debugger="true" url="http://localhost.4200" />
</EXTENSION>
<method v="2" />
</configuration> </configuration>
</component> </component>

View File

@@ -1 +1,19 @@
# wgenerator # wgenerator
## Admin migration
If `songUsage` needs to be rebuilt from all existing shows, log in with a user that has the `admin` role and run this in the browser console:
```js
await window.wgeneratorAdmin.rebuildSongUsage()
```
The migration:
- resets `songUsage` for all users
- scans all shows and all `shows/{id}/songs` entries
- rebuilds the per-user counters based on show ownership
It returns a summary object with processed user, show and show-song counts.
This is intended as a manual one-off migration and is read-heavy by design.

View File

@@ -155,6 +155,30 @@
}, },
"@angular-eslint/schematics:library": { "@angular-eslint/schematics:library": {
"setParserOptionsProject": true "setParserOptionsProject": true
},
"@schematics/angular:component": {
"type": "component"
},
"@schematics/angular:directive": {
"type": "directive"
},
"@schematics/angular:service": {
"type": "service"
},
"@schematics/angular:guard": {
"typeSeparator": "."
},
"@schematics/angular:interceptor": {
"typeSeparator": "."
},
"@schematics/angular:module": {
"typeSeparator": "."
},
"@schematics/angular:pipe": {
"typeSeparator": "."
},
"@schematics/angular:resolver": {
"typeSeparator": "."
} }
} }
} }

76
codex-session.json Normal file
View File

@@ -0,0 +1,76 @@
{
"updated_at": "2026-03-09",
"project": "wgenerator",
"summary": {
"css_theme": [
"LESS @-Variablen durch CSS-Custom-Properties ersetzt",
"natuerlichere Farbpalette auf Basis des Body-Gradients eingefuehrt",
"Material Icon Buttons auf die Primaerfarbe abgestimmt",
"mehrere harte Farben in normale App-Views auf Tokens umgestellt",
"Monitor-/Beamer-Ansicht bewusst kontrastreich belassen"
],
"material_theme": [
"src/custom-theme.scss auf map-basierte Angular-Material-M2-Theme-Definition umgestellt",
"Warnung zu legacy define-light-theme-Signatur behoben"
],
"transpose": [
"TransposeService auf Halbtonlogik umgebaut",
"unbekannte Akkorde rendern bewusst als X",
"dynamisches Rendern statt festem 100-Zeichen-Template",
"Tests fuer Enharmonik, B/H, X-Faelle und Key-Helper ergaenzt",
"key.helper Korrekturen: Gb-Mapping und D-Skala"
],
"firebase_reads": [
"ConfigService und GlobalSettingsService auf Singleton-Streams umgestellt",
"read$ fuer shows, songs und guest wieder direkt ueber doc$ statt list$.find(...)",
"songUsage Login-Backfill entfernt",
"songUsage-Inkremente auf FieldValue.increment(...) umgestellt",
"Admin-Konsoleintrag window.wgeneratorAdmin.rebuildSongUsage() hinzugefuegt",
"showSongDataService.list$(showId) pro showId gecacht",
"monitor.component.ts entkoppelt, damit Show-Metadaten keine unnoetigen Song-Reads triggern"
],
"shows_filter": [
"showType-Filter funktioniert wieder clientseitig",
"Zeitraumfilter fachlich auf heute minus n*30 Tage umgestellt",
"oeffentliche Shows werden fuer den Zeitraum serverseitig per Firestore-Query geladen",
"owner und showType filtern weiterhin clientseitig auf dem kleineren Resultset",
"Null-Fall im Filter-Template abgesichert"
]
},
"important_files": [
"src/styles/styles.less",
"src/custom-theme.scss",
"src/app/modules/songs/services/transpose.service.ts",
"src/app/modules/songs/services/transpose.service.spec.ts",
"src/app/modules/songs/services/key.helper.ts",
"src/app/modules/songs/services/key.helper.spec.ts",
"src/app/services/config.service.ts",
"src/app/services/global-settings.service.ts",
"src/app/services/user/user.service.ts",
"src/main.ts",
"src/app/modules/shows/services/show-song-data.service.ts",
"src/app/modules/presentation/monitor/monitor.component.ts",
"src/app/modules/presentation/remote/remote.component.ts",
"src/app/modules/shows/services/show-data.service.ts",
"src/app/modules/shows/list/list.component.ts",
"src/app/modules/shows/list/filter/filter.component.ts",
"src/app/modules/shows/list/filter/filter.component.html",
"src/app/modules/songs/song/song.component.ts",
"src/app/modules/songs/song/song.component.html",
"README.md"
],
"console_commands": {
"song_usage_rebuild": "await window.wgeneratorAdmin.rebuildSongUsage()"
},
"known_tradeoffs": [
"songUsage wird historisch nicht mehr automatisch beim Login rekonstruiert; dafuer ist die Admin-Migration gedacht",
"songUsage decrement kann bei inkonsistenten Aufrufpfaden theoretisch unter 0 laufen",
"owner- und showType-Filter fuer Shows laufen noch clientseitig",
"oeffentliche Show-Zeitraumquery kann Firestore-Indexe benoetigen"
},
"next_candidates": [
"remote.component.ts weiter entkoppeln, damit textRendering.parse(...) nicht bei jeder Show-Metadatenaenderung fuer alle Songs neu laeuft",
"users$ als Voll-Collection-Livestream spaeter auf Einzelreads bzw. gezieltere Nutzung pruefen",
"weitere Firestore-Read-Hotspots mit echten Metriken gegenpruefen"
]
}

34511
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,60 +11,57 @@
}, },
"private": true, "private": true,
"dependencies": { "dependencies": {
"@angular/animations": "^19.0.5", "@angular/animations": "^21.2.2",
"@angular/cdk": "^19.0.4", "@angular/cdk": "^21.2.1",
"@angular/common": "^19.0.5", "@angular/common": "^21.2.2",
"@angular/compiler": "^19.0.5", "@angular/compiler": "^21.2.2",
"@angular/core": "^19.0.5", "@angular/core": "^21.2.2",
"@angular/fire": "^18.0.1", "@angular/fire": "21.0.0-rc.0",
"@angular/forms": "^19.0.5", "@angular/forms": "^21.2.2",
"@angular/material": "^19.0.4", "@angular/material": "^21.2.1",
"@angular/platform-browser": "^19.0.5", "@angular/platform-browser": "^21.2.2",
"@angular/platform-browser-dynamic": "^19.0.5", "@angular/platform-browser-dynamic": "^21.2.2",
"@angular/router": "^19.0.5", "@angular/router": "^21.2.2",
"@angular/service-worker": "^19.0.5", "@angular/service-worker": "^21.2.2",
"@fortawesome/angular-fontawesome": "^0.14.1", "@fortawesome/angular-fontawesome": "^4.0.0",
"@fortawesome/fontawesome-svg-core": "^6.5.1", "@fortawesome/fontawesome-svg-core": "^7.2.0",
"@fortawesome/free-solid-svg-icons": "^6.5.1", "@fortawesome/free-solid-svg-icons": "^7.2.0",
"docx": "^8.5.0", "docx": "^9.6.0",
"firebase": "^10.8.0", "firebase": "^12.10.0",
"lodash": "^4.17.21", "ngx-mat-select-search": "^8.0.4",
"ngx-mat-select-search": "^7.0.5", "qrcode": "^1.5.4",
"qrcode": "^1.5.3",
"rxfire": "^6.0.5",
"rxjs": "~7.8.1", "rxjs": "~7.8.1",
"swiper": "^11.0.6", "swiper": "^12.1.2",
"tslib": "^2.6.2", "tslib": "^2.8.1",
"zone.js": "~0.15.0" "zone.js": "~0.15.0"
}, },
"devDependencies": { "devDependencies": {
"@angular-devkit/architect": "0.1900.6", "@angular-devkit/architect": "0.2102.1",
"@angular-devkit/build-angular": "^19.0.6", "@angular-devkit/build-angular": "^21.2.1",
"@angular-eslint/builder": "19.0.2", "@angular-eslint/builder": "21.3.0",
"@angular-eslint/eslint-plugin": "19.0.2", "@angular-eslint/eslint-plugin": "21.3.0",
"@angular-eslint/eslint-plugin-template": "19.0.2", "@angular-eslint/eslint-plugin-template": "21.3.0",
"@angular-eslint/schematics": "19.0.2", "@angular-eslint/schematics": "21.3.0",
"@angular-eslint/template-parser": "19.0.2", "@angular-eslint/template-parser": "21.3.0",
"@angular/cli": "^19.0.6", "@angular/cli": "^21.2.1",
"@angular/compiler-cli": "^19.0.5", "@angular/compiler-cli": "^21.2.2",
"@angular/language-service": "^19.0.5", "@angular/language-service": "^21.2.2",
"@types/jasmine": "~5.1.4", "@types/jasmine": "~6.0.0",
"@types/jasminewd2": "~2.0.13", "@types/jasminewd2": "~2.0.13",
"@types/lodash": "^4.14.202", "@typescript-eslint/eslint-plugin": "^8.57.0",
"@typescript-eslint/eslint-plugin": "^7.2.0", "@typescript-eslint/parser": "^8.57.0",
"@typescript-eslint/parser": "^7.2.0", "eslint": "^9.39.4",
"eslint": "^8.57.0", "eslint-config-prettier": "^10.1.8",
"eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-prettier": "^5.1.3", "firebase-tools": "^15.9.1",
"firebase-tools": "^13.3.1", "jasmine-core": "~6.1.0",
"jasmine-core": "~5.1.2",
"jasmine-spec-reporter": "~7.0.0", "jasmine-spec-reporter": "~7.0.0",
"karma": "~6.4.2", "karma": "~6.4.4",
"karma-chrome-launcher": "~3.2.0", "karma-chrome-launcher": "~3.2.0",
"karma-coverage-istanbul-reporter": "~3.0.3", "karma-coverage-istanbul-reporter": "~3.0.3",
"karma-jasmine": "~5.1.0", "karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "^2.1.0", "karma-jasmine-html-reporter": "^2.2.0",
"prettier": "^3.2.5", "prettier": "^3.8.1",
"typescript": "~5.5.4" "typescript": "~5.9.3"
} }
} }

View File

@@ -1,7 +1,7 @@
import {NgModule} from '@angular/core'; import {NgModule} from '@angular/core';
import {PreloadAllModules, RouterModule, Routes} from '@angular/router'; import {PreloadAllModules, RouterModule, Routes} from '@angular/router';
import {AngularFireAuthGuard, redirectUnauthorizedTo} from '@angular/fire/compat/auth-guard';
import {RoleGuard} from './widget-modules/guards/role.guard'; import {RoleGuard} from './widget-modules/guards/role.guard';
import {AuthGuard} from './widget-modules/guards/auth.guard';
const routes: Routes = [ const routes: Routes = [
{ {
@@ -12,27 +12,24 @@ const routes: Routes = [
{ {
path: 'songs', path: 'songs',
loadChildren: () => import('./modules/songs/songs.module').then(m => m.SongsModule), loadChildren: () => import('./modules/songs/songs.module').then(m => m.SongsModule),
canActivate: [AngularFireAuthGuard, RoleGuard], canActivate: [AuthGuard, RoleGuard],
data: { data: {
authGuardPipe: () => redirectUnauthorizedTo(['user', 'login']),
requiredRoles: ['user'], requiredRoles: ['user'],
}, },
}, },
{ {
path: 'shows', path: 'shows',
loadChildren: () => import('./modules/shows/shows.module').then(m => m.ShowsModule), loadChildren: () => import('./modules/shows/shows.module').then(m => m.ShowsModule),
canActivate: [AngularFireAuthGuard, RoleGuard], canActivate: [AuthGuard, RoleGuard],
data: { data: {
authGuardPipe: () => redirectUnauthorizedTo(['user', 'login']),
requiredRoles: ['leader', 'member'], requiredRoles: ['leader', 'member'],
}, },
}, },
{ {
path: 'presentation', path: 'presentation',
loadChildren: () => import('./modules/presentation/presentation.module').then(m => m.PresentationModule), loadChildren: () => import('./modules/presentation/presentation.module').then(m => m.PresentationModule),
canActivate: [AngularFireAuthGuard, RoleGuard], canActivate: [AuthGuard, RoleGuard],
data: { data: {
authGuardPipe: () => redirectUnauthorizedTo(['user', 'login']),
requiredRoles: ['presenter'], requiredRoles: ['presenter'],
}, },
}, },

View File

@@ -1,3 +1,3 @@
h1 { h1 {
color: red; color: var(--text);
} }

View File

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

View File

@@ -1,4 +1,4 @@
<div class="brand"> <div class="brand">
<app-logo></app-logo> <app-logo></app-logo>
<div class="copyright">© 2019 - 2024 - Benjamin Ifland</div> <div class="copyright">© 2019 - 2026 - Benjamin Ifland</div>
</div> </div>

View File

@@ -1,6 +1,7 @@
<div class="frame"> <div class="frame">
<app-brand class="brand"></app-brand> <app-brand class="brand"></app-brand>
<div *ngIf="user$ | async as user" class="text"> @if (user$ | async; as user) {
<div class="text">
<div class="welcome">WILLKOMMEN</div> <div class="welcome">WILLKOMMEN</div>
<div class="name">{{ user.name }}</div> <div class="name">{{ user.name }}</div>
<div class="roles"> <div class="roles">
@@ -8,4 +9,5 @@
Administrator! Administrator!
</div> </div>
</div> </div>
}
</div> </div>

View File

@@ -1,4 +1,6 @@
@animation-duration: 20s; :host {
--animation-duration: 20s;
}
.frame { .frame {
width: 512px; width: 512px;
@@ -11,10 +13,10 @@
.brand { .brand {
position: absolute; position: absolute;
left: 0; left: 0;
animation: @animation-duration brand ease-in-out forwards; animation: var(--animation-duration) brand ease-in-out forwards;
opacity: 0; opacity: 0;
@media screen and (max-width: 860px) { @media screen and (max-width: 860px) {
animation: @animation-duration brand-mobile ease-in-out forwards; animation: var(--animation-duration) brand-mobile ease-in-out forwards;
} }
} }
@@ -34,7 +36,7 @@
@media screen and (max-width: 860px) { @media screen and (max-width: 860px) {
font-size: 40px; font-size: 40px;
} }
animation: @animation-duration welcome ease-in-out forwards; animation: var(--animation-duration) welcome ease-in-out forwards;
} }
.name { .name {
@@ -43,14 +45,14 @@
@media screen and (max-width: 860px) { @media screen and (max-width: 860px) {
font-size: 30px; font-size: 30px;
} }
animation: @animation-duration name ease-in-out forwards; animation: var(--animation-duration) name ease-in-out forwards;
} }
.roles { .roles {
opacity: 0; opacity: 0;
font-size: 20px; font-size: 20px;
margin-top: 40px; margin-top: 40px;
animation: @animation-duration roles ease-in-out forwards; animation: var(--animation-duration) roles ease-in-out forwards;
} }
} }

View File

@@ -1,20 +1,24 @@
import {Component} from '@angular/core'; import {Component, inject} from '@angular/core';
import {UserService} from '../../../services/user/user.service'; import {UserService} from '../../../services/user/user.service';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {User} from '../../../services/user/user'; import {User} from '../../../services/user/user';
import {BrandComponent} from '../brand.component'; import {BrandComponent} from '../brand.component';
import {AsyncPipe, NgIf} from '@angular/common'; import {AsyncPipe} from '@angular/common';
@Component({ @Component({
selector: 'app-new-user', selector: 'app-new-user',
templateUrl: './new-user.component.html', templateUrl: './new-user.component.html',
styleUrls: ['./new-user.component.less'], styleUrls: ['./new-user.component.less'],
imports: [BrandComponent, NgIf, AsyncPipe], imports: [BrandComponent, AsyncPipe],
}) })
export class NewUserComponent { export class NewUserComponent {
private userService = inject(UserService);
public user$: Observable<User | null> | null = null; public user$: Observable<User | null> | null = null;
public constructor(private userService: UserService) { public constructor() {
const userService = this.userService;
this.user$ = userService.user$; this.user$ = userService.user$;
} }
} }

View File

@@ -0,0 +1,75 @@
import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {DbService} from 'src/app/services/db.service';
import {GuestShowDataService} from './guest-show-data.service';
describe('GuestShowDataService', () => {
let service: GuestShowDataService;
let docUpdateSpy: jasmine.Spy<() => Promise<void>>;
let docDeleteSpy: jasmine.Spy<() => Promise<void>>;
let docSpy: jasmine.Spy;
let colAddSpy: jasmine.Spy<() => Promise<{id: string}>>;
let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(async () => {
docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.returnValue({
update: docUpdateSpy,
delete: docDeleteSpy,
});
colAddSpy = jasmine.createSpy('add').and.resolveTo({id: 'guest-2'});
colSpy = jasmine.createSpy('col').and.returnValue({add: colAddSpy});
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['col$', 'doc$', 'doc', 'col']);
dbServiceSpy.col$.and.returnValue(of([{id: 'guest-1'}]) as never);
dbServiceSpy.doc$.and.returnValue(of({id: 'guest-1'}) as never);
dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy);
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});
service = TestBed.inject(GuestShowDataService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should read the guest collection for list$', () => {
service.list$.subscribe();
expect(dbServiceSpy.col$).toHaveBeenCalledWith('guest');
});
it('should read a single guest show by id', () => {
service.read$('guest-7').subscribe();
expect(dbServiceSpy.doc$).toHaveBeenCalledWith('guest/guest-7');
});
it('should update a guest show document', async () => {
await service.update$('guest-7', {published: true} as never);
expect(docSpy).toHaveBeenCalledWith('guest/guest-7');
const [updatePayload] = docUpdateSpy.calls.mostRecent().args as unknown as [Record<string, unknown>];
expect(updatePayload).toEqual({published: true});
});
it('should add a guest show and return the created id', async () => {
await expectAsync(service.add({published: false} as never)).toBeResolvedTo('guest-2');
expect(colSpy).toHaveBeenCalledWith('guest');
const [addPayload] = colAddSpy.calls.mostRecent().args as unknown as [Record<string, unknown>];
expect(addPayload).toEqual({published: false});
});
it('should delete a guest show document', async () => {
await service.delete('guest-7');
expect(docSpy).toHaveBeenCalledWith('guest/guest-7');
expect(docDeleteSpy).toHaveBeenCalled();
});
});

View File

@@ -1,6 +1,6 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {map} from 'rxjs/operators'; import {shareReplay} from 'rxjs/operators';
import {DbService} from 'src/app/services/db.service'; import {DbService} from 'src/app/services/db.service';
import {GuestShow} from './guest-show'; import {GuestShow} from './guest-show';
@@ -8,14 +8,17 @@ import {GuestShow} from './guest-show';
providedIn: 'root', providedIn: 'root',
}) })
export class GuestShowDataService { export class GuestShowDataService {
public list$: BehaviorSubject<GuestShow[]> = new BehaviorSubject<GuestShow[]>([]); private dbService = inject(DbService);
private collection = 'guest'; private collection = 'guest';
public list$: Observable<GuestShow[]> = this.dbService.col$<GuestShow>(this.collection).pipe(
shareReplay({
bufferSize: 1,
refCount: true,
})
);
public constructor(private dbService: DbService) { public read$: (id: string) => Observable<GuestShow | null> = (id: string): Observable<GuestShow | null> => this.dbService.doc$(`${this.collection}/${id}`);
this.dbService.col$<GuestShow>(this.collection).subscribe(_ => this.list$.next(_));
}
public read$: (id: string) => Observable<GuestShow | null> = (id: string): Observable<GuestShow | null> => this.list$.pipe(map(_ => _.find(s => s.id === id) || null));
public update$: (id: string, data: Partial<GuestShow>) => Promise<void> = async (id: string, data: Partial<GuestShow>): Promise<void> => public update$: (id: string, data: Partial<GuestShow>) => Promise<void> = async (id: string, data: Partial<GuestShow>): Promise<void> =>
await this.dbService.doc(this.collection + '/' + id).update(data); await this.dbService.doc(this.collection + '/' + id).update(data);
public add: (data: Partial<GuestShow>) => Promise<string> = async (data: Partial<GuestShow>): Promise<string> => (await this.dbService.col(this.collection).add(data)).id; public add: (data: Partial<GuestShow>) => Promise<string> = async (data: Partial<GuestShow>): Promise<string> => (await this.dbService.col(this.collection).add(data)).id;

View File

@@ -0,0 +1,64 @@
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(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();
await TestBed.configureTestingModule({
providers: [
{provide: GuestShowDataService, useValue: guestShowDataServiceSpy},
{provide: ShowService, useValue: showServiceSpy},
],
});
service = TestBed.inject(GuestShowService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
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 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);
expect(guestShowDataServiceSpy.add).toHaveBeenCalledWith({
showType: 'service-worship',
date: show.date,
songs,
});
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {shareId: 'share-1'});
});
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 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);
expect(guestShowDataServiceSpy.update$).toHaveBeenCalledWith('share-9', {
showType: 'service-worship',
date: show.date,
songs,
});
expect(guestShowDataServiceSpy.add).not.toHaveBeenCalled();
expect(showServiceSpy.update$).not.toHaveBeenCalled();
});
});

View File

@@ -1,4 +1,4 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {Show} from '../shows/services/show'; import {Show} from '../shows/services/show';
import {Song} from '../songs/services/song'; import {Song} from '../songs/services/song';
import {GuestShowDataService} from './guest-show-data.service'; import {GuestShowDataService} from './guest-show-data.service';
@@ -8,10 +8,8 @@ import {ShowService} from '../shows/services/show.service';
providedIn: 'root', providedIn: 'root',
}) })
export class GuestShowService { export class GuestShowService {
public constructor( private showService = inject(ShowService);
private showService: ShowService, private guestShowDataService = inject(GuestShowDataService);
private guestShowDataService: GuestShowDataService
) {}
public async share(show: Show, songs: Song[]): Promise<string> { public async share(show: Show, songs: Song[]): Promise<string> {
const data = { const data = {
@@ -19,14 +17,15 @@ export class GuestShowService {
date: show.date, date: show.date,
songs: songs, songs: songs,
}; };
let shareId = show.shareId;
if (!show.shareId) { if (!show.shareId) {
const shareId = await this.guestShowDataService.add(data); shareId = await this.guestShowDataService.add(data);
await this.showService.update$(show.id, {shareId}); await this.showService.update$(show.id, {shareId});
} else { } else {
await this.guestShowDataService.update$(show.shareId, data); await this.guestShowDataService.update$(show.shareId, data);
} }
return window.location.protocol + '//' + window.location.host + '/guest/' + show.shareId; return window.location.protocol + '//' + window.location.host + '/guest/' + shareId;
} }
} }

View File

@@ -1,6 +1,5 @@
import firebase from 'firebase/compat/app';
import {Song} from '../songs/services/song'; import {Song} from '../songs/services/song';
import Timestamp = firebase.firestore.Timestamp; import {Timestamp} from '@angular/fire/firestore';
export interface GuestShow { export interface GuestShow {
id: string; id: string;

View File

@@ -1,25 +1,28 @@
<div *ngIf="show$|async as show" class="page"> @if (show$|async; as show) {
<div class="page">
<div class="title"> <div class="title">
<div class="left">{{ show.showType|showType }}</div> <div class="left">{{ show.showType|showType }}</div>
<div class="right">{{ show.date.toDate() | date: 'dd.MM.yyyy' }}</div> <div class="right">{{ show.date.toDate() | date: 'dd.MM.yyyy' }}</div>
</div> </div>
<div class="view"> <div class="view">
<swiper-container scrollbar="true"> <swiper-container scrollbar="true">
<swiper-slide *ngFor="let song of show.songs; let i = index; trackBy: trackBy" @for (song of show.songs; track trackBy(i, song); let i = $index) {
<swiper-slide
class="song-swipe"> class="song-swipe">
<div class="song-title">{{ song.title }}</div> <div class="song-title">{{ song.title }}</div>
<div class="legal"> <div class="legal">
<p *ngIf="song.artist">{{ song.artist }}</p> @if (song.artist) {
<p>{{ song.artist }}</p>
}
</div> </div>
<app-song-text <app-song-text
[text]="song.text" [text]="song.text"
></app-song-text> ></app-song-text>
</swiper-slide> </swiper-slide>
}
</swiper-container> </swiper-container>
</div> </div>
</div> </div>
}

View File

@@ -1,5 +1,5 @@
.page { .page {
background: #0009; background: var(--overlay);
position: fixed; position: fixed;
top: 0; top: 0;
bottom: 0; bottom: 0;
@@ -7,15 +7,15 @@
right: 0; right: 0;
backdrop-filter: blur(8px); backdrop-filter: blur(8px);
--swiper-scrollbar-bg-color: #fff3; --swiper-scrollbar-bg-color: rgba(247, 251, 255, 0.2);
--swiper-scrollbar-drag-bg-color: #fff9; --swiper-scrollbar-drag-bg-color: rgba(247, 251, 255, 0.6);
--swiper-scrollbar-sides-offset: 20px; --swiper-scrollbar-sides-offset: 20px;
--swiper-scrollbar-top: 100px; --swiper-scrollbar-top: 100px;
--swiper-scrollbar-bottom: auto; --swiper-scrollbar-bottom: auto;
} }
.title { .title {
color: white; color: var(--text-inverse);
padding: 70px 20px 0; padding: 70px 20px 0;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@@ -23,7 +23,7 @@
.left { .left {
font-size: 1.8em; font-size: 1.8em;
color: #fff; color: var(--text-inverse);
} }
} }
@@ -35,7 +35,7 @@
.legal { .legal {
padding: 0 20px; padding: 0 20px;
font-size: 0.6em; font-size: 0.6em;
color: #fff9; color: rgba(247, 251, 255, 0.72);
} }
.view { .view {
@@ -44,7 +44,7 @@
bottom: 0; bottom: 0;
left: 0; left: 0;
right: 0; right: 0;
color: white; color: var(--text-inverse);
} }
app-song-text { app-song-text {

View File

@@ -1,10 +1,10 @@
import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {Component, CUSTOM_ELEMENTS_SCHEMA, inject} from '@angular/core';
import {GuestShowDataService} from './guest-show-data.service'; import {GuestShowDataService} from './guest-show-data.service';
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute} from '@angular/router';
import {map, switchMap} from 'rxjs/operators'; import {map, switchMap} from 'rxjs/operators';
import {Song} from '../songs/services/song'; import {Song} from '../songs/services/song';
import {ConfigService} from '../../services/config.service'; import {ConfigService} from '../../services/config.service';
import {AsyncPipe, DatePipe, NgFor, NgIf} from '@angular/common'; import {AsyncPipe, DatePipe} from '@angular/common';
import {SongTextComponent} from '../../widget-modules/components/song-text/song-text.component'; import {SongTextComponent} from '../../widget-modules/components/song-text/song-text.component';
import {ShowTypePipe} from '../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../widget-modules/pipes/show-type-translater/show-type.pipe';
@@ -13,20 +13,18 @@ import {ShowTypePipe} from '../../widget-modules/pipes/show-type-translater/show
templateUrl: './guest.component.html', templateUrl: './guest.component.html',
styleUrls: ['./guest.component.less'], styleUrls: ['./guest.component.less'],
schemas: [CUSTOM_ELEMENTS_SCHEMA], schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [NgIf, NgFor, SongTextComponent, AsyncPipe, DatePipe, ShowTypePipe], imports: [SongTextComponent, AsyncPipe, DatePipe, ShowTypePipe],
}) })
export class GuestComponent { export class GuestComponent {
private currentRoute = inject(ActivatedRoute);
private service = inject(GuestShowDataService);
private configService = inject(ConfigService);
public show$ = this.currentRoute.params.pipe( public show$ = this.currentRoute.params.pipe(
map(param => param.id as string), map(param => param.id as string),
switchMap(id => this.service.read$(id)) switchMap(id => this.service.read$(id))
); );
public config$ = this.configService.get$(); public config$ = this.configService.get$();
public constructor(
private currentRoute: ActivatedRoute,
private service: GuestShowDataService,
private configService: ConfigService
) {}
public trackBy = (index: number, show: Song) => show.id; public trackBy = (index: number, show: Song) => show.id;
} }

View File

@@ -1,14 +1,27 @@
<ng-container *ngIf="song"> @if (song) {
<p *ngIf="song.artist">{{ song.artist }}</p> @if (song.artist) {
<p *ngIf="song.label">{{ song.label }}</p> <p>{{ song.artist }}</p>
<p *ngIf="song.termsOfUse" class="terms-of-use">{{ song.termsOfUse }}</p> }
<p *ngIf="song.origin">{{ song.origin }}</p> @if (song.label) {
<p>{{ song.label }}</p>
<div *ngIf="song.legalOwnerId"> }
<p *ngIf="song.legalOwner === 'CCLI' && config"> @if (song.termsOfUse) {
<p class="terms-of-use">{{ song.termsOfUse }}</p>
}
@if (song.origin) {
<p>{{ song.origin }}</p>
}
@if (song.legalOwnerId) {
<div>
@if (song.legalOwner === 'CCLI' && config) {
<p>
CCLI-Liednummer {{ song.legalOwnerId }}, CCLI-Lizenznummer CCLI-Liednummer {{ song.legalOwnerId }}, CCLI-Lizenznummer
{{ config.ccliLicenseId }} {{ config.ccliLicenseId }}
</p> </p>
<p *ngIf="song.legalOwner !== 'CCLI'">Liednummer {{ song.legalOwnerId }}</p> }
@if (song.legalOwner !== 'CCLI') {
<p>Liednummer {{ song.legalOwnerId }}</p>
}
</div> </div>
</ng-container> }
}

View File

@@ -1,13 +1,12 @@
import {Component, Input} from '@angular/core'; import {Component, Input} from '@angular/core';
import {Song} from '../../../songs/services/song'; import {Song} from '../../../songs/services/song';
import {Config} from '../../../../services/config'; import {Config} from '../../../../services/config';
import {NgIf} from '@angular/common';
@Component({ @Component({
selector: 'app-legal', selector: 'app-legal',
templateUrl: './legal.component.html', templateUrl: './legal.component.html',
styleUrls: ['./legal.component.less'], styleUrls: ['./legal.component.less'],
imports: [NgIf], imports: [],
}) })
export class LegalComponent { export class LegalComponent {
@Input() public song: Song | null = null; @Input() public song: Song | null = null;

View File

@@ -1,13 +1,11 @@
<div class="fullscreen background"></div> <div class="fullscreen background"></div>
<div *ngIf="song && showType" [style.font-size.px]="zoom" class="fullscreen background"> @if (showType) {
<div [style.font-size.px]="zoom" class="fullscreen background">
<div [class.visible]="presentationBackground==='blue'" class="bg-blue fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='blue'" class="bg-blue fullscreen bg-image"></div>
<div [class.visible]="presentationBackground==='green'" class="bg-green fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='green'" class="bg-green fullscreen bg-image"></div>
<div [class.visible]="presentationBackground==='leder'" class="bg-leder fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='leder'" class="bg-leder fullscreen bg-image"></div>
<div [class.visible]="presentationBackground==='praise'" class="bg-praise fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='praise'" class="bg-praise fullscreen bg-image"></div>
<div [class.visible]="presentationBackground==='bible'" class="bg-bible fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='bible'" class="bg-bible fullscreen bg-image"></div>
<div <div
[@songSwitch]="songId" [@songSwitch]="songId"
[class.blur]="songId === 'title' || songId === 'dynamicText'" [class.blur]="songId === 'title' || songId === 'dynamicText'"
@@ -17,19 +15,20 @@
> >
<app-logo></app-logo> <app-logo></app-logo>
</div> </div>
@if (songId === 'title') {
<div *ngIf="songId === 'title'" @songSwitch class="start fullscreen"> <div @songSwitch class="start fullscreen">
<div>{{ showType | showType }}</div> <div>{{ showType | showType }}</div>
<div class="date">{{ date | date: "dd.MM.yyyy" }}</div> <div class="date">{{ date | date: "dd.MM.yyyy" }}</div>
</div> </div>
}
<div *ngIf="songId === 'dynamicText'" @songSwitch class="start fullscreen dynamic-text"> @if (songId === 'dynamicText') {
<div @songSwitch class="start fullscreen dynamic-text">
<div>{{ presentationDynamicCaption }}</div> <div>{{ presentationDynamicCaption }}</div>
<div class="date">{{ presentationDynamicText }}</div> <div class="date">{{ presentationDynamicText }}</div>
</div> </div>
}
@if (song && songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText') {
<app-song-text <app-song-text
*ngIf="songId !== 'title' && songId !== 'empty'"
[@songSwitch]="songId" [@songSwitch]="songId"
[fullscreen]="true" [fullscreen]="true"
[header]="song.title" [header]="song.title"
@@ -39,10 +38,13 @@
[text]="song.text" [text]="song.text"
chordMode="hide" chordMode="hide"
></app-song-text> ></app-song-text>
}
@if (song && songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText') {
<app-legal <app-legal
*ngIf="songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText'"
[@songSwitch]="songId" [@songSwitch]="songId"
[config]="config$ | async" [config]="config$ | async"
[song]="song" [song]="song"
></app-legal> ></app-legal>
</div> }
</div>
}

View File

@@ -1,18 +1,17 @@
import {ChangeDetectorRef, Component, OnInit} from '@angular/core'; import {ChangeDetectorRef, Component, OnDestroy, OnInit, inject} from '@angular/core';
import {debounceTime, distinctUntilChanged, filter, map, switchMap, tap} from 'rxjs/operators'; import {distinctUntilChanged, filter, map, shareReplay, switchMap, takeUntil, tap} from 'rxjs/operators';
import {ShowService} from '../../shows/services/show.service'; import {ShowService} from '../../shows/services/show.service';
import {SongService} from '../../songs/services/song.service';
import {Song} from '../../songs/services/song'; import {Song} from '../../songs/services/song';
import {GlobalSettingsService} from '../../../services/global-settings.service'; import {GlobalSettingsService} from '../../../services/global-settings.service';
import {Config} from '../../../services/config'; import {Config} from '../../../services/config';
import {Observable} from 'rxjs'; import {Observable, Subject} from 'rxjs';
import {ConfigService} from '../../../services/config.service'; import {ConfigService} from '../../../services/config.service';
import {songSwitch} from '../../../widget-modules/components/song-text/animation'; import {songSwitch} from '../../../widget-modules/components/song-text/animation';
import {TextRenderingService} from '../../songs/services/text-rendering.service';
import {PresentationBackground, Show} from '../../shows/services/show'; import {PresentationBackground, Show} from '../../shows/services/show';
import {ShowSong} from '../../shows/services/show-song';
import {ShowSongService} from '../../shows/services/show-song.service'; import {ShowSongService} from '../../shows/services/show-song.service';
import {openFullscreen} from '../../../services/fullscreen'; import {openFullscreen} from '../../../services/fullscreen';
import {AsyncPipe, DatePipe, NgIf} from '@angular/common'; import {AsyncPipe, DatePipe} from '@angular/common';
import {LogoComponent} from './logo/logo.component'; import {LogoComponent} from './logo/logo.component';
import {SongTextComponent} from '../../../widget-modules/components/song-text/song-text.component'; import {SongTextComponent} from '../../../widget-modules/components/song-text/song-text.component';
import {LegalComponent} from './legal/legal.component'; import {LegalComponent} from './legal/legal.component';
@@ -23,9 +22,15 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
templateUrl: './monitor.component.html', templateUrl: './monitor.component.html',
styleUrls: ['./monitor.component.less'], styleUrls: ['./monitor.component.less'],
animations: [songSwitch], animations: [songSwitch],
imports: [NgIf, LogoComponent, SongTextComponent, LegalComponent, AsyncPipe, DatePipe, ShowTypePipe], imports: [LogoComponent, SongTextComponent, LegalComponent, AsyncPipe, DatePipe, ShowTypePipe],
}) })
export class MonitorComponent implements OnInit { export class MonitorComponent implements OnInit, OnDestroy {
private showService = inject(ShowService);
private showSongService = inject(ShowSongService);
private globalSettingsService = inject(GlobalSettingsService);
private configService = inject(ConfigService);
private cRef = inject(ChangeDetectorRef);
public song: Song | null = null; public song: Song | null = null;
public zoom = 10; public zoom = 10;
public currentShowId: string | null = null; public currentShowId: string | null = null;
@@ -37,55 +42,78 @@ export class MonitorComponent implements OnInit {
public date: Date | null = null; public date: Date | null = null;
public config$: Observable<Config | null>; public config$: Observable<Config | null>;
public presentationBackground: PresentationBackground = 'none'; public presentationBackground: PresentationBackground = 'none';
private destroy$ = new Subject<void>();
public constructor() {
const configService = this.configService;
public constructor(
private showService: ShowService,
private showSongService: ShowSongService,
private songService: SongService,
private textRenderingService: TextRenderingService,
private globalSettingsService: GlobalSettingsService,
private configService: ConfigService,
private cRef: ChangeDetectorRef
) {
this.config$ = configService.get$(); this.config$ = configService.get$();
} }
public ngOnInit(): void { public ngOnInit(): void {
openFullscreen(); openFullscreen();
this.globalSettingsService.get$ const currentShowId$ = this.globalSettingsService.get$.pipe(
.pipe( filter((settings): settings is NonNullable<typeof settings> => !!settings),
debounceTime(100), map(settings => settings.currentShow),
filter(_ => !!_), filter((showId): showId is string => !!showId),
map(_ => _),
map(_ => _.currentShow),
distinctUntilChanged(), distinctUntilChanged(),
tap(_ => (this.currentShowId = _)) tap(_ => (this.currentShowId = _)),
) takeUntil(this.destroy$)
);
const show$ = currentShowId$.pipe(
switchMap(showId => this.showService.read$(showId)),
filter((show): show is Show => !!show),
shareReplay({
bufferSize: 1,
refCount: true,
}),
takeUntil(this.destroy$)
);
show$
.pipe( .pipe(
switchMap(_ => this.showService.read$(_)), tap(show => {
filter(_ => !!_), this.showType = show.showType;
map(_ => _), this.date = show.date.toDate();
tap<Show>(_ => { this.index = show.presentationSection;
this.showType = _.showType; this.presentationBackground = show.presentationBackground;
this.date = _.date.toDate(); this.presentationDynamicCaption = show.presentationDynamicCaption;
this.index = _.presentationSection; this.presentationDynamicText = show.presentationDynamicText;
this.presentationBackground = _.presentationBackground; this.zoom = show.presentationZoom ?? 30;
this.presentationDynamicCaption = _.presentationDynamicCaption; }),
this.presentationDynamicText = _.presentationDynamicText; takeUntil(this.destroy$)
this.zoom = _.presentationZoom ?? 30; )
if (this.songId !== _.presentationSongId) this.songId = 'empty'; .subscribe(() => this.cRef.markForCheck());
show$
.pipe(
map(show => ({showId: show.id, presentationSongId: show.presentationSongId})),
distinctUntilChanged((a, b) => a.showId === b.showId && a.presentationSongId === b.presentationSongId),
tap(({presentationSongId}) => {
if (presentationSongId === 'title' || presentationSongId === 'dynamicText' || !presentationSongId) {
this.song = null;
}
if (this.songId !== presentationSongId) {
this.songId = 'empty';
}
setTimeout(() => { setTimeout(() => {
this.songId = _.presentationSongId; this.songId = presentationSongId;
this.cRef.markForCheck(); this.cRef.markForCheck();
}, 600); }, 600);
}), }),
switchMap((_: Show) => this.showSongService.read$(_.id, _.presentationSongId)), switchMap(({showId, presentationSongId}) => this.showSongService.read$(showId, presentationSongId)),
filter(_ => !!_), filter((song): song is ShowSong => !!song),
map(_ => _ as Song) takeUntil(this.destroy$)
) )
.subscribe(_ => { .subscribe(song => {
this.song = _; this.song = song;
this.cRef.markForCheck(); this.cRef.markForCheck();
}); });
} }
public ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
} }

View File

@@ -1,10 +1,11 @@
<div *ngIf="show" @fade> @if (show) {
<div @fade>
<app-card [closeIcon]="faIcon" [heading]="show.showType | showType" <app-card [closeIcon]="faIcon" [heading]="show.showType | showType"
[subheading]="show.date.toDate() | date:'dd.MM.yyyy'" closeLink="/presentation/select"> [subheading]="show.date.toDate() | date:'dd.MM.yyyy'" closeLink="/presentation/select">
@if (!progress) {
<ng-container *ngIf="!progress">
<div class="song"> <div class="song">
<div *ngIf="show" class="song-parts"> @if (show) {
<div class="song-parts">
<div <div
(click)="onSectionClick('title', -1, show.id)" (click)="onSectionClick('title', -1, show.id)"
[class.active]="show.presentationSongId === 'title'" [class.active]="show.presentationSongId === 'title'"
@@ -20,10 +21,12 @@
<div class="head">Leer</div> <div class="head">Leer</div>
</div> </div>
</div> </div>
}
</div> </div>
@for (song of presentationSongs; track trackBy($index, song)) {
<div *ngFor="let song of presentationSongs; trackBy: trackBy" class="song"> <div class="song">
<div *ngIf="show" @if (show) {
<div
[class.active]="show.presentationSongId === song.id" [class.active]="show.presentationSongId === song.id"
class="title song-part" class="title song-part"
> >
@@ -31,10 +34,12 @@
{{ song.title }} {{ song.title }}
</div> </div>
</div> </div>
<div *ngIf="show" class="song-parts"> }
@if (show) {
<div class="song-parts">
@for (section of song.sections; track section; let i = $index) {
<div <div
(click)="onSectionClick(song.id, i, show.id)" (click)="onSectionClick(song.id, i, show.id)"
*ngFor="let section of song.sections; index as i"
[class.active]=" [class.active]="
show.presentationSongId === song.id && show.presentationSongId === song.id &&
show.presentationSection === i show.presentationSection === i
@@ -46,11 +51,14 @@
</div> </div>
<div class="fragment">{{ getFirstLine(section) }}</div> <div class="fragment">{{ getFirstLine(section) }}</div>
</div> </div>
}
</div> </div>
}
</div> </div>
}
<div class="song"> <div class="song">
<div *ngIf="show" @if (show) {
<div
[class.active]="show.presentationSongId === 'dynamicText'" [class.active]="show.presentationSongId === 'dynamicText'"
class="title song-part" class="title song-part"
> >
@@ -58,7 +66,7 @@
Freier Text Freier Text
</div> </div>
</div> </div>
}
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Überschrift</mat-label> <mat-label>Überschrift</mat-label>
<input (ngModelChange)="onDynamicCaption($event, show.id)" [ngModel]="show.presentationDynamicCaption" <input (ngModelChange)="onDynamicCaption($event, show.id)" [ngModel]="show.presentationDynamicCaption"
@@ -66,24 +74,19 @@
matInput matInput
type="text"> type="text">
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Text</mat-label> <mat-label>Text</mat-label>
<textarea (ngModelChange)="onDynamicText($event, show.id)" [ngModel]="show.presentationDynamicText" <textarea (ngModelChange)="onDynamicText($event, show.id)" [ngModel]="show.presentationDynamicText"
autocomplete="off" id="dynamic-text" autocomplete="off" id="dynamic-text"
matInput></textarea> matInput></textarea>
</mat-form-field> </mat-form-field>
</div> </div>
@if (show) {
<div *ngIf="show" class="div-bottom"> <div class="div-bottom">
<button class="btn-start-presentation" mat-button routerLink="/presentation/monitor"> <button class="btn-start-presentation" mat-button routerLink="/presentation/monitor">
<fa-icon [icon]="faDesktop"></fa-icon> <fa-icon [icon]="faDesktop"></fa-icon>
Präsentation starten Präsentation starten
</button> </button>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Hintergrund</mat-label> <mat-label>Hintergrund</mat-label>
<mat-select <mat-select
@@ -97,7 +100,6 @@
<mat-option value="bible">Bibel</mat-option> <mat-option value="bible">Bibel</mat-option>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-slider <mat-slider
#slider #slider
[max]="100" [max]="100"
@@ -110,17 +112,17 @@
[ngModel]="show.presentationZoom" [ngModel]="show.presentationZoom"
matSliderThumb> matSliderThumb>
</mat-slider> </mat-slider>
</div> </div>
}
@if (show) {
<app-add-song <app-add-song
*ngIf="show"
[addedLive]="true" [addedLive]="true"
[showSongs]="showSongs" [showSongs]="showSongs"
[show]="show" [show]="show"
[songs]="songs$|async" [songs]="songs$|async"
></app-add-song> ></app-add-song>
</ng-container> }
}
</app-card> </app-card>
</div> </div>
}

View File

@@ -1,12 +1,13 @@
@import "../../../../styles/shadow"; @import "../../../../styles/shadow";
.song { .song {
background: #fff; background: var(--surface-strong);
width: 100%; width: 100%;
padding: 10px; padding: 10px;
border-radius: 8px; border-radius: 8px;
margin-bottom: 10px; margin-bottom: 10px;
box-sizing: border-box; box-sizing: border-box;
color: var(--text);
@media screen and (max-width: 860px) { @media screen and (max-width: 860px) {
width: 100vw; width: 100vw;
@@ -14,7 +15,7 @@
border-radius: 0; border-radius: 0;
box-sizing: border-box; box-sizing: border-box;
margin: -11px -20px 10px; margin: -11px -20px 10px;
border: 1px solid #ddd; border: 1px solid var(--surface-border);
} }
} }
@@ -39,31 +40,31 @@
} }
.song-part { .song-part {
background: #fff; background: var(--surface-strong);
border-radius: 8px; border-radius: 8px;
overflow: hidden; overflow: hidden;
transition: 300ms all ease-in-out; transition: var(--transition);
cursor: pointer; cursor: pointer;
outline: 0.5px solid #eee; outline: 1px solid var(--surface-muted);
&:hover { &:hover {
outline: 0.5px solid var(--color-primary-light); outline: 1px solid var(--primary-hover);
} }
&.active { &.active {
outline: 0.5px solid var(--color-primary); outline: 1px solid var(--primary-color);
.head { .head {
background-color: var(--color-primary); background-color: var(--primary-color);
color: white; color: var(--text-inverse);
} }
} }
} }
.head { .head {
transition: 300ms all ease-in-out; transition: var(--transition);
background: #eee; background: var(--surface-muted);
padding: 10px; padding: 10px;
font-weight: bold; font-weight: bold;
} }
@@ -100,9 +101,9 @@
a { a {
font-size: 30px; font-size: 30px;
padding: 10px; padding: 10px;
transition: all 300ms ease-in-out; transition: var(--transition);
&:hover { &:hover {
color: #4286f4; color: var(--link-color);
} }
} }

View File

@@ -1,4 +1,4 @@
import {ChangeDetectionStrategy, ChangeDetectorRef, Component} from '@angular/core'; import {ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, inject} from '@angular/core';
import {combineLatest, Subject} from 'rxjs'; import {combineLatest, Subject} from 'rxjs';
import {PresentationBackground, Show} from '../../shows/services/show'; import {PresentationBackground, Show} from '../../shows/services/show';
import {ShowSongService} from '../../shows/services/show-song.service'; import {ShowSongService} from '../../shows/services/show-song.service';
@@ -7,12 +7,12 @@ import {faDesktop, faFolderOpen} from '@fortawesome/free-solid-svg-icons';
import {ShowService} from '../../shows/services/show.service'; import {ShowService} from '../../shows/services/show.service';
import {ShowSong} from '../../shows/services/show-song'; import {ShowSong} from '../../shows/services/show-song';
import {GlobalSettingsService} from '../../../services/global-settings.service'; import {GlobalSettingsService} from '../../../services/global-settings.service';
import {debounceTime, filter, map} from 'rxjs/operators'; import {debounceTime, distinctUntilChanged, filter, map, switchMap, takeUntil} from 'rxjs/operators';
import {fade} from '../../../animations'; import {fade} from '../../../animations';
import {TextRenderingService} from '../../songs/services/text-rendering.service'; import {TextRenderingService} from '../../songs/services/text-rendering.service';
import {Section} from '../../songs/services/section'; import {Section} from '../../songs/services/section';
import {LineType} from '../../songs/services/line-type'; import {LineType} from '../../songs/services/line-type';
import {AsyncPipe, DatePipe, NgFor, NgIf} from '@angular/common'; import {AsyncPipe, DatePipe} from '@angular/common';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {MatFormField, MatLabel} from '@angular/material/form-field'; import {MatFormField, MatLabel} from '@angular/material/form-field';
import {MatInput} from '@angular/material/input'; import {MatInput} from '@angular/material/input';
@@ -40,9 +40,7 @@ export interface PresentationSong {
animations: [fade], animations: [fade],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ imports: [
NgIf,
CardComponent, CardComponent,
NgFor,
MatFormField, MatFormField,
MatLabel, MatLabel,
MatInput, MatInput,
@@ -62,7 +60,13 @@ export interface PresentationSong {
SectionTypePipe, SectionTypePipe,
], ],
}) })
export class RemoteComponent { export class RemoteComponent implements OnDestroy {
private showService = inject(ShowService);
private showSongService = inject(ShowSongService);
private songService = inject(SongService);
private textRenderingService = inject(TextRenderingService);
private cRef = inject(ChangeDetectorRef);
public show: Show | null = null; public show: Show | null = null;
public showSongs: ShowSong[] = []; public showSongs: ShowSong[] = [];
public songs$ = this.songService.list$(); public songs$ = this.songService.list$();
@@ -73,22 +77,45 @@ export class RemoteComponent {
public faDesktop = faDesktop; public faDesktop = faDesktop;
public presentationDynamicCaptionChanged$ = new Subject<{presentationDynamicCaption: string; showId: string}>(); public presentationDynamicCaptionChanged$ = new Subject<{presentationDynamicCaption: string; showId: string}>();
public presentationDynamicTextChanged$ = new Subject<{presentationDynamicText: string; showId: string}>(); public presentationDynamicTextChanged$ = new Subject<{presentationDynamicText: string; showId: string}>();
private destroy$ = new Subject<void>();
public constructor( public constructor() {
private showService: ShowService, const globalSettingsService = inject(GlobalSettingsService);
private showSongService: ShowSongService,
private songService: SongService, const currentShowId$ = globalSettingsService.get$.pipe(
private textRenderingService: TextRenderingService, filter((settings): settings is NonNullable<typeof settings> => !!settings),
globalSettingsService: GlobalSettingsService, map(_ => _.currentShow),
private cRef: ChangeDetectorRef filter((showId): showId is string => !!showId),
) { distinctUntilChanged(),
globalSettingsService.get$ takeUntil(this.destroy$)
.pipe( );
filter(_ => !!_),
map(_ => _.currentShow) const show$ = currentShowId$.pipe(
) switchMap(showId => this.showService.read$(showId)),
.subscribe(_ => { takeUntil(this.destroy$)
this.onShowChanged(_); );
const parsedSongs$ = currentShowId$.pipe(
switchMap(showId => this.showSongService.list$(showId)),
map(list => ({
list,
parsed: list.map(song => ({
id: song.id,
title: song.title,
sections: this.textRenderingService.parse(song.text, null, false),
})),
})),
takeUntil(this.destroy$)
);
combineLatest([show$, parsedSongs$])
.pipe(takeUntil(this.destroy$))
.subscribe(([show, parsedSongs]) => {
this.showSongs = parsedSongs.list;
this.show = show;
const order = show?.order ?? [];
const presentationSongsById = new Map(parsedSongs.parsed.map(song => [song.id, song] as const));
this.presentationSongs = order.map(id => presentationSongsById.get(id) ?? null).filter((s): s is PresentationSong => !!s);
this.cRef.markForCheck(); this.cRef.markForCheck();
}); });
@@ -102,20 +129,6 @@ export class RemoteComponent {
return item.id; return item.id;
} }
public onShowChanged(change: string): void {
combineLatest([this.showService.read$(change), this.showSongService.list$(change)]).subscribe(([show, list]) => {
this.showSongs = list;
this.show = show;
const presentationSongs = list.map(song => ({
id: song.id,
title: song.title,
sections: this.textRenderingService.parse(song.text, null, false),
}));
this.presentationSongs = show?.order.map(_ => presentationSongs.filter(f => f.id === _)[0]) ?? [];
this.cRef.markForCheck();
});
}
public getFirstLine(section: Section): string { public getFirstLine(section: Section): string {
return section.lines.filter(_ => _.type === LineType.text)[0].text; return section.lines.filter(_ => _.type === LineType.text)[0].text;
} }
@@ -142,4 +155,9 @@ export class RemoteComponent {
public onDynamicText(presentationDynamicText: string, showId: string): void { public onDynamicText(presentationDynamicText: string, showId: string): void {
this.presentationDynamicTextChanged$.next({presentationDynamicText, showId}); this.presentationDynamicTextChanged$.next({presentationDynamicText, showId});
} }
public ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
} }

View File

@@ -1,16 +1,25 @@
<div *ngIf="shows$ | async as shows" @fade> @if (shows$ | async; as shows) {
<app-card *ngIf="visible" heading="Bitte eine Veranstaltung auswählen"> <div @fade>
<p *ngIf="!shows.length"> @if (visible) {
<app-card heading="Bitte eine Veranstaltung auswählen">
@if (!shows.length) {
<p>
Es ist derzeit keine Veranstaltung vorhanden Es ist derzeit keine Veranstaltung vorhanden
</p> </p>
}
<div *ngIf="shows.length>0" class="list"> @if (shows.length>0) {
<button (click)="selectShow(show)" *ngFor="let show of shows" mat-stroked-button> <div class="list">
@for (show of shows; track show) {
<button (click)="selectShow(show)" mat-stroked-button>
<app-user-name [userId]="show.owner"></app-user-name> <app-user-name [userId]="show.owner"></app-user-name>
, ,
{{ show.showType | showType }}, {{ show.showType | showType }},
{{ show.date.toDate() | date: "dd.MM.yyyy" }} {{ show.date.toDate() | date: "dd.MM.yyyy" }}
</button> </button>
}
</div> </div>
}
</app-card> </app-card>
</div> }
</div>
}

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

@@ -1,11 +1,11 @@
import {Component, OnInit} from '@angular/core'; import {Component, OnInit, inject} from '@angular/core';
import {map} from 'rxjs/operators'; import {map} from 'rxjs/operators';
import {ShowService} from '../../shows/services/show.service'; import {ShowService} from '../../shows/services/show.service';
import {Show} from '../../shows/services/show'; import {Show} from '../../shows/services/show';
import {GlobalSettingsService} from '../../../services/global-settings.service'; import {GlobalSettingsService} from '../../../services/global-settings.service';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {fade} from '../../../animations'; import {fade} from '../../../animations';
import {AsyncPipe, DatePipe, NgFor, NgIf} from '@angular/common'; import {AsyncPipe, DatePipe} from '@angular/common';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {MatButton} from '@angular/material/button'; import {MatButton} from '@angular/material/button';
import {UserNameComponent} from '../../../services/user/user-name/user-name.component'; import {UserNameComponent} from '../../../services/user/user-name/user-name.component';
@@ -16,20 +16,18 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
templateUrl: './select.component.html', templateUrl: './select.component.html',
styleUrls: ['./select.component.less'], styleUrls: ['./select.component.less'],
animations: [fade], animations: [fade],
imports: [NgIf, CardComponent, NgFor, MatButton, UserNameComponent, AsyncPipe, DatePipe, ShowTypePipe], imports: [CardComponent, MatButton, UserNameComponent, AsyncPipe, DatePipe, ShowTypePipe],
}) })
export class SelectComponent implements OnInit { export class SelectComponent implements OnInit {
private showService = inject(ShowService);
private globalSettingsService = inject(GlobalSettingsService);
private router = inject(Router);
public visible = false; public visible = false;
public shows$ = this.showService public shows$ = this.showService
.list$(true) .list$(true)
.pipe(map(_ => _.filter(_ => _.date.toDate() > new Date(new Date().setMonth(new Date().getMonth() - 1))).sort((a, b) => (b.date < a.date ? -1 : b.date > a.date ? 1 : 0)))); .pipe(map(_ => _.filter(_ => _.date.toDate() > new Date(new Date().setMonth(new Date().getMonth() - 1))).sort((a, b) => (b.date < a.date ? -1 : b.date > a.date ? 1 : 0))));
public constructor(
private showService: ShowService,
private globalSettingsService: GlobalSettingsService,
private router: Router
) {}
public async selectShow(show: Show) { public async selectShow(show: Show) {
this.visible = false; this.visible = false;

View File

@@ -1,12 +1,15 @@
import {ComponentFixture, TestBed} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ShareDialogComponent} from './share-dialog.component'; import {ShareDialogComponent} from './share-dialog.component';
import QRCode from 'qrcode';
describe('ShareDialogComponent', () => { describe('ShareDialogComponent', () => {
let component: ShareDialogComponent; let component: ShareDialogComponent;
let fixture: ComponentFixture<ShareDialogComponent>; let fixture: ComponentFixture<ShareDialogComponent>;
beforeEach(async () => { beforeEach(async () => {
spyOn(QRCode, 'toDataURL').and.resolveTo('data:image/jpeg;base64,test');
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [ShareDialogComponent], imports: [ShareDialogComponent],
}).compileComponents(); }).compileComponents();

View File

@@ -1,4 +1,4 @@
import {Component, Inject} from '@angular/core'; import {Component, inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogActions, MatDialogClose, MatDialogContent} from '@angular/material/dialog'; import {MAT_DIALOG_DATA, MatDialogActions, MatDialogClose, MatDialogContent} from '@angular/material/dialog';
import {MatButton} from '@angular/material/button'; import {MatButton} from '@angular/material/button';
import QRCode from 'qrcode'; import QRCode from 'qrcode';
@@ -17,9 +17,13 @@ export interface ShareDialogData {
styleUrl: './share-dialog.component.less', styleUrl: './share-dialog.component.less',
}) })
export class ShareDialogComponent { export class ShareDialogComponent {
public data = inject<ShareDialogData>(MAT_DIALOG_DATA);
public qrCode: string; public qrCode: string;
public constructor(@Inject(MAT_DIALOG_DATA) public data: ShareDialogData) { public constructor() {
const data = this.data;
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
QRCode.toDataURL(data.url, { QRCode.toDataURL(data.url, {
type: 'image/jpeg', type: 'image/jpeg',

View File

@@ -5,16 +5,20 @@
<mat-label>Art der Veranstaltung</mat-label> <mat-label>Art der Veranstaltung</mat-label>
<mat-select formControlName="showType"> <mat-select formControlName="showType">
<mat-optgroup label="öffentlich"> <mat-optgroup label="öffentlich">
<mat-option *ngFor="let key of showTypePublic" [value]="key">{{ @for (key of showTypePublic; track key) {
<mat-option [value]="key">{{
key | showType key | showType
}} }}
</mat-option> </mat-option>
}
</mat-optgroup> </mat-optgroup>
<mat-optgroup label="privat"> <mat-optgroup label="privat">
<mat-option *ngFor="let key of showTypePrivate" [value]="key">{{ @for (key of showTypePrivate; track key) {
<mat-option [value]="key">{{
key | showType key | showType
}} }}
</mat-option> </mat-option>
}
</mat-optgroup> </mat-optgroup>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>

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

@@ -1,4 +1,4 @@
import {Component, OnInit} from '@angular/core'; import {Component, OnInit, inject} from '@angular/core';
import {ShowDataService} from '../services/show-data.service'; import {ShowDataService} from '../services/show-data.service';
import {Observable, take} from 'rxjs'; import {Observable, take} from 'rxjs';
import {Show} from '../services/show'; import {Show} from '../services/show';
@@ -7,18 +7,17 @@ import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/
import {ActivatedRoute, Router} from '@angular/router'; import {ActivatedRoute, Router} from '@angular/router';
import {faSave} from '@fortawesome/free-solid-svg-icons'; import {faSave} from '@fortawesome/free-solid-svg-icons';
import {map, switchMap} from 'rxjs/operators'; import {map, switchMap} from 'rxjs/operators';
import firebase from 'firebase/compat/app'; import {Timestamp} from '@angular/fire/firestore';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field'; import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field';
import {MatSelect} from '@angular/material/select'; import {MatSelect} from '@angular/material/select';
import {MatOptgroup, MatOption} from '@angular/material/core'; import {MatOptgroup, MatOption} from '@angular/material/core';
import {NgFor} from '@angular/common';
import {MatInput} from '@angular/material/input'; import {MatInput} from '@angular/material/input';
import {MatDatepicker, MatDatepickerInput, MatDatepickerToggle} from '@angular/material/datepicker'; import {MatDatepicker, MatDatepickerInput, MatDatepickerToggle} from '@angular/material/datepicker';
import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component'; import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../widget-modules/components/button/button.component'; import {ButtonComponent} from '../../../widget-modules/components/button/button.component';
import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import Timestamp = firebase.firestore.Timestamp;
@Component({ @Component({
selector: 'app-edit', selector: 'app-edit',
@@ -31,7 +30,6 @@ import Timestamp = firebase.firestore.Timestamp;
MatLabel, MatLabel,
MatSelect, MatSelect,
MatOptgroup, MatOptgroup,
NgFor,
MatOption, MatOption,
MatInput, MatInput,
MatDatepickerInput, MatDatepickerInput,
@@ -44,6 +42,10 @@ import Timestamp = firebase.firestore.Timestamp;
], ],
}) })
export class EditComponent implements OnInit { export class EditComponent implements OnInit {
private showService = inject(ShowService);
private router = inject(Router);
private activatedRoute = inject(ActivatedRoute);
public shows$: Observable<Show[]>; public shows$: Observable<Show[]>;
public showTypePublic = ShowService.SHOW_TYPE_PUBLIC; public showTypePublic = ShowService.SHOW_TYPE_PUBLIC;
public showTypePrivate = ShowService.SHOW_TYPE_PRIVATE; public showTypePrivate = ShowService.SHOW_TYPE_PRIVATE;
@@ -54,12 +56,9 @@ export class EditComponent implements OnInit {
}); });
public faSave = faSave; public faSave = faSave;
public constructor( public constructor() {
private showService: ShowService, const showDataService = inject(ShowDataService);
showDataService: ShowDataService,
private router: Router,
private activatedRoute: ActivatedRoute
) {
this.shows$ = showDataService.list$; this.shows$ = showDataService.list$;
} }

View File

@@ -4,42 +4,52 @@
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Zeitraum</mat-label> <mat-label>Zeitraum</mat-label>
<mat-select formControlName="time"> <mat-select formControlName="time">
<mat-option *ngFor="let time of times" [value]="time.key">{{ @for (time of times; track time) {
<mat-option [value]="time.key">{{
time.value time.value
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Ersteller</mat-label> <mat-label>Ersteller</mat-label>
<mat-select formControlName="owner"> <mat-select formControlName="owner">
<mat-option *ngFor="let owner of owners" [value]="owner.key">{{ <mat-option value="">Alle</mat-option>
@for (owner of owners; track owner) {
<mat-option [value]="owner.key">{{
owner.value owner.value
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Art der Veranstaltung</mat-label> <mat-label>Art der Veranstaltung</mat-label>
<mat-select formControlName="showType"> <mat-select formControlName="showType">
<mat-option value="">Alle</mat-option>
<mat-optgroup label="öffentlich"> <mat-optgroup label="öffentlich">
<mat-option *ngFor="let key of showTypePublic" [value]="key">{{ @for (key of showTypePublic; track key) {
<mat-option [value]="key">{{
key | showType key | showType
}} }}
</mat-option> </mat-option>
}
</mat-optgroup> </mat-optgroup>
<mat-optgroup label="privat"> <mat-optgroup label="privat">
<mat-option *ngFor="let key of showTypePrivate" [value]="key">{{ @for (key of showTypePrivate; track key) {
<mat-option [value]="key">{{
key | showType key | showType
}} }}
</mat-option> </mat-option>
}
</mat-optgroup> </mat-optgroup>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>
<i>Anzahl der Suchergebnisse: {{ shows.length }}</i> <i>Anzahl der Suchergebnisse: {{ shows?.length ?? 0 }}</i>
</div> </div>

View File

@@ -1,15 +1,14 @@
import {Component, Input} from '@angular/core'; import {Component, Input, inject} from '@angular/core';
import {KeyValue, NgFor} from '@angular/common'; import {KeyValue} from '@angular/common';
import {ActivatedRoute, Router} from '@angular/router';
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup} from '@angular/forms'; import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup} from '@angular/forms';
import {FilterValues} from './filter-values'; import {FilterValues} from './filter-values';
import {Show} from '../../services/show'; import {Show} from '../../services/show';
import {ShowService} from '../../services/show.service'; import {ShowService} from '../../services/show.service';
import {distinctUntilChanged, map} from 'rxjs/operators'; import {distinctUntilChanged, map, switchMap} from 'rxjs/operators';
import {combineLatest, Observable} from 'rxjs'; import {combineLatest, Observable, of} from 'rxjs';
import {dynamicSort, onlyUnique} from '../../../../services/filter.helper'; import {dynamicSort, onlyUnique} from '../../../../services/filter.helper';
import {UserService} from '../../../../services/user/user.service'; import {UserService} from '../../../../services/user/user.service';
import {isEqual} from 'lodash'; import {FilterStoreService} from '../../../../services/filter-store.service';
import {MatFormField, MatLabel} from '@angular/material/form-field'; import {MatFormField, MatLabel} from '@angular/material/form-field';
import {MatSelect} from '@angular/material/select'; import {MatSelect} from '@angular/material/select';
import {MatOptgroup, MatOption} from '@angular/material/core'; import {MatOptgroup, MatOption} from '@angular/material/core';
@@ -19,10 +18,13 @@ import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translate
selector: 'app-filter', selector: 'app-filter',
templateUrl: './filter.component.html', templateUrl: './filter.component.html',
styleUrls: ['./filter.component.less'], styleUrls: ['./filter.component.less'],
imports: [ReactiveFormsModule, MatFormField, MatLabel, MatSelect, NgFor, MatOption, MatOptgroup, ShowTypePipe], imports: [ReactiveFormsModule, MatFormField, MatLabel, MatSelect, MatOption, MatOptgroup, ShowTypePipe],
}) })
export class FilterComponent { export class FilterComponent {
@Input() public route = '/shows/'; private showService = inject(ShowService);
private userService = inject(UserService);
private filterStore = inject(FilterStoreService);
@Input() public shows: Show[] = []; @Input() public shows: Show[] = [];
public showTypePublic = ShowService.SHOW_TYPE_PUBLIC; public showTypePublic = ShowService.SHOW_TYPE_PUBLIC;
@@ -38,58 +40,74 @@ export class FilterComponent {
public owners: {key: string; value: string}[] = []; public owners: {key: string; value: string}[] = [];
public constructor( public constructor() {
private router: Router, const fb = inject(UntypedFormBuilder);
private showService: ShowService,
private userService: UserService,
activatedRoute: ActivatedRoute,
fb: UntypedFormBuilder
) {
this.filterFormGroup = fb.group({ this.filterFormGroup = fb.group({
time: 1, time: 1,
owner: null, owner: null,
showType: null, showType: null,
}); });
activatedRoute.queryParams.subscribe(params => { this.filterStore.showFilter$.subscribe(filterValues => {
const filterValues = params as FilterValues; this.filterFormGroup.patchValue(
if (filterValues.time) this.filterFormGroup.controls.time.setValue(+filterValues.time); {
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.time.valueChanges.subscribe(_ => this.filterValueChanged('time', (_ as number) ?? 1));
this.filterFormGroup.controls.owner.valueChanges.subscribe(_ => void this.filerValueChanged('owner', _ as string)); this.filterFormGroup.controls.owner.valueChanges.subscribe(_ => this.filterValueChanged('owner', (_ as string | null) ?? ''));
this.filterFormGroup.controls.showType.valueChanges.subscribe(_ => void this.filerValueChanged('showType', _ as string)); this.filterFormGroup.controls.showType.valueChanges.subscribe(_ => this.filterValueChanged('showType', (_ as string | null) ?? ''));
this.owners$().subscribe(owners => (this.owners = owners)); this.owners$().subscribe(owners => (this.owners = owners));
} }
public owners$ = (): Observable<{key: string; value: string}[]> => { public owners$ = (): Observable<{key: string; value: string}[]> => {
return combineLatest([ return this.showService.list$().pipe(
this.showService.list$().pipe( map(shows =>
map(shows => { shows
return shows.map(show => show.owner).filter(onlyUnique); .map(show => show.owner)
}) .filter(onlyUnique)
.filter((ownerId): ownerId is string => !!ownerId)
), ),
this.userService.users$, switchMap(ownerIds => {
]).pipe( if (ownerIds.length === 0) {
map(([owners, users]) => { return of([] as {key: string; value: string}[]);
return owners }
.map(ownerId => ({
return combineLatest(
ownerIds.map(ownerId =>
this.userService.getUserbyId$(ownerId).pipe(
map(user => ({
key: ownerId, key: ownerId,
value: users.find(user => user.id === ownerId)?.name, value: user?.name,
})) }))
.sort(dynamicSort('value')); )
)
);
}), }),
distinctUntilChanged(isEqual), map(owners => {
return owners.sort(dynamicSort('value'));
}),
distinctUntilChanged((left, right) => this.sameOwners(left, right)),
map(_ => _ as {key: string; value: string}[]) map(_ => _ as {key: string; value: string}[])
); );
}; };
private async filerValueChanged<T>(key: string, value: T): Promise<void> { private filterValueChanged<T>(key: keyof FilterValues, value: T): void {
const route = this.router.createUrlTree([this.route], { this.filterStore.updateShowFilter({[key]: value} as Partial<FilterValues>);
queryParams: {[key]: value}, }
queryParamsHandling: 'merge',
}); private sameOwners(left: {key: string; value: string}[], right: {key: string; value: string}[]): boolean {
await this.router.navigateByUrl(route); if (left.length !== right.length) {
return false;
}
return left.every((owner, index) => owner.key === right[index]?.key && owner.value === right[index]?.value);
} }
} }

View File

@@ -1,7 +1,9 @@
<div *ngIf="show" class="list-item"> @if (show) {
<div class="list-item">
<div>{{ show.date.toDate() | date: "dd.MM.yyyy" }}</div> <div>{{ show.date.toDate() | date: "dd.MM.yyyy" }}</div>
<div> <div>
<app-user-name [userId]="show.owner"></app-user-name> <app-user-name [userId]="show.owner"></app-user-name>
</div> </div>
<div>{{ show.showType | showType }}</div> <div>{{ show.showType | showType }}</div>
</div> </div>
}

View File

@@ -1,5 +1,3 @@
@import "../../../../../styles/styles";
.list-item { .list-item {
padding: 5px 20px; padding: 5px 20px;
display: grid; display: grid;
@@ -12,10 +10,11 @@
} }
cursor: pointer; cursor: pointer;
transition: var(--transition);
&:hover { &:hover {
background: @primary-color; background: var(--hover-background);
color: #fff; color: var(--text);
} }
} }

View File

@@ -1,6 +1,6 @@
import {Component, Input} from '@angular/core'; import {Component, Input} from '@angular/core';
import {Show} from '../../services/show'; import {Show} from '../../services/show';
import {DatePipe, NgIf} from '@angular/common'; import {DatePipe} from '@angular/common';
import {UserNameComponent} from '../../../../services/user/user-name/user-name.component'; import {UserNameComponent} from '../../../../services/user/user-name/user-name.component';
import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translater/show-type.pipe';
@@ -8,7 +8,7 @@ import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translate
selector: 'app-list-item', selector: 'app-list-item',
templateUrl: './list-item.component.html', templateUrl: './list-item.component.html',
styleUrls: ['./list-item.component.less'], styleUrls: ['./list-item.component.less'],
imports: [NgIf, UserNameComponent, DatePipe, ShowTypePipe], imports: [UserNameComponent, DatePipe, ShowTypePipe],
}) })
export class ListItemComponent { export class ListItemComponent {
@Input() public show: Show | null = null; @Input() public show: Show | null = null;

View File

@@ -1,36 +1,42 @@
<div> <div>
<!-- <app-list-header *appRole="['leader']"></app-list-header>--> <!-- <app-list-header *appRole="['leader']"></app-list-header>-->
<app-list-header *appRole="['leader']"> <app-list-header *appRole="['leader']">
<app-filter *ngIf="shows$ | async as shows" [shows]="publicShows$ | async"></app-filter> @if (shows$ | async; as shows) {
<app-filter [shows]="publicShows$ | async"></app-filter>
}
</app-list-header> </app-list-header>
<ng-container *appRole="['leader']"> <ng-container *appRole="['leader']">
<ng-container *ngIf="privateShows$ | async as shows"> @if (privateShows$ | async; as shows) {
@if (shows.length > 0) {
<app-card <app-card
*ngIf="shows.length > 0"
[padding]="false" [padding]="false"
heading="Meine Veranstaltungen" heading="Meine Veranstaltungen"
> >
@for (show of shows | sortBy: 'desc':'date'; track show) {
<app-list-item <app-list-item
*ngFor="let show of shows | sortBy: 'desc':'date'"
[routerLink]="show.id" [routerLink]="show.id"
[show]="show" [show]="show"
></app-list-item> ></app-list-item>
}
</app-card> </app-card>
</ng-container> }
}
</ng-container> </ng-container>
<ng-container *ngIf="publicShows$ | async as shows"> @if (publicShows$ | async; as shows) {
@if (shows.length > 0) {
<app-card <app-card
*ngIf="shows.length > 0"
[padding]="false" [padding]="false"
heading="Veröffentlichte Veranstaltungen" heading="Veröffentlichte Veranstaltungen"
> >
@for (show of shows | sortBy: 'desc':'date'; track trackBy($index, show)) {
<app-list-item <app-list-item
*ngFor="let show of shows | sortBy: 'desc':'date'; trackBy: trackBy"
[routerLink]="show.id" [routerLink]="show.id"
[show]="show" [show]="show"
></app-list-item> ></app-list-item>
}
</app-card> </app-card>
</ng-container> }
}
</div> </div>

View File

@@ -1,14 +1,15 @@
import {Component} from '@angular/core'; import {Component, inject} from '@angular/core';
import {combineLatest} from 'rxjs'; import {combineLatest} from 'rxjs';
import {Show} from '../services/show'; import {Show} from '../services/show';
import {fade} from '../../../animations'; import {fade} from '../../../animations';
import {ShowService} from '../services/show.service'; import {ShowService} from '../services/show.service';
import {FilterValues} from './filter/filter-values'; import {FilterValues} from './filter/filter-values';
import {ActivatedRoute, RouterLink} from '@angular/router'; import {RouterLink} from '@angular/router';
import {map} from 'rxjs/operators'; import {map, switchMap} from 'rxjs/operators';
import {FilterStoreService} from '../../../services/filter-store.service';
import {RoleDirective} from '../../../services/user/role.directive'; import {RoleDirective} from '../../../services/user/role.directive';
import {ListHeaderComponent} from '../../../widget-modules/components/list-header/list-header.component'; import {ListHeaderComponent} from '../../../widget-modules/components/list-header/list-header.component';
import {AsyncPipe, NgFor, NgIf} from '@angular/common'; import {AsyncPipe} from '@angular/common';
import {FilterComponent} from './filter/filter.component'; import {FilterComponent} from './filter/filter.component';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {ListItemComponent} from './list-item/list-item.component'; import {ListItemComponent} from './list-item/list-item.component';
@@ -19,41 +20,44 @@ import {SortByPipe} from '../../../widget-modules/pipes/sort-by/sort-by.pipe';
templateUrl: './list.component.html', templateUrl: './list.component.html',
styleUrls: ['./list.component.less'], styleUrls: ['./list.component.less'],
animations: [fade], animations: [fade],
imports: [RoleDirective, ListHeaderComponent, NgIf, FilterComponent, CardComponent, NgFor, ListItemComponent, RouterLink, AsyncPipe, SortByPipe], imports: [RoleDirective, ListHeaderComponent, FilterComponent, CardComponent, ListItemComponent, RouterLink, AsyncPipe, SortByPipe],
}) })
export class ListComponent { export class ListComponent {
private showService = inject(ShowService);
private filterStore = inject(FilterStoreService);
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 shows$ = this.showService.list$();
public privateShows$ = this.showService.list$().pipe(map(show => show.filter(_ => !_.published))); public privateShows$ = combineLatest([this.shows$, this.filter$]).pipe(
public lastMonths$ = this.activatedRoute.queryParams.pipe( map(([shows, filter]) => shows.filter(show => !show.published).filter(show => this.matchesPrivateFilter(show, filter)))
map(params => { );
const filterValues = params as FilterValues; public queriedPublicShows$ = this.lastMonths$.pipe(switchMap(lastMonths => this.showService.listPublicSince$(lastMonths)));
if (!filterValues?.time) return 1; public fallbackPublicShows$ = combineLatest([this.shows$, this.lastMonths$]).pipe(
return +filterValues.time; map(([shows, lastMonths]) => {
}) return shows.filter(show => show.published && !show.archived).filter(show => this.matchesTimeFilter(show, lastMonths));
);
public owner$ = this.activatedRoute.queryParams.pipe(
map(params => {
const filterValues = params as FilterValues;
return filterValues?.owner;
}) })
); );
public publicShows$ = combineLatest([this.queriedPublicShows$, this.fallbackPublicShows$, this.owner$, this.showType$]).pipe(
map(([queriedShows, fallbackShows, owner, showType]) => {
const shows = queriedShows.length > 0 || fallbackShows.length === 0 ? queriedShows : fallbackShows;
public publicShows$ = combineLatest([this.shows$, this.lastMonths$, this.owner$]).pipe( return shows.filter(show => !owner || show.owner === owner).filter(show => !showType || show.showType === showType);
map(([shows, lastMonths, owner]) =>
shows
.filter(f => {
const d = new Date();
d.setMonth(d.getMonth() - lastMonths);
return f.published && f.date.toDate() >= d;
}) })
.filter(show => !owner || show.owner === owner)
)
); );
public constructor(
private showService: ShowService,
private activatedRoute: ActivatedRoute
) {}
public trackBy = (index: number, show: unknown) => (show as Show).id; 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

@@ -5,16 +5,20 @@
<mat-label>Art der Veranstaltung</mat-label> <mat-label>Art der Veranstaltung</mat-label>
<mat-select formControlName="showType"> <mat-select formControlName="showType">
<mat-optgroup label="öffentlich"> <mat-optgroup label="öffentlich">
<mat-option *ngFor="let key of showTypePublic" [value]="key">{{ @for (key of showTypePublic; track key) {
<mat-option [value]="key">{{
key | showType key | showType
}} }}
</mat-option> </mat-option>
}
</mat-optgroup> </mat-optgroup>
<mat-optgroup label="privat"> <mat-optgroup label="privat">
<mat-option *ngFor="let key of showTypePrivate" [value]="key">{{ @for (key of showTypePrivate; track key) {
<mat-option [value]="key">{{
key | showType key | showType
}} }}
</mat-option> </mat-option>
}
</mat-optgroup> </mat-optgroup>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>

View File

@@ -1,4 +1,4 @@
import {Component, OnInit} from '@angular/core'; import {Component, OnInit, inject} from '@angular/core';
import {ShowDataService} from '../services/show-data.service'; import {ShowDataService} from '../services/show-data.service';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {Show} from '../services/show'; import {Show} from '../services/show';
@@ -10,7 +10,7 @@ import {CardComponent} from '../../../widget-modules/components/card/card.compon
import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field'; import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field';
import {MatSelect} from '@angular/material/select'; import {MatSelect} from '@angular/material/select';
import {MatOptgroup, MatOption} from '@angular/material/core'; import {MatOptgroup, MatOption} from '@angular/material/core';
import {NgFor} from '@angular/common';
import {MatInput} from '@angular/material/input'; import {MatInput} from '@angular/material/input';
import {MatDatepicker, MatDatepickerInput, MatDatepickerToggle} from '@angular/material/datepicker'; import {MatDatepicker, MatDatepickerInput, MatDatepickerToggle} from '@angular/material/datepicker';
import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component'; import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component';
@@ -28,7 +28,6 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
MatLabel, MatLabel,
MatSelect, MatSelect,
MatOptgroup, MatOptgroup,
NgFor,
MatOption, MatOption,
MatInput, MatInput,
MatDatepickerInput, MatDatepickerInput,
@@ -41,6 +40,9 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
], ],
}) })
export class NewComponent implements OnInit { export class NewComponent implements OnInit {
private showService = inject(ShowService);
private router = inject(Router);
public shows$: Observable<Show[]>; public shows$: Observable<Show[]>;
public showTypePublic = ShowService.SHOW_TYPE_PUBLIC; public showTypePublic = ShowService.SHOW_TYPE_PUBLIC;
public showTypePrivate = ShowService.SHOW_TYPE_PRIVATE; public showTypePrivate = ShowService.SHOW_TYPE_PRIVATE;
@@ -50,11 +52,9 @@ export class NewComponent implements OnInit {
}); });
public faSave = faSave; public faSave = faSave;
public constructor( public constructor() {
private showService: ShowService, const showDataService = inject(ShowDataService);
showDataService: ShowDataService,
private router: Router
) {
this.shows$ = showDataService.list$; this.shows$ = showDataService.list$;
} }

View File

@@ -1,16 +1,56 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {Packer} from 'docx';
import {DocxService} from './docx.service'; import {DocxService} from './docx.service';
describe('DocxService', () => { describe('DocxService', () => {
let service: 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(() => { beforeEach(async () => {
void TestBed.configureTestingModule({}); await TestBed.configureTestingModule({});
service = TestBed.inject(DocxService); service = TestBed.inject(DocxService);
}); });
it('should be created', () => { it('should be created', () => {
void expect(service).toBeTruthy(); 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,4 +1,4 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {Document, HeadingLevel, ISectionOptions, Packer, Paragraph} from 'docx'; import {Document, HeadingLevel, ISectionOptions, Packer, Paragraph} from 'docx';
import {ShowService} from './show.service'; import {ShowService} from './show.service';
import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe';
@@ -26,13 +26,11 @@ export interface DownloadOptions {
providedIn: 'root', providedIn: 'root',
}) })
export class DocxService { export class DocxService {
public constructor( private showService = inject(ShowService);
private showService: ShowService, private showSongService = inject(ShowSongService);
private showSongService: ShowSongService, private textRenderingService = inject(TextRenderingService);
private textRenderingService: TextRenderingService, private userService = inject(UserService);
private userService: UserService, private configService = inject(ConfigService);
private configService: ConfigService
) {}
public async create(showId: string, options: DownloadOptions = {}): Promise<void> { public async create(showId: string, options: DownloadOptions = {}): Promise<void> {
const data = await this.prepareData(showId); const data = await this.prepareData(showId);
@@ -194,7 +192,8 @@ export class DocxService {
if (!config) return null; if (!config) return null;
const showSongs = await this.showSongService.list(showId); const showSongs = await this.showSongService.list(showId);
const songsAsync = showSongs.map(showSong => { const songsLoaded = showSongs
.map(showSong => {
const sections = this.textRenderingService.parse(showSong.text, { const sections = this.textRenderingService.parse(showSong.text, {
baseKey: showSong.keyOriginal, baseKey: showSong.keyOriginal,
targetKey: showSong.key, targetKey: showSong.key,
@@ -203,8 +202,7 @@ export class DocxService {
showSong, showSong,
sections, sections,
}; };
}); })
const songsLoaded = (await Promise.all(songsAsync))
.filter(_ => !!_) .filter(_ => !!_)
.map( .map(
_ => _ =>
@@ -213,7 +211,7 @@ export class DocxService {
sections: Section[]; sections: Section[];
} }
); );
const songs = show.order.map(_ => songsLoaded.filter(f => f.showSong.id === _)[0]); const songs = show.order.map(_ => songsLoaded.find(f => f.showSong.id === _)).filter(_ => !!_);
return {songs, show, user, config}; return {songs, show, user, config};
} }

View File

@@ -1,12 +1,111 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {firstValueFrom, of, Subject} from 'rxjs';
import {take} from 'rxjs/operators';
import {DbService} from '../../../services/db.service';
import {ShowDataService} from './show-data.service'; import {ShowDataService} from './show-data.service';
describe('ShowDataService', () => { describe('ShowDataService', () => {
beforeEach(() => void TestBed.configureTestingModule({})); let service: ShowDataService;
let shows$: Subject<Array<{id: string; date: {toMillis: () => number}; archived?: boolean}>>;
let docUpdateSpy: jasmine.Spy<() => Promise<void>>;
let docSpy: jasmine.Spy;
let colAddSpy: jasmine.Spy<() => Promise<{id: string}>>;
let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
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});
colAddSpy = jasmine.createSpy('add').and.resolveTo({id: 'show-3'});
colSpy = jasmine.createSpy('col').and.returnValue({add: colAddSpy});
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['col$', 'doc$', 'doc', 'col']);
dbServiceSpy.col$.and.returnValue(shows$.asObservable());
dbServiceSpy.doc$.and.returnValue(of(null));
dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy);
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});
service = TestBed.inject(ShowDataService);
});
it('should be created', () => { it('should be created', () => {
const service: ShowDataService = TestBed.inject(ShowDataService); expect(service).toBeTruthy();
void expect(service).toBeTruthy(); });
it('should load the raw show list from the shows collection on creation', () => {
expect(dbServiceSpy.col$).toHaveBeenCalledWith('shows');
});
it('should sort the list by ascending show date', async () => {
const listPromise = firstValueFrom(service.list$.pipe(take(1)));
shows$.next([
{id: 'show-2', date: {toMillis: () => 200}},
{id: 'show-1', date: {toMillis: () => 100}},
{id: 'show-3', date: {toMillis: () => 300}},
]);
const list = await listPromise;
expect(list.map(show => show.id)).toEqual(['show-1', 'show-2', 'show-3']);
});
it('should replay the latest sorted list to late subscribers', async () => {
const initialSubscription = service.list$.subscribe();
shows$.next([
{id: 'show-2', date: {toMillis: () => 200}},
{id: 'show-1', date: {toMillis: () => 100}},
]);
const replayedList = await firstValueFrom(service.list$.pipe(take(1)));
expect(replayedList.map(show => show.id)).toEqual(['show-1', 'show-2']);
initialSubscription.unsubscribe();
});
it('should expose the raw list without sorting via listRaw$', () => {
service.listRaw$().subscribe();
expect(dbServiceSpy.col$).toHaveBeenCalledWith('shows');
});
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'}]);
dbServiceSpy.col$.and.returnValue(publicShows$ as never);
const result = await firstValueFrom(service.listPublicSince$(3));
expect(dbServiceSpy.col$).toHaveBeenCalledWith('shows', jasmine.any(Array));
const [, queryConstraints] = dbServiceSpy.col$.calls.mostRecent().args as [string, unknown[]];
expect(queryConstraints.length).toBe(3);
expect(result.map(show => show.id)).toEqual(['show-1', 'show-3']);
});
it('should read a single show by id', () => {
service.read$('show-7').subscribe();
expect(dbServiceSpy.doc$).toHaveBeenCalledWith('shows/show-7');
});
it('should update a show at the expected document path', async () => {
await service.update('show-8', {archived: true});
expect(docSpy).toHaveBeenCalledWith('shows/show-8');
const [updatePayload] = docUpdateSpy.calls.mostRecent().args as unknown as [Record<string, unknown>];
expect(updatePayload).toEqual({archived: true});
});
it('should add a show to the shows collection and return the new id', async () => {
await expectAsync(service.add({published: true})).toBeResolvedTo('show-3');
expect(colSpy).toHaveBeenCalledWith('shows');
const [addPayload] = colAddSpy.calls.mostRecent().args as unknown as [Record<string, unknown>];
expect(addPayload).toEqual({published: true});
}); });
}); });

View File

@@ -1,26 +1,50 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {DbService} from '../../../services/db.service'; import {DbService} from '../../../services/db.service';
import {Show} from './show'; import {Show} from './show';
import {map} from 'rxjs/operators'; import {map, shareReplay} from 'rxjs/operators';
import {orderBy, QueryConstraint, Timestamp, where} from 'firebase/firestore';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class ShowDataService { export class ShowDataService {
public list$ = new BehaviorSubject<Show[]>([]); private dbService = inject(DbService);
private collection = 'shows';
public constructor(private dbService: DbService) { private collection = 'shows';
this.dbService.col$<Show>(this.collection).subscribe(_ => this.list$.next(_)); public list$: Observable<Show[]> = this.dbService.col$<Show>(this.collection).pipe(
} // server-side ordering cuts client work and keeps stable order across subscribers
map(shows => [...shows].sort((a, b) => a.date.toMillis() - b.date.toMillis())),
shareReplay({
bufferSize: 1,
refCount: true,
})
);
public listRaw$ = () => this.dbService.col$<Show>(this.collection); public listRaw$ = () => this.dbService.col$<Show>(this.collection);
public read$ = (showId: string): Observable<Show | null> => this.list$.pipe(map(_ => _.find(s => s.id === showId) || null)); 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);
queryConstraints.splice(1, 0, where('date', '>=', startTimestamp));
}
return this.dbService.col$<Show>(this.collection, queryConstraints).pipe(
map(shows => shows.filter(show => !show.archived)),
shareReplay({
bufferSize: 1,
refCount: true,
})
);
}
public read$ = (showId: string): Observable<Show | null> => this.dbService.doc$(`${this.collection}/${showId}`);
// public list$ = (): Observable<Show[]> => this.dbService.col$(this.collection);
// public read$ = (showId: string): Observable<Show | null> => this.dbService.doc$(`${this.collection}/${showId}`);
public update = async (showId: string, data: Partial<Show>): Promise<void> => await this.dbService.doc(`${this.collection}/${showId}`).update(data); public update = async (showId: string, data: Partial<Show>): Promise<void> => await this.dbService.doc(`${this.collection}/${showId}`).update(data);
public add = async (data: Partial<Show>): Promise<string> => (await this.dbService.col(this.collection).add(data)).id; public add = async (data: Partial<Show>): Promise<string> => (await this.dbService.col(this.collection).add(data)).id;
} }

View File

@@ -1,16 +1,98 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {DbService} from '../../../services/db.service';
import {ShowSongDataService} from './show-song-data.service'; import {ShowSongDataService} from './show-song-data.service';
describe('ShowSongDataService', () => { describe('ShowSongDataService', () => {
let service: ShowSongDataService; let service: ShowSongDataService;
let docUpdateSpy: jasmine.Spy<() => Promise<void>>;
let docDeleteSpy: jasmine.Spy<() => Promise<void>>;
let docSpy: jasmine.Spy;
let colAddSpy: jasmine.Spy<() => Promise<{id: string}>>;
let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(async () => {
docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.returnValue({
update: docUpdateSpy,
delete: docDeleteSpy,
});
colAddSpy = jasmine.createSpy('add').and.resolveTo({id: 'show-song-3'});
colSpy = jasmine.createSpy('col').and.returnValue({add: colAddSpy});
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['col$', 'doc$', 'doc', 'col']);
dbServiceSpy.col$.and.callFake(() => of([{id: 'show-song-1'}]) as never);
dbServiceSpy.doc$.and.returnValue(of({id: 'show-song-1'}) as never);
dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy);
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});
beforeEach(() => {
void TestBed.configureTestingModule({});
service = TestBed.inject(ShowSongDataService); service = TestBed.inject(ShowSongDataService);
}); });
it('should be created', () => { it('should be created', () => {
void expect(service).toBeTruthy(); expect(service).toBeTruthy();
});
it('should cache the list observable per show id when no query constraints are passed', () => {
const first = service.list$('show-1');
const second = service.list$('show-1');
expect(first).toBe(second);
expect(dbServiceSpy.col$).toHaveBeenCalledTimes(1);
expect(dbServiceSpy.col$).toHaveBeenCalledWith('shows/show-1/songs');
});
it('should not reuse the cache when query constraints are passed', () => {
const constraints = [{}] as never[];
const first = service.list$('show-1', constraints as never);
const second = service.list$('show-1', constraints as never);
expect(first).not.toBe(second);
expect(dbServiceSpy.col$).toHaveBeenCalledTimes(2);
expect(dbServiceSpy.col$).toHaveBeenCalledWith('shows/show-1/songs', constraints as never);
});
it('should keep separate caches for different shows', () => {
service.list$('show-1');
service.list$('show-2');
expect(dbServiceSpy.col$).toHaveBeenCalledTimes(2);
expect(dbServiceSpy.col$).toHaveBeenCalledWith('shows/show-1/songs');
expect(dbServiceSpy.col$).toHaveBeenCalledWith('shows/show-2/songs');
});
it('should read a single show song by nested document path', () => {
service.read$('show-4', 'song-5').subscribe();
expect(dbServiceSpy.doc$).toHaveBeenCalledWith('shows/show-4/songs/song-5');
});
it('should update a nested show song document', async () => {
await service.update$('show-4', 'song-5', {title: 'Updated'} as never);
expect(docSpy).toHaveBeenCalledWith('shows/show-4/songs/song-5');
const [updatePayload] = docUpdateSpy.calls.mostRecent().args as unknown as [Record<string, unknown>];
expect(updatePayload).toEqual({title: 'Updated'});
});
it('should delete a nested show song document', async () => {
await service.delete('show-4', 'song-5');
expect(docSpy).toHaveBeenCalledWith('shows/show-4/songs/song-5');
expect(docDeleteSpy).toHaveBeenCalled();
});
it('should add a song to the nested show songs collection and return the id', async () => {
await expectAsync(service.add('show-4', {songId: 'song-5'} as never)).toBeResolvedTo('show-song-3');
expect(colSpy).toHaveBeenCalledWith('shows/show-4/songs');
const [addPayload] = colAddSpy.calls.mostRecent().args as unknown as [Record<string, unknown>];
expect(addPayload).toEqual({songId: 'song-5'});
}); });
}); });

View File

@@ -1,19 +1,41 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {DbService} from '../../../services/db.service'; import {DbService} from '../../../services/db.service';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {ShowSong} from './show-song'; import {ShowSong} from './show-song';
import {QueryFn} from '@angular/fire/compat/firestore/interfaces'; import {QueryConstraint} from '@angular/fire/firestore';
import {shareReplay} from 'rxjs/operators';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class ShowSongDataService { export class ShowSongDataService {
private dbService = inject(DbService);
private collection = 'shows'; private collection = 'shows';
private subCollection = 'songs'; private subCollection = 'songs';
private listCache = new Map<string, Observable<ShowSong[]>>();
public constructor(private dbService: DbService) {} public list$ = (showId: string, queryConstraints?: QueryConstraint[]): Observable<ShowSong[]> => {
if (queryConstraints && queryConstraints.length > 0) {
return this.dbService.col$(`${this.collection}/${showId}/${this.subCollection}`, queryConstraints);
}
const cached = this.listCache.get(showId);
if (cached) {
return cached;
}
const stream$ = this.dbService.col$<ShowSong>(`${this.collection}/${showId}/${this.subCollection}`).pipe(
shareReplay({
bufferSize: 1,
refCount: true,
})
);
this.listCache.set(showId, stream$);
return stream$;
};
public list$ = (showId: string, queryFn?: QueryFn): Observable<ShowSong[]> => this.dbService.col$(`${this.collection}/${showId}/${this.subCollection}`, queryFn);
public read$ = (showId: string, songId: string): Observable<ShowSong | null> => this.dbService.doc$(`${this.collection}/${showId}/${this.subCollection}/${songId}`); public read$ = (showId: string, songId: string): Observable<ShowSong | null> => this.dbService.doc$(`${this.collection}/${showId}/${this.subCollection}/${songId}`);
public update$ = async (showId: string, songId: string, data: Partial<ShowSong>): Promise<void> => public update$ = async (showId: string, songId: string, data: Partial<ShowSong>): Promise<void> =>
await this.dbService.doc(`${this.collection}/${showId}/${this.subCollection}/${songId}`).update(data); await this.dbService.doc(`${this.collection}/${showId}/${this.subCollection}/${songId}`).update(data);

View File

@@ -1,16 +1,135 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {BehaviorSubject, of} from 'rxjs';
import {SongDataService} from '../../songs/services/song-data.service';
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 {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', () => { describe('ShowSongService', () => {
let service: ShowSongService; let service: ShowSongService;
let showSongDataServiceSpy: jasmine.SpyObj<ShowSongDataService>;
let songDataServiceSpy: jasmine.SpyObj<SongDataService>;
let userServiceSpy: jasmine.SpyObj<UserService>;
let showServiceSpy: jasmine.SpyObj<ShowService>;
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(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'], {
user$: user$.asObservable(),
});
showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['read$', 'update$']);
showSongDataServiceSpy.add.and.resolveTo('show-song-2');
showSongDataServiceSpy.read$.and.returnValue(of(showSong));
showSongDataServiceSpy.list$.and.returnValue(of([showSong]));
showSongDataServiceSpy.delete.and.resolveTo();
showSongDataServiceSpy.update$.and.resolveTo();
songDataServiceSpy.read$.and.returnValue(of(song));
userServiceSpy.incSongCount.and.resolveTo();
userServiceSpy.decSongCount.and.resolveTo();
showServiceSpy.read$.and.returnValue(of(show));
showServiceSpy.update$.and.resolveTo();
await TestBed.configureTestingModule({
providers: [
{provide: ShowSongDataService, useValue: showSongDataServiceSpy},
{provide: SongDataService, useValue: songDataServiceSpy},
{provide: UserService, useValue: userServiceSpy},
{provide: ShowService, useValue: showServiceSpy},
],
});
beforeEach(() => {
void TestBed.configureTestingModule({});
service = TestBed.inject(ShowSongService); service = TestBed.inject(ShowSongService);
}); });
it('should be created', () => { it('should be created', () => {
void expect(service).toBeTruthy(); expect(service).toBeTruthy();
});
it('should create a show song from the song and current user', async () => {
await expectAsync(service.new$('show-1', 'song-1', true)).toBeResolvedTo('show-song-2');
expect(userServiceSpy.incSongCount).toHaveBeenCalledWith('song-1');
expect(showSongDataServiceSpy.add).toHaveBeenCalledWith('show-1', {
...song,
songId: 'song-1',
key: 'G',
keyOriginal: 'G',
chordMode: 'letters',
addedLive: true,
});
});
it('should return null when the song is missing', async () => {
songDataServiceSpy.read$.and.returnValue(of(null));
await expectAsync(service.new$('show-1', 'song-1')).toBeResolvedTo(null);
expect(showSongDataServiceSpy.add).not.toHaveBeenCalled();
expect(userServiceSpy.incSongCount).not.toHaveBeenCalled();
});
it('should return null when the current user is missing', async () => {
user$.next(null);
await expectAsync(service.new$('show-1', 'song-1')).toBeResolvedTo(null);
expect(showSongDataServiceSpy.add).not.toHaveBeenCalled();
expect(userServiceSpy.incSongCount).not.toHaveBeenCalled();
});
it('should delegate reads to the data service', async () => {
await expectAsync(service.read('show-1', 'show-song-1')).toBeResolvedTo(showSong);
expect(showSongDataServiceSpy.read$).toHaveBeenCalledWith('show-1', 'show-song-1');
});
it('should delegate list access to the data service', async () => {
await expectAsync(service.list('show-1')).toBeResolvedTo([showSong]);
expect(showSongDataServiceSpy.list$).toHaveBeenCalledWith('show-1');
});
it('should delete a show song, update the order and decrement song usage', async () => {
await service.delete$('show-1', 'show-song-1', 0);
expect(showSongDataServiceSpy.delete).toHaveBeenCalledWith('show-1', 'show-song-1');
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {order: ['show-song-2']});
expect(userServiceSpy.decSongCount).toHaveBeenCalledWith('song-1');
});
it('should stop delete when the show is missing', async () => {
showServiceSpy.read$.and.returnValue(of(null));
await service.delete$('show-1', 'show-song-1', 0);
expect(showSongDataServiceSpy.delete).not.toHaveBeenCalled();
expect(showServiceSpy.update$).not.toHaveBeenCalled();
expect(userServiceSpy.decSongCount).not.toHaveBeenCalled();
});
it('should stop delete when the show song is missing', async () => {
showSongDataServiceSpy.read$.and.returnValue(of(null));
await service.delete$('show-1', 'show-song-1', 0);
expect(showSongDataServiceSpy.delete).not.toHaveBeenCalled();
expect(showServiceSpy.update$).not.toHaveBeenCalled();
expect(userServiceSpy.decSongCount).not.toHaveBeenCalled();
});
it('should delegate updates to the data service', async () => {
await service.update$('show-1', 'show-song-1', {title: 'Updated'} as never);
expect(showSongDataServiceSpy.update$).toHaveBeenCalledWith('show-1', 'show-song-1', {title: 'Updated'} as never);
}); });
}); });

View File

@@ -1,4 +1,4 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {ShowSongDataService} from './show-song-data.service'; import {ShowSongDataService} from './show-song-data.service';
import {firstValueFrom, Observable} from 'rxjs'; import {firstValueFrom, Observable} from 'rxjs';
import {ShowSong} from './show-song'; import {ShowSong} from './show-song';
@@ -10,12 +10,10 @@ import {ShowService} from './show.service';
providedIn: 'root', providedIn: 'root',
}) })
export class ShowSongService { export class ShowSongService {
public constructor( private showSongDataService = inject(ShowSongDataService);
private showSongDataService: ShowSongDataService, private songDataService = inject(SongDataService);
private songDataService: SongDataService, private userService = inject(UserService);
private userService: UserService, private showService = inject(ShowService);
private showService: ShowService
) {}
public async new$(showId: string, songId: string, addedLive = false): Promise<string | null> { public async new$(showId: string, songId: string, addedLive = false): Promise<string | null> {
const song = await firstValueFrom(this.songDataService.read$(songId)); const song = await firstValueFrom(this.songDataService.read$(songId));
@@ -40,14 +38,14 @@ export class ShowSongService {
public list = (showId: string): Promise<ShowSong[]> => firstValueFrom(this.list$(showId)); public list = (showId: string): Promise<ShowSong[]> => firstValueFrom(this.list$(showId));
public async delete$(showId: string, showSongId: string, index: number): Promise<void> { public async delete$(showId: string, showSongId: string, index: number): Promise<void> {
const showSong = await this.read(showId, showSongId); const [showSong, show] = await Promise.all([this.read(showId, showSongId), firstValueFrom(this.showService.read$(showId))]);
await this.showSongDataService.delete(showId, showSongId);
const show = await firstValueFrom(this.showService.read$(showId));
if (!show) return; if (!show) return;
const order = show.order; if (!showSong) return;
const order = [...show.order];
order.splice(index, 1); order.splice(index, 1);
await this.showService.update$(showId, {order});
await this.userService.decSongCount(showSong.songId); await Promise.all([this.showSongDataService.delete(showId, showSongId), this.showService.update$(showId, {order}), this.userService.decSongCount(showSong.songId)]);
} }
public update$ = async (showId: string, songId: string, data: Partial<ShowSong>): Promise<void> => await this.showSongDataService.update$(showId, songId, data); public update$ = async (showId: string, songId: string, data: Partial<ShowSong>): Promise<void> => await this.showSongDataService.update$(showId, songId, data);

View File

@@ -1,27 +1,102 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {BehaviorSubject, of} from 'rxjs';
import {ShowService} from './show.service';
import {ShowDataService} from './show-data.service'; import {ShowDataService} from './show-data.service';
import {ShowService} from './show.service';
import {UserService} from '../../../services/user/user.service';
describe('ShowService', () => { describe('ShowService', () => {
const mockShowDataService = {add: Promise.resolve(null)}; let service: ShowService;
beforeEach( let showDataServiceSpy: jasmine.SpyObj<ShowDataService>;
() => let user$: BehaviorSubject<unknown>;
void TestBed.configureTestingModule({ const shows = [
providers: [{provide: ShowDataService, useValue: mockShowDataService}], {id: 'show-1', owner: 'user-1', published: false, archived: false},
}) {id: 'show-2', owner: 'other-user', published: true, archived: false},
); {id: 'show-3', owner: 'user-1', published: true, archived: true},
] as never;
beforeEach(async () => {
user$ = new BehaviorSubject<unknown>({id: 'user-1'});
showDataServiceSpy = jasmine.createSpyObj<ShowDataService>('ShowDataService', ['read$', 'listPublicSince$', 'update', 'add'], {
list$: of(shows),
});
showDataServiceSpy.read$.and.returnValue(of(shows[0]));
showDataServiceSpy.listPublicSince$.and.returnValue(of([shows[1]]));
showDataServiceSpy.update.and.resolveTo();
showDataServiceSpy.add.and.resolveTo('new-show-id');
await TestBed.configureTestingModule({
providers: [
{provide: ShowDataService, useValue: showDataServiceSpy},
{provide: UserService, useValue: {user$: user$.asObservable()}},
],
});
service = TestBed.inject(ShowService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should list published shows and own drafts, but exclude archived ones', done => {
service.list$().subscribe(result => {
expect(result.map(show => show.id)).toEqual(['show-1', 'show-2']);
done();
});
});
it('should filter out private drafts when publishedOnly is true', done => {
service.list$(true).subscribe(result => {
expect(result.map(show => show.id)).toEqual(['show-2']);
done();
});
});
it('should delegate public listing to the data service', done => {
service.listPublicSince$(6).subscribe(result => {
expect(result).toEqual([shows[1]]);
expect(showDataServiceSpy.listPublicSince$).toHaveBeenCalledWith(6);
done();
});
});
it('should delegate reads to the data service', done => {
service.read$('show-1').subscribe(result => {
expect(result).toEqual(shows[0]);
expect(showDataServiceSpy.read$).toHaveBeenCalledWith('show-1');
done();
});
});
it('should delegate updates to the data service', async () => {
await service.update$('show-1', {published: true});
expect(showDataServiceSpy.update).toHaveBeenCalledWith('show-1', {published: true});
});
it('should return null when creating a show without showType', async () => {
await expectAsync(service.new$({published: true})).toBeResolvedTo(null);
expect(showDataServiceSpy.add).not.toHaveBeenCalled();
});
it('should return null when no user is available for show creation', async () => {
user$.next(null);
await expectAsync(service.new$({showType: 'misc-public'})).toBeResolvedTo(null);
expect(showDataServiceSpy.add).not.toHaveBeenCalled();
});
ShowService.SHOW_TYPE_PUBLIC.forEach(type => { ShowService.SHOW_TYPE_PUBLIC.forEach(type => {
it('should calc public flag for ' + type, async () => { it('should calc public flag for ' + type, async () => {
const service: ShowService = TestBed.inject(ShowService);
const addSpy = spyOn(TestBed.inject(ShowDataService), 'add').and.returnValue(Promise.resolve('id'));
const id = await service.new$({showType: type}); const id = await service.new$({showType: type});
void expect(id).toBe('id'); expect(id).toBe('new-show-id');
void expect(addSpy).toHaveBeenCalledWith({ expect(showDataServiceSpy.add).toHaveBeenCalledWith({
showType: type, showType: type,
owner: 'user-1',
order: [],
public: true, public: true,
}); });
}); });
@@ -29,14 +104,13 @@ describe('ShowService', () => {
ShowService.SHOW_TYPE_PRIVATE.forEach(type => { ShowService.SHOW_TYPE_PRIVATE.forEach(type => {
it('should calc private flag for ' + type, async () => { it('should calc private flag for ' + type, async () => {
const service: ShowService = TestBed.inject(ShowService);
const addSpy = spyOn(TestBed.inject(ShowDataService), 'add').and.returnValue(Promise.resolve('id'));
const id = await service.new$({showType: type}); const id = await service.new$({showType: type});
void expect(id).toBe('id'); expect(id).toBe('new-show-id');
void expect(addSpy).toHaveBeenCalledWith({ expect(showDataServiceSpy.add).toHaveBeenCalledWith({
showType: type, showType: type,
owner: 'user-1',
order: [],
public: false, public: false,
}); });
}); });

View File

@@ -1,7 +1,7 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {ShowDataService} from './show-data.service'; import {ShowDataService} from './show-data.service';
import {Show} from './show'; import {Show} from './show';
import {Observable} from 'rxjs'; import {firstValueFrom, Observable} from 'rxjs';
import {UserService} from '../../../services/user/user.service'; import {UserService} from '../../../services/user/user.service';
import {map, switchMap} from 'rxjs/operators'; import {map, switchMap} from 'rxjs/operators';
import {User} from '../../../services/user/user'; import {User} from '../../../services/user/user';
@@ -10,19 +10,15 @@ import {User} from '../../../services/user/user';
providedIn: 'root', providedIn: 'root',
}) })
export class ShowService { export class ShowService {
private showDataService = inject(ShowDataService);
private userService = inject(UserService);
public static SHOW_TYPE = ['service-worship', 'service-praise', 'home-group-big', 'home-group', 'prayer-group', 'teens-group', 'kids-group', 'misc-public', 'misc-private']; public static SHOW_TYPE = ['service-worship', 'service-praise', 'home-group-big', 'home-group', 'prayer-group', 'teens-group', 'kids-group', 'misc-public', 'misc-private'];
public static SHOW_TYPE_PUBLIC = ['service-worship', 'service-praise', 'home-group-big', 'teens-group', 'kids-group', 'misc-public']; public static SHOW_TYPE_PUBLIC = ['service-worship', 'service-praise', 'home-group-big', 'teens-group', 'kids-group', 'misc-public'];
public static SHOW_TYPE_PRIVATE = ['home-group', 'prayer-group', 'misc-private']; public static SHOW_TYPE_PRIVATE = ['home-group', 'prayer-group', 'misc-private'];
private user: User | null = null;
public constructor(
private showDataService: ShowDataService,
private userService: UserService
) {
userService.user$.subscribe(_ => (this.user = _));
}
public read$ = (showId: string): Observable<Show | null> => this.showDataService.read$(showId); public read$ = (showId: string): Observable<Show | null> => this.showDataService.read$(showId);
public listPublicSince$ = (lastMonths: number): Observable<Show[]> => this.showDataService.listPublicSince$(lastMonths);
public list$(publishedOnly = false): Observable<Show[]> { public list$(publishedOnly = false): Observable<Show[]> {
return this.userService.user$.pipe( return this.userService.user$.pipe(
@@ -30,22 +26,18 @@ export class ShowService {
() => this.showDataService.list$, () => this.showDataService.list$,
(user: User | null, shows: Show[]) => ({user, shows}) (user: User | null, shows: Show[]) => ({user, shows})
), ),
map(s => map(s => s.shows.filter(show => !show.archived).filter(show => show.published || (show.owner === s.user?.id && !publishedOnly)))
s.shows
.sort((a, b) => a.date.toMillis() - b.date.toMillis())
.filter(_ => !_.archived)
.filter(show => show.published || (show.owner === s.user?.id && !publishedOnly))
)
); );
} }
public update$ = async (showId: string, data: Partial<Show>): Promise<void> => this.showDataService.update(showId, data); public update$ = async (showId: string, data: Partial<Show>): Promise<void> => this.showDataService.update(showId, data);
public async new$(data: Partial<Show>): Promise<string | null> { public async new$(data: Partial<Show>): Promise<string | null> {
if (!data.showType || !this.user) return null; const user = await firstValueFrom(this.userService.user$);
if (!data.showType || !user) return null;
const calculatedData: Partial<Show> = { const calculatedData: Partial<Show> = {
...data, ...data,
owner: this.user.id, owner: user.id,
order: [], order: [],
public: ShowService.SHOW_TYPE_PUBLIC.indexOf(data.showType) !== -1, public: ShowService.SHOW_TYPE_PUBLIC.indexOf(data.showType) !== -1,
}; };

View File

@@ -1,5 +1,4 @@
import firebase from 'firebase/compat/app'; import {Timestamp} from '@angular/fire/firestore';
import Timestamp = firebase.firestore.Timestamp;
export type PresentationBackground = 'none' | 'blue' | 'green' | 'leder' | 'praise' | 'bible'; export type PresentationBackground = 'none' | 'blue' | 'green' | 'leder' | 'praise' | 'bible';

View File

@@ -1,4 +1,5 @@
<div *ngIf="show$ | async as show"> @if (show$ | async; as show) {
<div>
<app-card <app-card
[fullscreen]="useSwiper" [fullscreen]="useSwiper"
closeLink="../" closeLink="../"
@@ -6,12 +7,16 @@
show.date.toDate() | date: 'dd.MM.yyyy' show.date.toDate() | date: 'dd.MM.yyyy'
}} - {{ getStatus(show) }}" }} - {{ getStatus(show) }}"
> >
<p *ngIf="!useSwiper">{{ show.public ? 'öffentliche' : 'geschlossene' }} Veranstaltung von @if (!useSwiper) {
<p>{{ show.public ? 'öffentliche' : 'geschlossene' }} Veranstaltung von
<app-user-name [userId]="show.owner"></app-user-name> <app-user-name [userId]="show.owner"></app-user-name>
</p> </p>
}
<div class="head"> <div class="head">
<div> <div>
<mat-checkbox *ngIf="!useSwiper" [(ngModel)]="showText">Text anzeigen</mat-checkbox> @if (!useSwiper) {
<mat-checkbox [(ngModel)]="showText">Text anzeigen</mat-checkbox>
}
</div> </div>
<div [class.floating]="useSwiper"> <div [class.floating]="useSwiper">
<app-menu-button (click)="onZoomOut()" @fade [icon]="faZoomOut" class="btn-delete btn-icon" <app-menu-button (click)="onZoomOut()" @fade [icon]="faZoomOut" class="btn-delete btn-icon"
@@ -19,18 +24,21 @@
<app-menu-button (click)="onZoomIn()" @fade [icon]="faZoomIn" class="btn-delete btn-icon" <app-menu-button (click)="onZoomIn()" @fade [icon]="faZoomIn" class="btn-delete btn-icon"
matTooltip="Vergrößern"></app-menu-button> matTooltip="Vergrößern"></app-menu-button>
<app-menu-button (click)="useSwiper=!useSwiper;fullscreen(useSwiper)" @fade <app-menu-button (click)="useSwiper=!useSwiper;fullscreen(useSwiper)" @fade
[icon]="useSwiper ? faFileLines : faFile" class="btn-delete btn-icon" [icon]="useSwiper ? faRestore : faMaximize" class="btn-delete btn-icon"
matTooltip="Swiper umschalten"></app-menu-button> matTooltip="Vollbild"></app-menu-button>
</div> </div>
</div> </div>
<div (cdkDropListDropped)="drop($event, show)" *ngIf="showSongs && !useSwiper" @if (showSongs && !useSwiper) {
<div (cdkDropListDropped)="drop($event, show)"
[cdkDropListDisabled]="show.published || showText" [cdkDropListDisabled]="show.published || showText"
[style.cursor]="!(show.published || showText) ? 'drag' : 'inherit'" [style.--song-key-column-width]="getSongKeyColumnWidth(show)"
[style.font-size]="textSize + 'em'" [style.font-size]="textSize + 'em'"
cdkDropList cdkDropList
class="song-list"> class="song-list">
<div *ngFor="let song of orderedShowSongs(show); let i = index; trackBy: trackBy" cdkDrag class="song-row"> @for (song of orderedShowSongs(show); track trackBy(i, song); let i = $index) {
<div cdkDrag class="song-row">
<app-song <app-song
[dragHandle]="!(show.published || showText)"
[fullscreen]="useSwiper" [fullscreen]="useSwiper"
[index]="i" [index]="i"
[showId]="showId" [showId]="showId"
@@ -39,10 +47,13 @@
[show]="show" [show]="show"
></app-song> ></app-song>
</div> </div>
}
</div> </div>
}
<swiper-container *ngIf="useSwiper" scrollbar="true"> @if (useSwiper) {
<swiper-slide *ngFor="let song of orderedShowSongs(show); let i = index; trackBy: trackBy" <swiper-container scrollbar="true">
@for (song of orderedShowSongs(show); track trackBy(i, song); let i = $index) {
<swiper-slide
[style.font-size]="textSize + 'em'" [style.font-size]="textSize + 'em'"
class="song-swipe"> class="song-swipe">
<app-song <app-song
@@ -53,43 +64,61 @@
[showText]="true" [showText]="true"
[show]="show" [show]="show"
></app-song> ></app-song>
<div *ngIf="getNextSong(orderedShowSongs(show), i) as next" class="next-song">{{ next }} <div class="time">{{ currentTime | date: 'HH:mm' }}</div>
@if (getNextSong(orderedShowSongs(show), i); as next) {
<div class="next-song">{{ next }}
<fa-icon [icon]="faNextSong"></fa-icon> <fa-icon [icon]="faNextSong"></fa-icon>
</div> </div>
}
</swiper-slide> </swiper-slide>
}
</swiper-container> </swiper-container>
}
@if (songs$ | async; as songs) {
@if (songs && !show.published && !useSwiper) {
<app-add-song <app-add-song
*ngIf="songs && !show.published && !useSwiper"
[showSongs]="showSongs" [showSongs]="showSongs"
[show]="show" [show]="show"
[songs]="songs" [songs]="songs"
></app-add-song> ></app-add-song>
}
<app-button-row *ngIf="!useSwiper"> }
@if (!useSwiper) {
<app-button-row>
<ng-container *appRole="['leader']"> <ng-container *appRole="['leader']">
<ng-container *appOwner="show.owner"> <ng-container *appOwner="show.owner">
<app-button (click)="onArchive(true)" *ngIf="!show.archived" [icon]="faBox"> @if (!show.archived) {
<app-button (click)="onArchive(true)" [icon]="faBox">
Archivieren Archivieren
</app-button> </app-button>
<app-button (click)="onArchive(false)" *ngIf="show.archived" [icon]="faBoxOpen"> }
@if (show.archived) {
<app-button (click)="onArchive(false)" [icon]="faBoxOpen">
Wiederherstellen Wiederherstellen
</app-button> </app-button>
<app-button (click)="onPublish(true)" *ngIf="!show.published" [icon]="faPublish"> }
@if (!show.published) {
<app-button (click)="onPublish(true)" [icon]="faPublish">
Veröffentlichen Veröffentlichen
</app-button> </app-button>
<app-button (click)="onPublish(false)" *ngIf="show.published" [icon]="faUnpublish"> }
@if (show.published) {
<app-button (click)="onPublish(false)" [icon]="faUnpublish">
Veröffentlichung zurückziehen Veröffentlichung zurückziehen
</app-button> </app-button>
<app-button (click)="onShare(show)" *ngIf="show.published" [icon]="faShare"> }
@if (show.published) {
<app-button (click)="onShare(show)" [icon]="faShare">
Teilen Teilen
</app-button> </app-button>
<app-button (click)="onChange(show.id)" *ngIf="!show.published" [icon]="faSliders"> }
@if (!show.published) {
<app-button (click)="onChange(show.id)" [icon]="faSliders">
Ändern Ändern
</app-button> </app-button>
}
</ng-container> </ng-container>
</ng-container> </ng-container>
<app-button [icon]="faDownload" [matMenuTriggerFor]="menu"> <app-button [icon]="faDownload" [matMenuTriggerFor]="menu">
Herunterladen Herunterladen
</app-button> </app-button>
@@ -102,5 +131,7 @@
</app-button> </app-button>
</mat-menu> </mat-menu>
</app-button-row> </app-button-row>
}
</app-card> </app-card>
</div> </div>
}

View File

@@ -5,7 +5,7 @@
.song-row:not(:last-child) { .song-row:not(:last-child) {
display: block; display: block;
border-bottom: 1px solid #0002; border-bottom: 1px solid var(--divider);
} }
.song-swipe { .song-swipe {
@@ -21,9 +21,10 @@
} }
.cdk-drag-preview { .cdk-drag-preview {
background-color: white; background-color: var(--surface-strong);
box-sizing: border-box; box-sizing: border-box;
border-radius: 4px; border-radius: 4px;
border: 1px solid var(--surface-border);
box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12);
} }
@@ -51,7 +52,7 @@
} }
.next-song { .next-song {
color: #0008; color: var(--text-muted);
position: fixed; position: fixed;
bottom: 0; bottom: 0;
right: 10px; right: 10px;
@@ -60,3 +61,10 @@
padding: 6px; padding: 6px;
} }
} }
.time {
color: var(--text-muted);
position: fixed;
bottom: 0;
left: 10px;
}

View File

@@ -1,8 +1,8 @@
import {ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, HostListener, OnDestroy, OnInit} from '@angular/core'; import {ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, HostListener, OnDestroy, OnInit, inject} from '@angular/core';
import {filter, map, switchMap, tap} from 'rxjs/operators'; import {filter, map, shareReplay, switchMap, tap} from 'rxjs/operators';
import {ActivatedRoute, Router} from '@angular/router'; import {ActivatedRoute, Router} from '@angular/router';
import {ShowService} from '../services/show.service'; import {ShowService} from '../services/show.service';
import {Observable, Subscription} from 'rxjs'; import {Observable, of, Subscription} from 'rxjs';
import {Show} from '../services/show'; import {Show} from '../services/show';
import {SongService} from '../../songs/services/song.service'; import {SongService} from '../../songs/services/song.service';
import {Song} from '../../songs/services/song'; import {Song} from '../../songs/services/song';
@@ -14,12 +14,12 @@ import {
faBox, faBox,
faBoxOpen, faBoxOpen,
faChevronRight, faChevronRight,
faFile,
faFileDownload, faFileDownload,
faFileLines,
faLock, faLock,
faMagnifyingGlassMinus, faMagnifyingGlassMinus,
faMagnifyingGlassPlus, faMagnifyingGlassPlus,
faMaximize,
faMinimize,
faSliders, faSliders,
faUnlock, faUnlock,
faUser, faUser,
@@ -32,7 +32,7 @@ import {ArchiveDialogComponent} from '../dialog/archive-dialog/archive-dialog.co
import {closeFullscreen, openFullscreen} from '../../../services/fullscreen'; import {closeFullscreen, openFullscreen} from '../../../services/fullscreen';
import {GuestShowService} from '../../guest/guest-show.service'; import {GuestShowService} from '../../guest/guest-show.service';
import {ShareDialogComponent} from '../dialog/share-dialog/share-dialog.component'; import {ShareDialogComponent} from '../dialog/share-dialog/share-dialog.component';
import {AsyncPipe, DatePipe, NgFor, NgIf} from '@angular/common'; import {AsyncPipe, DatePipe} from '@angular/common';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {UserNameComponent} from '../../../services/user/user-name/user-name.component'; import {UserNameComponent} from '../../../services/user/user-name/user-name.component';
import {MatCheckbox} from '@angular/material/checkbox'; import {MatCheckbox} from '@angular/material/checkbox';
@@ -56,7 +56,6 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
animations: [fade], animations: [fade],
schemas: [CUSTOM_ELEMENTS_SCHEMA], schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [ imports: [
NgIf,
CardComponent, CardComponent,
UserNameComponent, UserNameComponent,
MatCheckbox, MatCheckbox,
@@ -65,7 +64,6 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
MenuButtonComponent, MenuButtonComponent,
MatTooltip, MatTooltip,
CdkDropList, CdkDropList,
NgFor,
CdkDrag, CdkDrag,
SongComponent, SongComponent,
FaIconComponent, FaIconComponent,
@@ -82,8 +80,18 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
], ],
}) })
export class ShowComponent implements OnInit, OnDestroy { export class ShowComponent implements OnInit, OnDestroy {
private activatedRoute = inject(ActivatedRoute);
private showService = inject(ShowService);
private songService = inject(SongService);
private showSongService = inject(ShowSongService);
private docxService = inject(DocxService);
private router = inject(Router);
private cRef = inject(ChangeDetectorRef);
public dialog = inject(MatDialog);
private guestShowService = inject(GuestShowService);
public show$: Observable<Show | null> | null = null; public show$: Observable<Show | null> | null = null;
public songs: Song[] | null = null; public songs$: Observable<Song[] | null> | null = null;
public showSongs: ShowSong[] | null = null; public showSongs: ShowSong[] | null = null;
public showId: string | null = null; public showId: string | null = null;
public showText = false; public showText = false;
@@ -101,29 +109,26 @@ export class ShowComponent implements OnInit, OnDestroy {
public faZoomOut = faMagnifyingGlassMinus; public faZoomOut = faMagnifyingGlassMinus;
public useSwiper = false; public useSwiper = false;
public textSize = 1; public textSize = 1;
public faFileLines = faFileLines; public faRestore = faMinimize;
public faFile = faFile; public faMaximize = faMaximize;
public faNextSong = faChevronRight; public faNextSong = faChevronRight;
public currentTime: Date;
private subs: Subscription[] = []; private subs: Subscription[] = [];
public constructor(
private activatedRoute: ActivatedRoute,
private showService: ShowService,
private songService: SongService,
private showSongService: ShowSongService,
private docxService: DocxService,
private router: Router,
private cRef: ChangeDetectorRef,
public dialog: MatDialog,
private guestShowService: GuestShowService
) {}
public ngOnInit(): void { public ngOnInit(): void {
this.currentTime = new Date();
setInterval(() => {
this.currentTime = new Date();
}, 10000);
this.show$ = this.activatedRoute.params.pipe( this.show$ = this.activatedRoute.params.pipe(
map(param => param as {showId: string}), map(param => param as {showId: string}),
map(param => param.showId), map(param => param.showId),
tap((_: string) => (this.showId = _)), tap((_: string) => (this.showId = _)),
switchMap((showId: string) => this.showService.read$(showId)) switchMap((showId: string) => this.showService.read$(showId)),
shareReplay({
bufferSize: 1,
refCount: true,
})
); );
this.subs.push( this.subs.push(
this.activatedRoute.params this.activatedRoute.params
@@ -136,13 +141,14 @@ export class ShowComponent implements OnInit, OnDestroy {
.subscribe(_ => { .subscribe(_ => {
this.showSongs = _; this.showSongs = _;
this.cRef.markForCheck(); this.cRef.markForCheck();
}), })
this.songService );
.list$()
.pipe(filter(_ => !!_)) this.songs$ = this.show$.pipe(
.subscribe(_ => { switchMap(show => (show && !show.published ? this.songService.list$() : of(null))),
this.songs = _; shareReplay({
this.cRef.markForCheck(); bufferSize: 1,
refCount: true,
}) })
); );
} }
@@ -212,7 +218,8 @@ export class ShowComponent implements OnInit, OnDestroy {
public orderedShowSongs(show: Show): ShowSong[] { public orderedShowSongs(show: Show): ShowSong[] {
const list = this.showSongs; const list = this.showSongs;
if (!list) return []; if (!list) return [];
return show.order.map(_ => list.filter(f => f.id === _)[0]); const byId = new Map(list.map(item => [item.id, item] as const));
return show.order.map(id => byId.get(id)).filter((song): song is ShowSong => !!song);
} }
public trackBy = (_: number, show: ShowSong) => show?.id; public trackBy = (_: number, show: ShowSong) => show?.id;
@@ -223,6 +230,7 @@ export class ShowComponent implements OnInit, OnDestroy {
@HostListener('document:keydown', ['$event']) @HostListener('document:keydown', ['$event'])
public handleKeyboardEvent(event: KeyboardEvent) { public handleKeyboardEvent(event: KeyboardEvent) {
if (!this.useSwiper) return;
const swiperEl = document.querySelector('swiper-container') as unknown as Swiper; const swiperEl = document.querySelector('swiper-container') as unknown as Swiper;
switch (event.code) { switch (event.code) {
case 'ArrowRight': case 'ArrowRight':
@@ -237,6 +245,7 @@ export class ShowComponent implements OnInit, OnDestroy {
} }
public fullscreen(useSwiper: boolean) { public fullscreen(useSwiper: boolean) {
this.textSize = useSwiper ? 2 : 1;
if (useSwiper) openFullscreen(); if (useSwiper) openFullscreen();
else closeFullscreen(); else closeFullscreen();
} }
@@ -246,6 +255,20 @@ export class ShowComponent implements OnInit, OnDestroy {
const song = showSongs[i + 1]; const song = showSongs[i + 1];
return song?.title ?? ''; 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 { export interface Swiper {

View File

@@ -1,27 +1,87 @@
<div *ngIf="iSong && iSong && show"> @if (iSong && iSong && show) {
<div *ngIf="show.published || fullscreen" class="title published"> <div>
@if (show.published || fullscreen) {
<div class="title published">
<div class="key">{{ iSong.key }}</div> <div class="key">{{ iSong.key }}</div>
<div>{{ iSong.title }}</div> <div>{{ iSong.title }}</div>
</div> </div>
}
<div *ngIf="!show.published && !fullscreen" class="song"> @if (!show.published && !fullscreen) {
<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> <span class="title">{{ iSong.title }}</span>
<span *ngIf="!edit" class="keys"> @if (!edit) {
<span *ngIf="iSong.keyOriginal !== iSong.key">{{ iSong.keyOriginal }}&nbsp;&nbsp;</span><span <div class="keys-container">
(click)="openKeySelect()">{{ iSong.key }}</span> <div (click)="openKeySelect()" class="keys">
<mat-form-field (click)="option.open()" *ngIf="keys" class="transpose"> @if (iSong.keyOriginal !== iSong.key) {
<mat-select #option [formControl]="keyFormControl"> <span>{{ iSong.keyOriginal }}&nbsp;&nbsp;</span>
<mat-option *ngFor="let key of keys" [value]="key">{{ key }}</mat-option> }
<span>{{ iSong.key }}</span>
</div>
</div>
}
@if (!edit) {
<app-menu-button (click)="onEdit()" [icon]="faEdit" class="btn-edit btn-icon"
matTooltip="Lied für diese Veranstaltung bearbeiten"></app-menu-button>
}
@if (!edit) {
<app-menu-button (click)="onDelete()" [icon]="faDelete" class="btn-delete btn-icon"
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-select>
</mat-form-field> </mat-form-field>
</span> </span>
<app-menu-button (click)="onEdit()" *ngIf="!edit" [icon]="faEdit" class="btn-edit btn-icon" <span class="title"></span>
matTooltip="Lied für diese Veranstaltung bearbeiten"></app-menu-button> } @else {
<app-menu-button (click)="onDelete()" *ngIf="!edit" [icon]="faDelete" class="btn-delete btn-icon" <span class="title"></span>
matTooltip="Lied aus Veranstaltung entfernen"></app-menu-button> <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> </div>
}
<mat-form-field *ngIf="edit" appearance="outline"> }
@if (edit) {
<mat-form-field appearance="outline">
<mat-label>Songtext</mat-label> <mat-label>Songtext</mat-label>
<textarea [cdkTextareaAutosize]="true" <textarea [cdkTextareaAutosize]="true"
[formControl]="editSongControl" [formControl]="editSongControl"
@@ -30,18 +90,24 @@
matTooltip="Tonart ändern" matTooltip="Tonart ändern"
></textarea> ></textarea>
</mat-form-field> </mat-form-field>
<div *ngIf="edit">Es wird nur der Liedtext für dieser Veranstaltung geändert.</div> }
<app-button-row *ngIf="edit"> @if (edit) {
<div>Es wird nur der Liedtext für dieser Veranstaltung geändert.</div>
}
@if (edit) {
<app-button-row>
<app-button (click)="onSave()" [icon]="faSave">Speichern</app-button> <app-button (click)="onSave()" [icon]="faSave">Speichern</app-button>
<app-button (click)="onDiscard()" [icon]="faEraser">Verwerfen</app-button> <app-button (click)="onDiscard()" [icon]="faEraser">Verwerfen</app-button>
</app-button-row> </app-button-row>
}
@if (!edit && (showText)) {
<app-song-text <app-song-text
(chordModeChanged)="onChordModeChanged($event)" (chordModeChanged)="onChordModeChanged($event)"
*ngIf="!edit && (showText )"
[chordMode]="iSong.chordMode" [chordMode]="iSong.chordMode"
[showSwitch]="!show.published" [showSwitch]="!show.published"
[text]="iSong.text" [text]="iSong.text"
[transpose]="{ baseKey: iSong.keyOriginal, targetKey: iSong.key }" [transpose]="{ baseKey: iSong.keyOriginal, targetKey: iSong.key }"
></app-song-text> ></app-song-text>
</div> }
</div>
}

View File

@@ -1,12 +1,10 @@
.song { .song {
&:not(.select) {
min-height: 28px; 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; display: flex;
@@ -14,12 +12,109 @@
} }
overflow: hidden; 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 { .keys {
display: flex;
align-items: center;
position: relative; position: relative;
margin-right: 10px; margin-right: 10px;
cursor: pointer; cursor: pointer;
flex-grow: 0;
height: 100%;
&:hover { &:hover {
color: var(--color-primary); color: var(--color-primary);
@@ -41,6 +136,7 @@
.title { .title {
grid-area: title; grid-area: title;
min-width: 0;
&.published { &.published {
margin: 10px 0; margin: 10px 0;
@@ -49,8 +145,8 @@
grid-template-columns: 1em auto; grid-template-columns: 1em auto;
.key { .key {
color: #00b; color: var(--primary-active);
text-shadow: 0 0 1px #00b; text-shadow: 0 0 1px var(--primary-hover);
} }
} }
} }

View File

@@ -1,4 +1,4 @@
import {Component, Input, OnInit, ViewChild} from '@angular/core'; import {Component, Input, OnInit, ViewChild, inject} from '@angular/core';
import {ShowSongService} from '../../services/show-song.service'; import {ShowSongService} from '../../services/show-song.service';
import {ShowSong} from '../../services/show-song'; import {ShowSong} from '../../services/show-song';
import {getScale} from '../../../songs/services/key.helper'; import {getScale} from '../../../songs/services/key.helper';
@@ -8,7 +8,7 @@ import {Show} from '../../services/show';
import {faEraser, faPenToSquare, faSave, faTrash} from '@fortawesome/free-solid-svg-icons'; import {faEraser, faPenToSquare, faSave, faTrash} from '@fortawesome/free-solid-svg-icons';
import {fade} from '../../../../animations'; import {fade} from '../../../../animations';
import {MatSelect} from '@angular/material/select'; import {MatSelect} from '@angular/material/select';
import {NgFor, NgIf} from '@angular/common';
import {MatFormField, MatLabel} from '@angular/material/form-field'; import {MatFormField, MatLabel} from '@angular/material/form-field';
import {MatOption} from '@angular/material/core'; import {MatOption} from '@angular/material/core';
import {MenuButtonComponent} from '../../../../widget-modules/components/menu-button/menu-button.component'; import {MenuButtonComponent} from '../../../../widget-modules/components/menu-button/menu-button.component';
@@ -17,6 +17,7 @@ import {MatInput} from '@angular/material/input';
import {CdkTextareaAutosize} from '@angular/cdk/text-field'; import {CdkTextareaAutosize} from '@angular/cdk/text-field';
import {ButtonRowComponent} from '../../../../widget-modules/components/button-row/button-row.component'; import {ButtonRowComponent} from '../../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../../widget-modules/components/button/button.component'; import {ButtonComponent} from '../../../../widget-modules/components/button/button.component';
import {CdkDragHandle} from '@angular/cdk/drag-drop';
@Component({ @Component({
selector: 'app-song', selector: 'app-song',
@@ -24,11 +25,9 @@ import {ButtonComponent} from '../../../../widget-modules/components/button/butt
styleUrls: ['./song.component.less'], styleUrls: ['./song.component.less'],
animations: [fade], animations: [fade],
imports: [ imports: [
NgIf,
MatFormField, MatFormField,
MatSelect, MatSelect,
ReactiveFormsModule, ReactiveFormsModule,
NgFor,
MatOption, MatOption,
MenuButtonComponent, MenuButtonComponent,
MatTooltip, MatTooltip,
@@ -38,12 +37,16 @@ import {ButtonComponent} from '../../../../widget-modules/components/button/butt
ButtonRowComponent, ButtonRowComponent,
ButtonComponent, ButtonComponent,
SongTextComponent, SongTextComponent,
CdkDragHandle,
], ],
}) })
export class SongComponent implements OnInit { export class SongComponent implements OnInit {
private showSongService = inject(ShowSongService);
@Input() public show: Show | null = null; @Input() public show: Show | null = null;
@Input() public showId: string | null = null; @Input() public showId: string | null = null;
@Input() public showText: boolean | null = null; @Input() public showText: boolean | null = null;
@Input() public dragHandle = false;
@Input() public index = -1; @Input() public index = -1;
@Input() public fullscreen = false; @Input() public fullscreen = false;
public keys: string[] = []; public keys: string[] = [];
@@ -57,8 +60,6 @@ export class SongComponent implements OnInit {
public editSongControl = new UntypedFormControl(); public editSongControl = new UntypedFormControl();
@ViewChild('option') private keyOptions: MatSelect; @ViewChild('option') private keyOptions: MatSelect;
public constructor(private showSongService: ShowSongService) {}
@Input() @Input()
public set showSong(song: ShowSong) { public set showSong(song: ShowSong) {
this.iSong = song; this.iSong = song;

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 { export interface Chord {
chord: string; chord: string;
length: number; length: number;
position: number; position: number;
slashChord: string | null; slashChord: string | null;
add: string | null; add: string | null;
addDescriptor?: ChordAddDescriptor | null;
prefix?: string;
suffix?: string;
} }

View File

@@ -1,12 +1,68 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {DbService} from '../../../services/db.service';
import {FileDataService} from './file-data.service'; import {FileDataService} from './file-data.service';
describe('FileDataService', () => { describe('FileDataService', () => {
beforeEach(() => void TestBed.configureTestingModule({})); let service: FileDataService;
let filesCollectionValueChangesSpy: jasmine.Spy;
let filesCollectionAddSpy: jasmine.Spy;
let songDocCollectionSpy: jasmine.Spy;
let songDocSpy: jasmine.Spy;
let fileDeleteSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
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({
add: filesCollectionAddSpy,
valueChanges: filesCollectionValueChangesSpy,
});
songDocSpy = jasmine.createSpy('songDoc').and.callFake((path: string) => {
if (path.includes('/files/')) {
return {delete: fileDeleteSpy};
}
return {collection: songDocCollectionSpy};
});
fileDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['doc']);
dbServiceSpy.doc.and.callFake(songDocSpy);
await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}],
});
service = TestBed.inject(FileDataService);
});
it('should be created', () => { it('should be created', () => {
const service: FileDataService = TestBed.inject(FileDataService); expect(service).toBeTruthy();
void expect(service).toBeTruthy(); });
it('should add files to the song files subcollection and return the generated id', async () => {
const file = {name: 'setlist.pdf', path: 'songs/song-1/files', createdAt: new Date()};
await expectAsync(service.set('song-1', file)).toBeResolvedTo('file-2');
expect(songDocSpy).toHaveBeenCalledWith('songs/song-1');
expect(songDocCollectionSpy).toHaveBeenCalledWith('files');
expect(filesCollectionAddSpy).toHaveBeenCalledWith(file);
});
it('should delete files from the nested file document path', async () => {
await service.delete('song-4', 'file-9');
expect(songDocSpy).toHaveBeenCalledWith('songs/song-4/files/file-9');
expect(fileDeleteSpy).toHaveBeenCalled();
});
it('should read files from the files subcollection with the id field attached', () => {
service.read$('song-3').subscribe();
expect(songDocSpy).toHaveBeenCalledWith('songs/song-3');
expect(songDocCollectionSpy).toHaveBeenCalledWith('files');
expect(filesCollectionValueChangesSpy).toHaveBeenCalledWith({idField: 'id'});
}); });
}); });

View File

@@ -1,4 +1,4 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {File} from './file'; import {File} from './file';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {FileServer} from './fileServer'; import {FileServer} from './fileServer';
@@ -8,7 +8,7 @@ import {DbService} from '../../../services/db.service';
providedIn: 'root', providedIn: 'root',
}) })
export class FileDataService { export class FileDataService {
public constructor(private db: DbService) {} private db = inject(DbService);
public async set(songId: string, file: FileServer): Promise<string> { public async set(songId: string, file: FileServer): Promise<string> {
const songRef = this.db.doc('songs/' + songId); const songRef = this.db.doc('songs/' + songId);

View File

@@ -1,16 +1,48 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {Storage} from '@angular/fire/storage';
import {FileDataService} from './file-data.service';
import {FileService} from './file.service'; import {FileService} from './file.service';
describe('FileService', () => { describe('FileService', () => {
let service: FileService; let service: FileService;
let fileDataServiceSpy: jasmine.SpyObj<FileDataService>;
type FileServiceInternals = FileService & {
resolveDownloadUrl: (path: string) => Promise<string>;
deleteFromStorage: (path: string) => Promise<void>;
};
beforeEach(async () => {
fileDataServiceSpy = jasmine.createSpyObj<FileDataService>('FileDataService', ['delete']);
fileDataServiceSpy.delete.and.resolveTo();
await TestBed.configureTestingModule({
providers: [
{provide: Storage, useValue: {app: 'test-storage'}},
{provide: FileDataService, useValue: fileDataServiceSpy},
],
});
beforeEach(() => {
void TestBed.configureTestingModule({});
service = TestBed.inject(FileService); service = TestBed.inject(FileService);
}); });
it('should be created', () => { 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,25 +1,30 @@
import {Injectable} from '@angular/core'; import {EnvironmentInjector, inject, Injectable, runInInjectionContext} from '@angular/core';
import {AngularFireStorage} from '@angular/fire/compat/storage'; import {deleteObject, getDownloadURL, ref, Storage} from '@angular/fire/storage';
import {firstValueFrom, Observable} from 'rxjs'; import {from, Observable} from 'rxjs';
import {FileDataService} from './file-data.service'; import {FileDataService} from './file-data.service';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class FileService { export class FileService {
public constructor( private storage = inject(Storage);
private storage: AngularFireStorage, private fileDataService = inject(FileDataService);
private fileDataService: FileDataService private environmentInjector = inject(EnvironmentInjector);
) {}
public getDownloadUrl(path: string): Observable<string> { public getDownloadUrl(path: string): Observable<string> {
const ref = this.storage.ref(path); return from(runInInjectionContext(this.environmentInjector, () => this.resolveDownloadUrl(path)));
return ref.getDownloadURL() as Observable<string>;
} }
public delete(path: string, songId: string, fileId: string): void { public delete(path: string, songId: string, fileId: string): void {
const ref = this.storage.ref(path); void runInInjectionContext(this.environmentInjector, () => this.deleteFromStorage(path));
void firstValueFrom(ref.delete());
void this.fileDataService.delete(songId, fileId); 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

@@ -0,0 +1,15 @@
import {getScale, scaleMapping} from './key.helper';
describe('key.helper', () => {
it('should render Gb correctly', () => {
void expect(scaleMapping['Gb']).toBe('G♭');
});
it('should expose a sharp-based scale for D', () => {
void expect(getScale('D')).toEqual(['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'H']);
});
it('should keep flat-based spelling for Db', () => {
void expect(getScale('Db')).toEqual(['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'B', 'H']);
});
});

View File

@@ -82,7 +82,7 @@ const scaleAssignment: {[key: string]: string[]} = {
C: KEYS_MAJOR_FLAT, C: KEYS_MAJOR_FLAT,
'C#': KEYS_MAJOR_FLAT, 'C#': KEYS_MAJOR_FLAT,
Db: KEYS_MAJOR_B, Db: KEYS_MAJOR_B,
D: KEYS_MAJOR_B, D: KEYS_MAJOR_FLAT,
'D#': KEYS_MAJOR_FLAT, 'D#': KEYS_MAJOR_FLAT,
Eb: KEYS_MAJOR_B, Eb: KEYS_MAJOR_B,
E: KEYS_MAJOR_FLAT, E: KEYS_MAJOR_FLAT,
@@ -125,7 +125,7 @@ export const scaleMapping: {[key: string]: string} = {
E: 'E', E: 'E',
F: 'F', F: 'F',
'F#': 'F♯', 'F#': 'F♯',
Gb: 'D♭', Gb: 'G♭',
G: 'G', G: 'G',
'G#': 'G♯', 'G#': 'G♯',
Ab: 'A♭', Ab: 'A♭',

View File

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

View File

@@ -1,35 +1,104 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {firstValueFrom, Subject} from 'rxjs';
import {take, toArray} from 'rxjs/operators';
import {DbService} from '../../../services/db.service';
import {SongDataService} from './song-data.service'; import {SongDataService} from './song-data.service';
import {AngularFirestore} from '@angular/fire/compat/firestore';
import {firstValueFrom, of} from 'rxjs';
describe('SongDataService', () => { describe('SongDataService', () => {
const songs = [{title: 'title1'}]; let service: SongDataService;
let songs$: Subject<Array<{id: string; title: string}>>;
let docUpdateSpy: jasmine.Spy<() => Promise<void>>;
let docDeleteSpy: jasmine.Spy<() => Promise<void>>;
let docSpy: jasmine.Spy;
let colAddSpy: jasmine.Spy<() => Promise<{id: string}>>;
let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>;
const angularFirestoreCollection = { beforeEach(async () => {
valueChanges: () => of(songs), songs$ = new Subject<Array<{id: string; title: string}>>();
}; docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.callFake(() => ({
update: docUpdateSpy,
delete: docDeleteSpy,
}));
colAddSpy = jasmine.createSpy('add').and.resolveTo({id: 'song-3'});
colSpy = jasmine.createSpy('col').and.returnValue({
add: colAddSpy,
});
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['col$', 'doc$', 'doc', 'col']);
dbServiceSpy.col$.and.returnValue(songs$.asObservable());
dbServiceSpy.doc$.and.returnValue(songs$.asObservable() as never);
dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy);
const mockAngularFirestore = { await TestBed.configureTestingModule({
collection: () => angularFirestoreCollection, providers: [{provide: DbService, useValue: dbServiceSpy}],
}; });
beforeEach( service = TestBed.inject(SongDataService);
() => });
void TestBed.configureTestingModule({
providers: [{provide: AngularFirestore, useValue: mockAngularFirestore}],
})
);
it('should be created', () => { it('should be created', () => {
const service: SongDataService = TestBed.inject(SongDataService); expect(service).toBeTruthy();
void expect(service).toBeTruthy();
}); });
it('should list songs', async () => { it('should load songs from the songs collection once on creation', () => {
const service: SongDataService = TestBed.inject(SongDataService); expect(dbServiceSpy.col$).toHaveBeenCalledTimes(1);
const list = await firstValueFrom(service.list$); expect(dbServiceSpy.col$).toHaveBeenCalledWith('songs');
void expect(list[0].title).toEqual('title1'); });
it('should emit an empty list first and then the loaded songs', async () => {
const emissionsPromise = firstValueFrom(service.list$.pipe(take(2), toArray()));
songs$.next([{id: 'song-1', title: 'Amazing Grace'}]);
const emissions = await emissionsPromise;
expect(emissions[0]).toEqual([]);
expect(emissions[1].map(song => song.id)).toEqual(['song-1']);
expect(emissions[1].map(song => song.title)).toEqual(['Amazing Grace']);
});
it('should replay the latest songs to late subscribers', async () => {
const initialSubscription = service.list$.subscribe();
songs$.next([{id: 'song-2', title: 'How Great'}]);
const latestSongs = await firstValueFrom(service.list$.pipe(take(1)));
expect(latestSongs.map(song => song.id)).toEqual(['song-2']);
expect(latestSongs.map(song => song.title)).toEqual(['How Great']);
initialSubscription.unsubscribe();
});
it('should read a single song by id', () => {
service.read$('song-7');
expect(dbServiceSpy.doc$).toHaveBeenCalledWith('songs/song-7');
});
it('should update a song at the expected document path', async () => {
await service.update$('song-8', {title: 'Updated'});
expect(docSpy).toHaveBeenCalledWith('songs/song-8');
const [updatePayload] = docUpdateSpy.calls.mostRecent().args as unknown as [Record<string, unknown>];
expect(updatePayload).toEqual({title: 'Updated'});
});
it('should add a song to the songs collection and return the new id', async () => {
await expectAsync(service.add({title: 'New Song'})).toBeResolvedTo('song-3');
expect(colSpy).toHaveBeenCalledWith('songs');
const [addPayload] = colAddSpy.calls.mostRecent().args as unknown as [Record<string, unknown>];
expect(addPayload).toEqual({title: 'New Song'});
});
it('should delete a song at the expected document path', async () => {
await service.delete('song-9');
expect(docSpy).toHaveBeenCalledWith('songs/song-9');
expect(docDeleteSpy).toHaveBeenCalled();
}); });
}); });

View File

@@ -1,24 +1,32 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {Song} from './song'; import {Song} from './song';
import {BehaviorSubject, Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {DbService} from '../../../services/db.service'; import {DbService} from '../../../services/db.service';
import {map} from 'rxjs/operators'; import {shareReplay, startWith} from 'rxjs/operators';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class SongDataService { export class SongDataService {
public list$ = new BehaviorSubject<Song[]>([]); private dbService = inject(DbService);
private collection = 'songs'; private collection = 'songs';
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 constructor(private dbService: DbService) { public read$ = (songId: string): Observable<Song | null> => this.dbService.doc$(this.collection + '/' + songId);
this.dbService.col$<Song>(this.collection).subscribe(_ => this.list$.next(_));
}
// public list$ = (): Observable<Song[]> => this.dbService.col$(this.collection);
//public read$ = (songId: string): Observable<Song | null> => this.dbService.doc$(this.collection + '/' + songId);
public read$ = (songId: string): Observable<Song | null> => this.list$.pipe(map(_ => _.find(s => s.id === songId) || null));
public update$ = async (songId: string, data: Partial<Song>): Promise<void> => await this.dbService.doc(this.collection + '/' + songId).update(data); public update$ = async (songId: string, data: Partial<Song>): Promise<void> => await this.dbService.doc(this.collection + '/' + songId).update(data);
public add = async (data: Partial<Song>): Promise<string> => (await this.dbService.col(this.collection).add(data)).id; public add = async (data: Partial<Song>): Promise<string> => (await this.dbService.col(this.collection).add(data)).id;
public delete = async (songId: string): Promise<void> => await this.dbService.doc(this.collection + '/' + songId).delete(); public delete = async (songId: string): Promise<void> => await this.dbService.doc(this.collection + '/' + songId).delete();

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

@@ -1,17 +1,17 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {SongService} from './song.service'; import {SongService} from './song.service';
import {Song} from './song'; import {Song} from './song';
import {filter} from 'rxjs/operators'; import {take} from 'rxjs/operators';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class SongListResolver { export class SongListResolver {
public constructor(private songService: SongService) {} private songService = inject(SongService);
public resolve(): Observable<Song[]> { public resolve(): Observable<Song[]> {
return this.songService.list$().pipe(filter(_ => _.length > 0)); return this.songService.listLoaded$().pipe(take(1));
} }
} }

View File

@@ -1,32 +1,100 @@
import {TestBed, waitForAsync} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {SongService} from './song.service';
import {SongDataService} from './song-data.service';
import {of} from 'rxjs'; import {of} from 'rxjs';
import {SongDataService} from './song-data.service';
import {SongService} from './song.service';
import {UserService} from '../../../services/user/user.service';
import {Timestamp} from '@angular/fire/firestore';
describe('SongService', () => { describe('SongService', () => {
const songs = [{title: 'title1'}]; let service: SongService;
let songDataServiceSpy: jasmine.SpyObj<SongDataService>;
let userServiceSpy: jasmine.SpyObj<UserService>;
const song = {
id: 'song-1',
title: 'Amazing Grace',
edits: [],
} as never;
const mockSongDataService = { beforeEach(async () => {
list: () => of(songs), songDataServiceSpy = jasmine.createSpyObj<SongDataService>('SongDataService', ['read$', 'update$', 'add', 'delete'], {
}; list$: of([song]),
});
userServiceSpy = jasmine.createSpyObj<UserService>('UserService', ['currentUser']);
beforeEach( songDataServiceSpy.read$.and.returnValue(of(song));
() => songDataServiceSpy.update$.and.resolveTo();
void TestBed.configureTestingModule({ songDataServiceSpy.add.and.resolveTo('song-2');
providers: [{provide: SongDataService, useValue: mockSongDataService}], songDataServiceSpy.delete.and.resolveTo();
}) userServiceSpy.currentUser.and.resolveTo({name: 'Benjamin'} as never);
);
await TestBed.configureTestingModule({
providers: [
{provide: SongDataService, useValue: songDataServiceSpy},
{provide: UserService, useValue: userServiceSpy},
],
});
service = TestBed.inject(SongService);
});
it('should be created', () => { it('should be created', () => {
const service: SongService = TestBed.inject(SongService); expect(service).toBeTruthy();
void expect(service).toBeTruthy();
}); });
it('should list songs', waitForAsync(() => { it('should list songs from the data service', done => {
const service: SongService = TestBed.inject(SongService); service.list$().subscribe(songs => {
service.list$().subscribe(s => { expect(songs).toEqual([song]);
void expect(s[0].title).toEqual('title1'); done();
});
});
it('should delegate reads to the data service', async () => {
await expectAsync(service.read('song-1')).toBeResolvedTo(song);
expect(songDataServiceSpy.read$).toHaveBeenCalledWith('song-1');
});
it('should append an edit with the current user when updating a song', async () => {
const timestamp = {seconds: 1} as never;
spyOn(Timestamp, 'now').and.returnValue(timestamp);
await service.update$('song-1', {title: 'Updated'});
expect(songDataServiceSpy.update$).toHaveBeenCalled();
const [, payload] = songDataServiceSpy.update$.calls.mostRecent().args as unknown as [string, Record<string, unknown>];
expect(payload.title).toBe('Updated');
expect(payload.edits).toEqual([{username: 'Benjamin', timestamp}]);
});
it('should not update when the song does not exist', async () => {
songDataServiceSpy.read$.and.returnValue(of(null));
await service.update$('missing-song', {title: 'Updated'});
expect(songDataServiceSpy.update$).not.toHaveBeenCalled();
});
it('should not update when no current user is available', async () => {
userServiceSpy.currentUser.and.resolveTo(null);
await service.update$('song-1', {title: 'Updated'});
expect(songDataServiceSpy.update$).not.toHaveBeenCalled();
});
it('should create new songs with the expected defaults', async () => {
await expectAsync(service.new(42, 'New Song')).toBeResolvedTo('song-2');
expect(songDataServiceSpy.add).toHaveBeenCalledWith({
number: 42,
title: 'New Song',
status: 'draft',
legalType: 'open',
});
});
it('should delete songs via the data service', async () => {
await service.delete('song-1');
expect(songDataServiceSpy.delete).toHaveBeenCalledWith('song-1');
}); });
}));
}); });

View File

@@ -1,10 +1,9 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {firstValueFrom, Observable} from 'rxjs'; import {firstValueFrom, Observable} from 'rxjs';
import {Song} from './song'; import {Song} from './song';
import {SongDataService} from './song-data.service'; import {SongDataService} from './song-data.service';
import {UserService} from '../../../services/user/user.service'; import {UserService} from '../../../services/user/user.service';
import firebase from 'firebase/compat/app'; import {Timestamp} from '@angular/fire/firestore';
import Timestamp = firebase.firestore.Timestamp;
// declare let importCCLI: any; // declare let importCCLI: any;
@@ -17,22 +16,17 @@ export type SongLegalType = 'open' | 'allowed';
providedIn: 'root', providedIn: 'root',
}) })
export class SongService { export class SongService {
private songDataService = inject(SongDataService);
private userService = inject(UserService);
public static TYPES: SongType[] = ['Praise', 'Worship', 'Misc']; public static TYPES: SongType[] = ['Praise', 'Worship', 'Misc'];
public static STATUS: SongStatus[] = ['draft', 'set', 'final']; public static STATUS: SongStatus[] = ['draft', 'set', 'final'];
public static LEGAL_OWNER: SongLegalOwner[] = ['CCLI', 'other']; public static LEGAL_OWNER: SongLegalOwner[] = ['CCLI', 'other'];
public static LEGAL_TYPE: SongLegalType[] = ['open', 'allowed']; public static LEGAL_TYPE: SongLegalType[] = ['open', 'allowed'];
// private list: Song[];
public constructor(
private songDataService: SongDataService,
private userService: UserService
) {
// importCCLI = (songs: Song[]) => this.updateFromCLI(songs);
}
public list$ = (): Observable<Song[]> => this.songDataService.list$; //.pipe(tap(_ => (this.list = _))); 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): Observable<Song | null> => this.songDataService.read$(songId);
public read = (songId: string): Promise<Song | null> => firstValueFrom(this.read$(songId)); public read = (songId: string): Promise<Song | null> => firstValueFrom(this.read$(songId));

View File

@@ -1,6 +1,5 @@
import firebase from 'firebase/compat/app';
import {SongLegalOwner, SongLegalType, SongStatus, SongType} from './song.service'; import {SongLegalOwner, SongLegalType, SongStatus, SongType} from './song.service';
import Timestamp = firebase.firestore.Timestamp; import {Timestamp} from '@angular/fire/firestore';
export interface Song { export interface Song {
id: string; id: string;

View File

@@ -2,8 +2,22 @@ import {TestBed} from '@angular/core/testing';
import {TextRenderingService} from './text-rendering.service'; import {TextRenderingService} from './text-rendering.service';
import {LineType} from './line-type'; import {LineType} from './line-type';
import {SectionType} from './section-type'; import {SectionType} from './section-type';
import {TransposeService} from './transpose.service';
import {ChordAddDescriptor} from './chord';
describe('TextRenderingService', () => { describe('TextRenderingService', () => {
const descriptor = (raw: string, partial: Partial<ChordAddDescriptor>) =>
jasmine.objectContaining({
raw,
quality: null,
extensions: [],
additions: [],
suspensions: [],
alterations: [],
modifiers: [],
...partial,
});
const testText = `Strophe const testText = `Strophe
C D E F G A H C D E F G A H
Text Line 1-1 Text Line 1-1
@@ -31,6 +45,7 @@ Cool bridge without any chords
void expect(service).toBeTruthy(); void expect(service).toBeTruthy();
}); });
describe('section parsing', () => {
it('should parse section types', () => { it('should parse section types', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService); const service: TextRenderingService = TestBed.inject(TextRenderingService);
const sections = service.parse(testText, null); const sections = service.parse(testText, null);
@@ -44,6 +59,53 @@ Cool bridge without any chords
void expect(sections[3].number).toBe(0); 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', () => { it('should parse text lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService); const service: TextRenderingService = TestBed.inject(TextRenderingService);
const sections = service.parse(testText, null); 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'); 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', () => { it('should parse chord lines', () => {
const service: TextRenderingService = TestBed.inject(TextRenderingService); const service: TextRenderingService = TestBed.inject(TextRenderingService);
const sections = service.parse(testText, null); const sections = service.parse(testText, null);
@@ -73,16 +195,15 @@ Cool bridge without any chords
void expect(sections[1].lines[2].type).toBe(LineType.chord); void expect(sections[1].lines[2].type).toBe(LineType.chord);
void expect(sections[1].lines[2].text).toBe(' a d e f g a h c b'); void expect(sections[1].lines[2].text).toBe(' a d e f g a h c b');
void expect(sections[2].lines[0].type).toBe(LineType.chord); void expect(sections[2].lines[0].type).toBe(LineType.chord);
void expect(sections[2].lines[0].text).toBe('c c# db c7 cmaj7 c/e'); 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([ void expect(sections[2].lines[0].chords).toEqual([
{chord: 'c', length: 1, position: 0, add: null, slashChord: null}, {chord: 'c', length: 1, position: 0, add: null, slashChord: null, addDescriptor: null},
{chord: 'c#', length: 2, position: 2, add: null, slashChord: null}, {chord: 'c#', length: 2, position: 2, add: null, slashChord: null, addDescriptor: null},
{chord: 'db', length: 2, position: 5, add: null, slashChord: null}, {chord: 'db', length: 2, position: 5, add: null, slashChord: null, addDescriptor: null},
{chord: 'c', length: 2, position: 8, add: '7', slashChord: 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}, {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'}, {chord: 'c', length: 3, position: 22, add: null, slashChord: 'e', addDescriptor: null},
]); ]);
}); });
@@ -93,8 +214,288 @@ g# F# E g# F# E
text`; text`;
const sections = service.parse(text, null); const sections = service.parse(text, null);
void expect(sections[0].lines[0].type).toBe(LineType.chord); void expect(sections[0].lines[0].type).toBe(LineType.chord);
void expect(sections[0].lines[0].text).toBe('g# F# E g# F# E'); void expect(sections[0].lines[0].text).toBe('g F E g F E');
void expect(sections[0].lines[1].type).toBe(LineType.text); void expect(sections[0].lines[1].type).toBe(LineType.text);
void expect(sections[0].lines[1].text).toBe('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

@@ -1,55 +1,170 @@
import {Injectable} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {TransposeService} from './transpose.service'; import {TransposeService} from './transpose.service';
import {TransposeMode} from './transpose-mode'; import {TransposeMode} from './transpose-mode';
import {SectionType} from './section-type'; import {SectionType} from './section-type';
import {Section} from './section'; import {Section} from './section';
import {LineType} from './line-type'; import {LineType} from './line-type';
import {Chord} from './chord'; import {Chord, ChordAddDescriptor, ChordValidationIssue} from './chord';
import {Line} from './line'; 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({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class TextRenderingService { export class TextRenderingService {
private regexSection = /(Strophe|Refrain|Bridge)/; private transposeService = inject(TransposeService);
public constructor(private transposeService: TransposeService) {} 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[] { public parse(text: string, transpose: TransposeMode | null, withComments = true): Section[] {
if (!text) { if (!text) {
return []; return [];
} }
const arrayOfLines = text.split(/\r?\n/).filter(_ => _ && (!_.startsWith('#') || withComments));
const indices = { const indices = {
[SectionType.Bridge]: 0, [SectionType.Bridge]: 0,
[SectionType.Chorus]: 0, [SectionType.Chorus]: 0,
[SectionType.Verse]: 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); const type = this.getSectionTypeOfLine(line);
if (this.regexSection.exec(line) && type !== null) { if (type !== null) {
const section: Section = { sections.push({
type, type,
number: indices[type]++, number: indices[type]++,
lines: [], lines: [],
}; });
return [...array, section]; continue;
}
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[]);
} }
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; if (!text) return null;
const cords = this.readChords(text); const validationResult = lineNumber ? this.getChordLineValidationResult(text, lineNumber) : {chords: [], issues: [], isStrictChordLine: false, isChordLike: false};
const hasMatches = cords.length > 0; const validationIssues = validationResult.issues;
const type = hasMatches ? LineType.chord : LineType.text; 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); 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) { if (!match || match.length < 2) {
return null; return null;
} }
const typeString = match[1]; const typeString = match[1].toLowerCase();
switch (typeString) { switch (typeString) {
case 'Strophe': case 'strophe':
return SectionType.Verse; return SectionType.Verse;
case 'Refrain': case 'refrain':
return SectionType.Chorus; return SectionType.Chorus;
case 'Bridge': case 'bridge':
return SectionType.Bridge; return SectionType.Bridge;
} }
return null; return null;
} }
private readChords(chordLine: string): Chord[] { private getParsedChords(chordLine: string): Chord[] {
let match: string[] | null;
const chords: Chord[] = []; const chords: Chord[] = [];
const tokens = chordLine.match(/\S+/g) ?? [];
// https://regex101.com/r/68jMB8/5 for (const token of tokens) {
const regex = const position = chordLine.indexOf(token, chords.length > 0 ? chords[chords.length - 1].position + chords[chords.length - 1].length : 0);
/(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; const chord = this.parseChordToken(token, position);
if (chord) {
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];
}
chords.push(chord); chords.push(chord);
} }
}
const chordCount = chords.reduce((acc: number, cur: Chord) => acc + cur.length, 0); return chords;
const lineCount = chordLine.replace(/\s/g, '').length; }
const isChrod = chordCount * 1.2 > lineCount;
return isChrod ? 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

@@ -1,6 +1,8 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {TransposeService} from './transpose.service'; import {TransposeService} from './transpose.service';
import {LineType} from './line-type';
import {Line} from './line';
describe('TransposeService', () => { describe('TransposeService', () => {
let service: TransposeService; let service: TransposeService;
@@ -11,8 +13,7 @@ describe('TransposeService', () => {
}); });
it('should create map upwards', () => { it('should create map upwards', () => {
const distance = service.getDistance('D', 'G'); const map = service.getMap('D', 'G');
const map = service.getMap('D', distance);
if (map) { if (map) {
void expect(map['D']).toBe('G'); void expect(map['D']).toBe('G');
@@ -20,11 +21,65 @@ describe('TransposeService', () => {
}); });
it('should create map downwards', () => { it('should create map downwards', () => {
const distance = service.getDistance('G', 'D'); const map = service.getMap('G', 'D');
const map = service.getMap('G', distance);
if (map) { if (map) {
void expect(map['G']).toBe('D'); void expect(map['G']).toBe('D');
} }
}); });
it('should transpose enharmonic targets by semitone distance', () => {
const distance = service.getDistance('C', 'Db');
const map = service.getMap('C', 'Db');
void expect(distance).toBe(1);
void expect(map?.['C']).toBe('Db');
void expect(map?.['G']).toBe('Ab');
});
it('should keep german B/H notation consistent', () => {
const distance = service.getDistance('H', 'C');
const map = service.getMap('H', 'C');
void expect(distance).toBe(1);
void expect(map?.['H']).toBe('C');
void expect(map?.['B']).toBe('H');
});
it('should render unknown chords as X', () => {
const line: Line = {
type: LineType.chord,
text: '',
chords: [{chord: 'Q', add: 'sus4', slashChord: null, position: 0, length: 1}],
};
const rendered = service.renderChords(line);
void expect(rendered.text).toBe('Xsus4');
});
it('should render unknown slash chords as X', () => {
const line: Line = {
type: LineType.chord,
text: '',
chords: [{chord: 'C', add: null, slashChord: 'Q', position: 0, length: 1}],
};
const rendered = service.renderChords(line);
void expect(rendered.text).toBe('C/X');
});
it('should transpose lines with long chord positions without truncating', () => {
const line: Line = {
type: LineType.chord,
text: '',
chords: [{chord: 'C', add: null, slashChord: null, position: 120, length: 1}],
};
const rendered = service.renderChords(line);
void expect(rendered.text.length).toBe(121);
void expect(rendered.text.endsWith('C')).toBeTrue();
});
}); });

View File

@@ -5,16 +5,69 @@ import {Chord} from './chord';
import {Line} from './line'; import {Line} from './line';
type TransposeMap = {[key: string]: string}; type TransposeMap = {[key: string]: string};
type ScaleVariants = [string[], string[]];
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class TransposeService { export class TransposeService {
private readonly enharmonicAliases: Array<[string, string]> = [
['C#', 'Db'],
['D#', 'Eb'],
['F#', 'Gb'],
['G#', 'Ab'],
['A#', 'B'],
['c#', 'db'],
['d#', 'eb'],
['f#', 'gb'],
['g#', 'ab'],
['a#', 'b'],
];
private readonly keyToSemitone: Record<string, number> = {
C: 0,
'C#': 1,
Db: 1,
D: 2,
'D#': 3,
Eb: 3,
E: 4,
F: 5,
'F#': 6,
Gb: 6,
G: 7,
'G#': 8,
Ab: 8,
A: 9,
'A#': 10,
B: 10,
H: 11,
c: 0,
'c#': 1,
db: 1,
d: 2,
'd#': 3,
eb: 3,
e: 4,
f: 5,
'f#': 6,
gb: 6,
g: 7,
'g#': 8,
ab: 8,
a: 9,
'a#': 10,
b: 10,
h: 11,
};
private readonly mapCache = new Map<string, TransposeMap>();
public transpose(line: Line, baseKey: string, targetKey: string): Line { public transpose(line: Line, baseKey: string, targetKey: string): Line {
if (line.type !== LineType.chord || !line.chords) return line; if (line.type !== LineType.chord || !line.chords) return line;
const difference = this.getDistance(baseKey, targetKey); const difference = this.getDistance(baseKey, targetKey);
const map = this.getMap(baseKey, difference); const map = this.getMap(baseKey, targetKey);
const chords = difference !== 0 && map ? line.chords.map(chord => this.transposeChord(chord, map)) : line.chords; const chords = difference !== 0 && map ? line.chords.map(chord => this.transposeChord(chord, map)) : line.chords;
const renderedLine = this.renderLine(chords); const renderedLine = this.renderLine(chords);
@@ -32,32 +85,59 @@ export class TransposeService {
} }
public getDistance(baseKey: string, targetKey: string): number { public getDistance(baseKey: string, targetKey: string): number {
const scale = getScaleType(baseKey); const baseSemitone = this.getSemitone(baseKey);
return scale ? (scale[0].indexOf(targetKey) - scale[0].indexOf(baseKey) ?? scale[1].indexOf(targetKey) - scale[1].indexOf(baseKey)) % 12 : 0; const targetSemitone = this.getSemitone(targetKey);
if (baseSemitone === undefined || targetSemitone === undefined) {
return 0;
} }
public getMap(baseKey: string, difference: number): TransposeMap | null { return (targetSemitone - baseSemitone + 12) % 12;
const scale = getScaleType(baseKey); }
if (!scale) {
public getMap(baseKey: string, targetKey: string): TransposeMap | null {
const cacheKey = `${baseKey}:${targetKey}`;
const cachedMap = this.mapCache.get(cacheKey);
if (cachedMap) {
return cachedMap;
}
const sourceScales = this.getScaleVariants(baseKey);
const targetScales = this.getScaleVariants(targetKey);
if (!sourceScales || !targetScales) {
return null; return null;
} }
const map: {[key: string]: string} = {};
const difference = this.getDistance(baseKey, targetKey);
const map: TransposeMap = {};
sourceScales.forEach((sourceScale, scaleIndex) => {
const targetScale = targetScales[scaleIndex];
for (let i = 0; i < 12; i++) { for (let i = 0; i < 12; i++) {
const source = scale[0][i]; const source = sourceScale[i];
const mappedIndex = (i + difference + 12) % 12; const mappedIndex = (i + difference + 12) % 12;
map[source] = scale[0][mappedIndex]; map[source] = targetScale[mappedIndex];
} }
for (let i = 0; i < 12; i++) { });
const source = scale[1][i];
const mappedIndex = (i + difference + 12) % 12; this.enharmonicAliases.forEach(([left, right]) => {
map[source] = scale[1][mappedIndex]; if (map[left] && !map[right]) {
map[right] = map[left];
} }
if (map[right] && !map[left]) {
map[left] = map[right];
}
});
this.mapCache.set(cacheKey, map);
return map; return map;
} }
private transposeChord(chord: Chord, map: TransposeMap): Chord { private transposeChord(chord: Chord, map: TransposeMap): Chord {
const translatedChord = map[chord.chord]; // Intentional fallback: unknown chord tokens must stay visibly invalid as "X".
const translatedSlashChord = chord.slashChord ? map[chord.slashChord] : null; // 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;
return { return {
...chord, ...chord,
chord: translatedChord, chord: translatedChord,
@@ -66,23 +146,46 @@ export class TransposeService {
} }
private renderLine(chords: Chord[]): string { private renderLine(chords: Chord[]): string {
let template = ' '; const width = chords.reduce((max, chord) => {
return Math.max(max, chord.position + this.renderChord(chord).length);
}, 0);
const buffer = Array.from({length: width}, () => ' ');
chords.forEach(chord => { chords.forEach(chord => {
const pos = chord.position; const pos = chord.position;
const renderedChord = this.renderChord(chord); const renderedChord = this.renderChord(chord);
const newLength = renderedChord.length; const requiredLength = pos + renderedChord.length;
const pre = template.substr(0, pos); while (buffer.length < requiredLength) {
const post = template.substr(pos + newLength); buffer.push(' ');
}
template = pre + renderedChord + post; for (let i = 0; i < renderedChord.length; i++) {
buffer[pos + i] = renderedChord[i];
}
}); });
return template.trimRight(); return buffer.join('').trimEnd();
} }
private renderChord(chord: Chord) { private renderChord(chord: Chord): string {
return scaleMapping[chord.chord] + (chord.add ? chord.add : '') + (chord.slashChord ? '/' + scaleMapping[chord.slashChord] : ''); // 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 prefix + renderedChord + (chord.add ?? '') + (renderedSlashChord ? '/' + renderedSlashChord : '') + suffix;
}
private getSemitone(key: string): number | undefined {
return this.keyToSemitone[key];
}
private getScaleVariants(key: string): ScaleVariants | null {
const scales = getScaleType(key);
return scales ? [scales[0], scales[1]] : null;
} }
} }

View File

@@ -1,12 +1,59 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {Storage} from '@angular/fire/storage';
import {FileDataService} from './file-data.service';
import {Upload} from './upload';
import {UploadService} from './upload.service'; import {UploadService} from './upload.service';
describe('UploadServiceService', () => { describe('UploadService', () => {
beforeEach(() => void TestBed.configureTestingModule({})); 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: {app: 'test-storage'}},
{provide: FileDataService, useValue: fileDataServiceSpy},
],
});
service = TestBed.inject(UploadService);
});
it('should be created', () => { it('should be created', () => {
const service: UploadService = TestBed.inject(UploadService); expect(service).toBeTruthy();
void 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

@@ -1,8 +1,7 @@
import {Injectable} from '@angular/core'; import {EnvironmentInjector, Injectable, inject, runInInjectionContext} from '@angular/core';
import {Upload} from './upload'; import {Upload} from './upload';
import {FileDataService} from './file-data.service'; import {FileDataService} from './file-data.service';
import {AngularFireStorage} from '@angular/fire/compat/storage'; import {ref, Storage, uploadBytesResumable} from '@angular/fire/storage';
import {finalize} from 'rxjs/operators';
import {FileBase} from './fileBase'; import {FileBase} from './fileBase';
import {FileServer} from './fileServer'; import {FileServer} from './fileServer';
@@ -10,26 +9,27 @@ import {FileServer} from './fileServer';
providedIn: 'root', providedIn: 'root',
}) })
export class UploadService extends FileBase { export class UploadService extends FileBase {
public constructor( private fileDataService = inject(FileDataService);
private fileDataService: FileDataService, private storage = inject(Storage);
private angularFireStorage: AngularFireStorage private environmentInjector = inject(EnvironmentInjector);
) {
super();
}
public pushUpload(songId: string, upload: Upload): void { public pushUpload(songId: string, upload: Upload): void {
const directory = this.directory(songId); const directory = this.directory(songId);
const filePath = `${directory}/${upload.file.name}`; const filePath = `${directory}/${upload.file.name}`;
upload.path = directory; upload.path = directory;
const ref = this.angularFireStorage.ref(filePath); const task = runInInjectionContext(this.environmentInjector, () => this.startUpload(filePath, upload.file));
const task = ref.put(upload.file);
task.percentageChanges().subscribe(percent => (upload.progress = percent ?? 0)); task.on(
task 'state_changed',
.snapshotChanges() snapshot => {
.pipe(finalize(() => void this.saveFileData(songId, upload))) upload.progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
.subscribe(); },
() => {
// Keep current UX: upload errors are ignored by this service.
},
() => void this.saveFileData(songId, upload)
);
} }
private async saveFileData(songId: string, upload: Upload) { private async saveFileData(songId: string, upload: Upload) {
@@ -40,4 +40,9 @@ export class UploadService extends FileBase {
}; };
await this.fileDataService.set(songId, file); await this.fileDataService.set(songId, file);
} }
private startUpload(filePath: string, file: File) {
const storageRef = ref(this.storage, filePath);
return uploadBytesResumable(storageRef, file);
}
} }

View File

@@ -9,10 +9,12 @@
<mat-label>Typ</mat-label> <mat-label>Typ</mat-label>
<mat-select formControlName="type"> <mat-select formControlName="type">
<mat-option [value]="null">- kein Filter -</mat-option> <mat-option [value]="null">- kein Filter -</mat-option>
<mat-option *ngFor="let type of types" [value]="type">{{ @for (type of types; track type) {
<mat-option [value]="type">{{
type | songType type | songType
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
@@ -20,10 +22,12 @@
<mat-label>Tonart</mat-label> <mat-label>Tonart</mat-label>
<mat-select formControlName="key"> <mat-select formControlName="key">
<mat-option [value]="null">- kein Filter -</mat-option> <mat-option [value]="null">- kein Filter -</mat-option>
<mat-option *ngFor="let key of keys" [value]="key">{{ @for (key of keys; track key) {
<mat-option [value]="key">{{
key | key key | key
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
@@ -31,10 +35,12 @@
<mat-label>Rechtlicher Status</mat-label> <mat-label>Rechtlicher Status</mat-label>
<mat-select formControlName="legalType"> <mat-select formControlName="legalType">
<mat-option [value]="null">- kein Filter -</mat-option> <mat-option [value]="null">- kein Filter -</mat-option>
<mat-option *ngFor="let key of legalType" [value]="key">{{ @for (key of legalType; track key) {
<mat-option [value]="key">{{
key | legalType key | legalType
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
@@ -42,10 +48,12 @@
<mat-label>Attribute</mat-label> <mat-label>Attribute</mat-label>
<mat-select formControlName="flag"> <mat-select formControlName="flag">
<mat-option [value]="null">- kein Filter -</mat-option> <mat-option [value]="null">- kein Filter -</mat-option>
<mat-option *ngFor="let flag of getFlags()" [value]="flag">{{ @for (flag of getFlags(); track flag) {
<mat-option [value]="flag">{{
flag flag
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>

View File

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

View File

@@ -1,30 +1,45 @@
<div *ngIf="songs$ | async as songs"> @if (songs$ | async; as songs) {
<div>
<app-list-header [anyFilterActive]="anyFilterActive"> <app-list-header [anyFilterActive]="anyFilterActive">
<app-filter [songs]="songs" route="songs"></app-filter> <app-filter [songs]="songs"></app-filter>
</app-list-header> </app-list-header>
<app-card [padding]="false"> <app-card [padding]="false">
<div *ngFor="let song of songs; trackBy: trackBy" [routerLink]="song.id" class="list-item"> @for (song of songs; track trackBy($index, song)) {
<div [routerLink]="song.id" class="list-item">
<div class="number">{{ song.number }}</div> <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> <div>
<ng-container *appRole="['contributor']"> <ng-container *appRole="['contributor']">
<div *ngIf="song.status === 'draft'" class="warning"> @if (song.status === 'draft') {
<div class="warning">
<fa-icon [icon]="faDraft"></fa-icon> <fa-icon [icon]="faDraft"></fa-icon>
</div> </div>
<div *ngIf="song.status === 'set'" class="neutral"> }
@if (song.status === 'set') {
<div class="neutral">
<fa-icon [icon]="faDraft"></fa-icon> <fa-icon [icon]="faDraft"></fa-icon>
</div> </div>
<div *ngIf="song.status === 'final'" class="success"> }
@if (song.status === 'final') {
<div class="success">
<fa-icon [icon]="faFinal"></fa-icon> <fa-icon [icon]="faFinal"></fa-icon>
</div> </div>
}
</ng-container> </ng-container>
<div *ngIf="song.legalType === 'open'" class="warning"> @if (song.legalType === 'open') {
<div class="warning">
<fa-icon [icon]="faLegal"></fa-icon> <fa-icon [icon]="faLegal"></fa-icon>
</div> </div>
}
</div> </div>
<div>{{ song.key }}</div> <div>{{ song.key }}</div>
</div> </div>
}
</app-card> </app-card>
</div> </div>
}

View File

@@ -1,5 +1,3 @@
@import "../../../../styles/styles";
.list-item { .list-item {
padding: 5px 20px; padding: 5px 20px;
display: grid; display: grid;
@@ -11,13 +9,14 @@
} }
cursor: pointer; cursor: pointer;
transition: var(--transition);
&:hover { &:hover {
background: @primary-color; background: var(--hover-background);
color: #fff; color: var(--text);
.warning { .warning {
color: #fff; color: var(--danger);
} }
} }
} }
@@ -28,18 +27,27 @@
text-align: right; text-align: right;
} }
.title {
gap: 6px;
}
.validation-star {
color: var(--danger);
font-weight: bold;
}
.neutral, .warning, .success { .neutral, .warning, .success {
width: 30px; width: 30px;
} }
.neutral { .neutral {
color: #888; color: var(--text-soft);
} }
.warning { .warning {
color: #ba3500; color: var(--danger);
} }
.success { .success {
color: #307501; color: var(--success);
} }

View File

@@ -12,7 +12,7 @@ describe('SongListComponent', () => {
const songs = [{title: 'title1'}]; const songs = [{title: 'title1'}];
const mockSongService = { const mockSongService = {
list: () => of(songs), list$: () => of(songs),
}; };
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {

View File

@@ -1,5 +1,4 @@
import {ChangeDetectionStrategy, Component, OnDestroy, OnInit} from '@angular/core'; import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
import {SongService} from '../services/song.service';
import {Song} from '../services/song'; import {Song} from '../services/song';
import {map} from 'rxjs/operators'; import {map} from 'rxjs/operators';
import {combineLatest, Observable} from 'rxjs'; import {combineLatest, Observable} from 'rxjs';
@@ -7,59 +6,54 @@ import {fade} from '../../../animations';
import {ActivatedRoute, RouterLink} from '@angular/router'; import {ActivatedRoute, RouterLink} from '@angular/router';
import {filterSong} from '../../../services/filter.helper'; import {filterSong} from '../../../services/filter.helper';
import {FilterValues} from './filter/filter-values'; import {FilterValues} from './filter/filter-values';
import {ScrollService} from '../../../services/scroll.service';
import {faBalanceScaleRight, faCheck, faPencilRuler} from '@fortawesome/free-solid-svg-icons'; import {faBalanceScaleRight, faCheck, faPencilRuler} from '@fortawesome/free-solid-svg-icons';
import {AsyncPipe, NgFor, NgIf} from '@angular/common'; 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 {ListHeaderComponent} from '../../../widget-modules/components/list-header/list-header.component';
import {FilterComponent} from './filter/filter.component'; import {FilterComponent} from './filter/filter.component';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {RoleDirective} from '../../../services/user/role.directive'; import {RoleDirective} from '../../../services/user/role.directive';
import {FaIconComponent} from '@fortawesome/angular-fontawesome'; import {FaIconComponent} from '@fortawesome/angular-fontawesome';
interface SongListItem extends Song {
hasChordValidationIssues: boolean;
}
@Component({ @Component({
selector: 'app-songs', selector: 'app-songs',
templateUrl: './song-list.component.html', templateUrl: './song-list.component.html',
styleUrls: ['./song-list.component.less'], styleUrls: ['./song-list.component.less'],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
animations: [fade], animations: [fade],
imports: [NgIf, ListHeaderComponent, FilterComponent, CardComponent, NgFor, RouterLink, RoleDirective, FaIconComponent, AsyncPipe], imports: [ListHeaderComponent, FilterComponent, CardComponent, RouterLink, RoleDirective, FaIconComponent, AsyncPipe],
}) })
export class SongListComponent implements OnInit, OnDestroy { export class SongListComponent {
private route = inject(ActivatedRoute);
private textRenderingService = inject(TextRenderingService);
private filterStore = inject(FilterStoreService);
public anyFilterActive = false; public anyFilterActive = false;
public songs$: Observable<Song[]> | null = combineLatest([ public songs$: Observable<SongListItem[]> = combineLatest([
this.activatedRoute.queryParams.pipe(map(_ => _ as FilterValues)), this.filterStore.songFilter$,
this.activatedRoute.data.pipe( this.route.data.pipe(map(data => (data['songs'] as Song[]).slice().sort((a, b) => a.number - b.number))),
map(data => data.songList as Song[]),
map(songs => songs.sort((a, b) => a.number - b.number))
),
]).pipe( ]).pipe(
map(_ => { map(([filter, songs]) => {
const songs = _[1];
const filter = _[0];
this.anyFilterActive = this.checkIfFilterActive(filter); 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 faLegal = faBalanceScaleRight;
public faDraft = faPencilRuler; public faDraft = faPencilRuler;
public faFinal = faCheck; public faFinal = faCheck;
public constructor( public trackBy = (index: number, show: SongListItem) => show.id;
private songService: SongService,
private activatedRoute: ActivatedRoute,
private scrollService: ScrollService
) {}
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;
private filter(song: Song, filter: FilterValues): boolean { private filter(song: Song, filter: FilterValues): boolean {
let baseFilter = filterSong(song, filter.q); let baseFilter = filterSong(song, filter.q);

View File

@@ -1,5 +1,6 @@
<app-card heading="Angehängte Dateien"> <app-card heading="Angehängte Dateien">
<div *ngIf="currentUpload"> @if (currentUpload) {
<div>
<div class="progress"> <div class="progress">
<div <div
[ngStyle]="{ width: currentUpload?.progress + '%' }" [ngStyle]="{ width: currentUpload?.progress + '%' }"
@@ -9,6 +10,7 @@
Progress: {{ currentUpload?.name }} | {{ currentUpload?.progress }}% Progress: {{ currentUpload?.name }} | {{ currentUpload?.progress }}%
Complete Complete
</div> </div>
}
<div class="upload"> <div class="upload">
<label> <label>
<input (change)="detectFiles($event)" type="file" /> <input (change)="detectFiles($event)" type="file" />
@@ -23,7 +25,9 @@
</button> </button>
</div> </div>
<p *ngFor="let file of files$ | async"> @for (file of files$ | async; track file) {
<p>
<app-file [file]="file" [songId]="songId"></app-file> <app-file [file]="file" [songId]="songId"></app-file>
</p> </p>
}
</app-card> </app-card>

View File

@@ -1,4 +1,4 @@
import {Component} from '@angular/core'; import {Component, inject} from '@angular/core';
import {Upload} from '../../../services/upload'; import {Upload} from '../../../services/upload';
import {UploadService} from '../../../services/upload.service'; import {UploadService} from '../../../services/upload.service';
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute} from '@angular/router';
@@ -7,7 +7,7 @@ import {FileDataService} from '../../../services/file-data.service';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {File} from '../../../services/file'; import {File} from '../../../services/file';
import {CardComponent} from '../../../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../../../widget-modules/components/card/card.component';
import {AsyncPipe, NgFor, NgIf, NgStyle} from '@angular/common'; import {AsyncPipe, NgStyle} from '@angular/common';
import {MatIconButton} from '@angular/material/button'; import {MatIconButton} from '@angular/material/button';
import {MatIcon} from '@angular/material/icon'; import {MatIcon} from '@angular/material/icon';
import {FileComponent} from './file/file.component'; import {FileComponent} from './file/file.component';
@@ -16,19 +16,19 @@ import {FileComponent} from './file/file.component';
selector: 'app-edit-file', selector: 'app-edit-file',
templateUrl: './edit-file.component.html', templateUrl: './edit-file.component.html',
styleUrls: ['./edit-file.component.less'], styleUrls: ['./edit-file.component.less'],
imports: [CardComponent, NgIf, NgStyle, MatIconButton, MatIcon, NgFor, FileComponent, AsyncPipe], imports: [CardComponent, NgStyle, MatIconButton, MatIcon, FileComponent, AsyncPipe],
}) })
export class EditFileComponent { export class EditFileComponent {
private activatedRoute = inject(ActivatedRoute);
private uploadService = inject(UploadService);
private fileService = inject(FileDataService);
public selectedFiles: FileList | null = null; public selectedFiles: FileList | null = null;
public currentUpload: Upload | null = null; public currentUpload: Upload | null = null;
public songId: string | null = null; public songId: string | null = null;
public files$: Observable<File[]>; public files$: Observable<File[]>;
public constructor( public constructor() {
private activatedRoute: ActivatedRoute,
private uploadService: UploadService,
private fileService: FileDataService
) {
this.activatedRoute.params this.activatedRoute.params
.pipe( .pipe(
map(param => param as {songId: string}), map(param => param as {songId: string}),

View File

@@ -1,4 +1,4 @@
import {Component, Input} from '@angular/core'; import {Component, Input, inject} from '@angular/core';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {File} from '../../../../services/file'; import {File} from '../../../../services/file';
import {faTrashAlt} from '@fortawesome/free-solid-svg-icons'; import {faTrashAlt} from '@fortawesome/free-solid-svg-icons';
@@ -14,6 +14,8 @@ import {AsyncPipe} from '@angular/common';
imports: [MatIconButton, FaIconComponent, AsyncPipe], imports: [MatIconButton, FaIconComponent, AsyncPipe],
}) })
export class FileComponent { export class FileComponent {
private fileService = inject(FileService);
public url$: Observable<string> | null = null; public url$: Observable<string> | null = null;
public name = ''; public name = '';
public faTrash = faTrashAlt; public faTrash = faTrashAlt;
@@ -21,8 +23,6 @@ export class FileComponent {
private fileId: string | null = null; private fileId: string | null = null;
private path: string | null = null; private path: string | null = null;
public constructor(private fileService: FileService) {}
@Input() @Input()
public set file(file: File) { public set file(file: File) {
this.url$ = this.fileService.getDownloadUrl(file.path + '/' + file.name); this.url$ = this.fileService.getDownloadUrl(file.path + '/' + file.name);

View File

@@ -1,5 +1,4 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {EditSongGuard} from './edit-song.guard'; import {EditSongGuard} from './edit-song.guard';
describe('EditSongGuard', () => { describe('EditSongGuard', () => {
@@ -11,6 +10,22 @@ describe('EditSongGuard', () => {
}); });
it('should be created', () => { 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

@@ -1,27 +1,31 @@
<app-card *ngIf="song" [heading]="song.number + ' bearbeiten'" closeLink="../"> @if (song) {
<app-card [heading]="song.number + ' bearbeiten'" closeLink="../">
<form [formGroup]="form" class="form"> <form [formGroup]="form" class="form">
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Titel</mat-label> <mat-label>Titel</mat-label>
<input formControlName="title" matInput /> <input formControlName="title" matInput />
</mat-form-field> </mat-form-field>
<div class="fourth"> <div class="fourth">
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Typ</mat-label> <mat-label>Typ</mat-label>
<mat-select formControlName="type"> <mat-select formControlName="type">
<mat-option *ngFor="let type of types" [value]="type">{{ @for (type of types; track type) {
<mat-option [value]="type">{{
type | songType type | songType
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Tonart</mat-label> <mat-label>Tonart</mat-label>
<mat-select formControlName="key"> <mat-select formControlName="key">
<mat-option *ngFor="let key of keys" [value]="key">{{ @for (key of keys; track key) {
<mat-option [value]="key">{{
key | key key | key
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
@@ -31,14 +35,15 @@
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Status</mat-label> <mat-label>Status</mat-label>
<mat-select formControlName="status"> <mat-select formControlName="status">
<mat-option *ngFor="let status of status" [value]="status">{{ @for (status of status; track status) {
<mat-option [value]="status">{{
status | status status | status
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Songtext</mat-label> <mat-label>Songtext</mat-label>
<textarea <textarea
@@ -49,9 +54,26 @@
matInput matInput
></textarea> ></textarea>
</mat-form-field> </mat-form-field>
<div *ngIf="songtextFocus" class="song-text-help"> @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> <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> <h3>Hinweise zur Bearbeitung</h3>
<h4>Aufbau</h4> <h4>Aufbau</h4>
Der Liedtext wird hintereinander weg geschrieben. Dabei werden Strophen, Der Liedtext wird hintereinander weg geschrieben. Dabei werden Strophen,
@@ -59,10 +81,8 @@
<pre> <pre>
Strophe Strophe
Text der ersten Strophe Text der ersten Strophe
Strophe Strophe
Text der zweiten Strophe Text der zweiten Strophe
Refrain Refrain
Und hier der Refrain Und hier der Refrain
</pre> </pre>
@@ -87,7 +107,7 @@
sed diam nonumy eirmod tempor invidunt ut labore et dolore sed diam nonumy eirmod tempor invidunt ut labore et dolore
</pre> </pre>
</div> </div>
}
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Kommentar</mat-label> <mat-label>Kommentar</mat-label>
<textarea <textarea
@@ -96,17 +116,17 @@
matInput matInput
></textarea> ></textarea>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-chip-grid #chipList> <mat-chip-grid #chipList>
@for (flag of flags; track flag) {
<mat-chip-row <mat-chip-row
(removed)="removeFlag(flag)" (removed)="removeFlag(flag)"
*ngFor="let flag of flags"
[removable]="true" [removable]="true"
> >
{{ flag }}&nbsp; {{ flag }}&nbsp;
<fa-icon (click)="removeFlag(flag)" [icon]="faRemove"></fa-icon> <fa-icon (click)="removeFlag(flag)" [icon]="faRemove"></fa-icon>
</mat-chip-row> </mat-chip-row>
}
<input <input
(matChipInputTokenEnd)="addFlag($event)" (matChipInputTokenEnd)="addFlag($event)"
[matChipInputAddOnBlur]="true" [matChipInputAddOnBlur]="true"
@@ -116,33 +136,34 @@
/> />
</mat-chip-grid> </mat-chip-grid>
</mat-form-field> </mat-form-field>
<div class="half"> <div class="half">
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Rechtlicher Status</mat-label> <mat-label>Rechtlicher Status</mat-label>
<mat-select formControlName="legalType"> <mat-select formControlName="legalType">
<mat-option *ngFor="let key of legalType" [value]="key">{{ @for (key of legalType; track key) {
<mat-option [value]="key">{{
key | legalType key | legalType
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Rechteinhaber</mat-label> <mat-label>Rechteinhaber</mat-label>
<mat-select formControlName="legalOwner"> <mat-select formControlName="legalOwner">
<mat-option *ngFor="let key of legalOwner" [value]="key">{{ @for (key of legalOwner; track key) {
<mat-option [value]="key">{{
key | legalOwner key | legalOwner
}} }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Rechteinhaber ID (z.B. CCLI Liednummer)</mat-label> <mat-label>Rechteinhaber ID (z.B. CCLI Liednummer)</mat-label>
<input formControlName="legalOwnerId" matInput /> <input formControlName="legalOwnerId" matInput />
@if (form.value.legalOwner === 'CCLI') {
<a <a
*ngIf="form.value.legalOwner === 'CCLI'"
class="link-ccli" class="link-ccli"
href="https://songselect.ccli.com/Songs/{{ form.value.legalOwnerId }}" href="https://songselect.ccli.com/Songs/{{ form.value.legalOwnerId }}"
matSuffix matSuffix
@@ -154,31 +175,28 @@
> >
<fa-icon [icon]="faLink"></fa-icon> <fa-icon [icon]="faLink"></fa-icon>
</a> </a>
}
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Künstler</mat-label> <mat-label>Künstler</mat-label>
<input formControlName="artist" matInput /> <input formControlName="artist" matInput />
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Verlag / Copyright</mat-label> <mat-label>Verlag / Copyright</mat-label>
<input formControlName="label" matInput /> <input formControlName="label" matInput />
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Nutzungsbedingungen</mat-label> <mat-label>Nutzungsbedingungen</mat-label>
<input formControlName="termsOfUse" matInput /> <input formControlName="termsOfUse" matInput />
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>abweichende Quelle</mat-label> <mat-label>abweichende Quelle</mat-label>
<input formControlName="origin" matInput /> <input formControlName="origin" matInput />
</mat-form-field> </mat-form-field>
</div> </div>
</form> </form>
<app-button-row> <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-button-row>
</app-card> </app-card>
}

View File

@@ -4,6 +4,7 @@
> * { > * {
width: 100%; width: 100%;
box-sizing: border-box;
} }
.fourth { .fourth {
@@ -43,3 +44,30 @@ h4 {
.song-text-help { .song-text-help {
font-size: 11px; 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

@@ -1,17 +1,20 @@
import {Component, OnInit} from '@angular/core'; import {Component, OnInit, inject} from '@angular/core';
import {Song} from '../../../services/song'; import {Song} from '../../../services/song';
import {ReactiveFormsModule, UntypedFormGroup} from '@angular/forms'; import {ReactiveFormsModule, UntypedFormGroup} from '@angular/forms';
import {ActivatedRoute, Router, RouterStateSnapshot} from '@angular/router'; import {ActivatedRoute, Router, RouterStateSnapshot} from '@angular/router';
import {SongService} from '../../../services/song.service'; import {SongService} from '../../../services/song.service';
import {EditService} from '../edit.service'; import {EditService} from '../edit.service';
import {first, map, switchMap} from 'rxjs/operators'; import {first, map, switchMap} from 'rxjs/operators';
import {startWith} from 'rxjs';
import {KEYS} from '../../../services/key.helper'; import {KEYS} from '../../../services/key.helper';
import {COMMA, ENTER} from '@angular/cdk/keycodes'; import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {MatChipGrid, MatChipInput, MatChipInputEvent, MatChipRow} from '@angular/material/chips'; import {MatChipGrid, MatChipInput, MatChipInputEvent, MatChipRow} from '@angular/material/chips';
import {faExternalLinkAlt, faSave, faTimesCircle} from '@fortawesome/free-solid-svg-icons'; import {faExternalLinkAlt, faSave, faTimesCircle} from '@fortawesome/free-solid-svg-icons';
import {MatDialog} from '@angular/material/dialog'; import {MatDialog} from '@angular/material/dialog';
import {SaveDialogComponent} from './save-dialog/save-dialog.component'; import {SaveDialogComponent} from './save-dialog/save-dialog.component';
import {NgFor, NgIf} from '@angular/common'; import {TextRenderingService} from '../../../services/text-rendering.service';
import {ChordValidationIssue} from '../../../services/chord';
import {CardComponent} from '../../../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../../../widget-modules/components/card/card.component';
import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field'; import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field';
import {MatInput} from '@angular/material/input'; import {MatInput} from '@angular/material/input';
@@ -34,14 +37,12 @@ import {StatusPipe} from '../../../../../widget-modules/pipes/status-translater/
templateUrl: './edit-song.component.html', templateUrl: './edit-song.component.html',
styleUrls: ['./edit-song.component.less'], styleUrls: ['./edit-song.component.less'],
imports: [ imports: [
NgIf,
CardComponent, CardComponent,
ReactiveFormsModule, ReactiveFormsModule,
MatFormField, MatFormField,
MatLabel, MatLabel,
MatInput, MatInput,
MatSelect, MatSelect,
NgFor,
MatOption, MatOption,
CdkTextareaAutosize, CdkTextareaAutosize,
SongTextComponent, SongTextComponent,
@@ -61,6 +62,13 @@ import {StatusPipe} from '../../../../../widget-modules/pipes/status-translater/
], ],
}) })
export class EditSongComponent implements OnInit { export class EditSongComponent implements OnInit {
private activatedRoute = inject(ActivatedRoute);
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; public song: Song | null = null;
public form: UntypedFormGroup = new UntypedFormGroup({}); public form: UntypedFormGroup = new UntypedFormGroup({});
public keys = KEYS; public keys = KEYS;
@@ -74,14 +82,7 @@ export class EditSongComponent implements OnInit {
public faSave = faSave; public faSave = faSave;
public faLink = faExternalLinkAlt; public faLink = faExternalLinkAlt;
public songtextFocus = false; public songtextFocus = false;
public chordValidationIssues: ChordValidationIssue[] = [];
public constructor(
private activatedRoute: ActivatedRoute,
private songService: SongService,
private editService: EditService,
private router: Router,
public dialog: MatDialog
) {}
public ngOnInit(): void { public ngOnInit(): void {
this.activatedRoute.params this.activatedRoute.params
@@ -96,12 +97,15 @@ export class EditSongComponent implements OnInit {
if (!song) return; if (!song) return;
this.form = this.editService.createSongForm(song); this.form = this.editService.createSongForm(song);
this.form.controls.flags.valueChanges.subscribe(_ => this.onFlagsChanged(_ as string)); 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); this.onFlagsChanged(this.form.controls.flags.value as string);
}); });
} }
public async onSave(): Promise<void> { public async onSave(): Promise<void> {
if (!this.song) return; if (!this.song || this.form.invalid) return;
const data = this.form.value as Partial<Song>; const data = this.form.value as Partial<Song>;
await this.songService.update$(this.song.id, data); await this.songService.update$(this.song.id, data);
this.form.markAsPristine(); this.form.markAsPristine();
@@ -153,8 +157,23 @@ export class EditSongComponent implements OnInit {
this.flags = flagArray.split(';').filter(_ => !!_); 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) { 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>; const data = this.form.value as Partial<Song>;
await this.songService.update$(this.song.id, data); await this.songService.update$(this.song.id, data);
} }

View File

@@ -8,7 +8,7 @@ describe('SaveDialogComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
void TestBed.configureTestingModule({ void TestBed.configureTestingModule({
declarations: [SaveDialogComponent], imports: [SaveDialogComponent],
}).compileComponents(); }).compileComponents();
})); }));

View File

@@ -1,12 +1,74 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {EditService} from './edit.service'; import {EditService} from './edit.service';
describe('EditService', () => { describe('EditService', () => {
beforeEach(() => void TestBed.configureTestingModule({})); let service: EditService;
beforeEach(() => {
void TestBed.configureTestingModule({});
service = TestBed.inject(EditService);
});
it('should be created', () => { it('should be created', () => {
const service: EditService = TestBed.inject(EditService); expect(service).toBeTruthy();
void 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');
}); });
}); });

Some files were not shown because too many files have changed in this diff Show More